id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_bad_1592_0
/* abrt-hook-ccpp.cpp - the hook for C/C++ crashing program Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com) Copyright (C) 2009 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/utsname.h> #include "libabrt.h" #define DUMP_SUID_UNSAFE 1 #define DUMP_SUID_SAFE 2 /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) static char* malloc_readlink(const char *linkname) { char buf[PATH_MAX + 1]; int len; len = readlink(linkname, buf, sizeof(buf)-1); if (len >= 0) { buf[len] = '\0'; return xstrdup(buf); } return NULL; } /* Custom version of copyfd_xyz, * one which is able to write into two descriptors at once. */ #define CONFIG_FEATURE_COPYBUF_KB 4 static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; //TODO: truncate to 0 or even delete the second file //(currently we delete the file later) } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } /* Global data */ static char *user_pwd; static char *proc_pid_status; static struct dump_dir *dd; static int user_core_fd = -1; /* * %s - signal number * %c - ulimit -c value * %p - pid * %u - uid * %g - gid * %t - UNIX time of dump * %e - executable filename * %h - hostname * %% - output one "%" */ /* Hook must be installed with exactly the same sequence of %c specifiers. * Last one, %h, may be omitted (we can find it out). */ static const char percent_specifiers[] = "%scpugteh"; static char *core_basename = (char*) "core"; /* * Used for error messages only. * It is either the same as core_basename if it is absolute, * or $PWD/core_basename. */ static char *full_core_basename; static char* get_executable(pid_t pid, int *fd_p) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); if (fd_p) *fd_p = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ char *executable = malloc_readlink(buf); if (!executable) return NULL; /* find and cut off " (deleted)" from the path */ char *deleted = executable + strlen(executable) - strlen(" (deleted)"); if (deleted > executable && strcmp(deleted, " (deleted)") == 0) { *deleted = '\0'; log("File '%s' seems to be deleted", executable); } /* find and cut off prelink suffixes from the path */ char *prelink = executable + strlen(executable) - strlen(".#prelink#.XXXXXX"); if (prelink > executable && strncmp(prelink, ".#prelink#.", strlen(".#prelink#.")) == 0) { log("File '%s' seems to be a prelink temporary file", executable); *prelink = '\0'; } return executable; } static char* get_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); return malloc_readlink(buf); } static char* get_rootdir(pid_t pid) { char buf[sizeof("/proc/%lu/root") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/root", (long)pid); return malloc_readlink(buf); } static int get_fsuid(void) { int real, euid, saved; /* if we fail to parse the uid, then make it root only readable to be safe */ int fs_uid = 0; char *line = proc_pid_status; /* never NULL */ for (;;) { if (strncmp(line, "Uid", 3) == 0) { int n = sscanf(line, "Uid:\t%d\t%d\t%d\t%d\n", &real, &euid, &saved, &fs_uid); if (n != 4) { perror_msg_and_die("Can't parse Uid: line"); } break; } line = strchr(line, '\n'); if (!line) break; line++; } return fs_uid; } static int dump_suid_policy() { /* - values are: 0 - don't dump suided programs - in this case the hook is not called by kernel 1 - create coredump readable by fs_uid 2 - create coredump readable by root only */ int c; int suid_dump_policy = 0; const char *filename = "/proc/sys/fs/suid_dumpable"; FILE *f = fopen(filename, "r"); if (!f) { log("Can't open %s", filename); return suid_dump_policy; } c = fgetc(f); fclose(f); if (c != EOF) suid_dump_policy = c - '0'; //log("suid dump policy is: %i", suid_dump_policy); return suid_dump_policy; } static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values) { errno = 0; if (user_pwd == NULL || chdir(user_pwd) != 0 ) { perror_msg("Can't cd to '%s'", user_pwd); return -1; } struct passwd* pw = getpwuid(uid); gid_t gid = pw ? pw->pw_gid : uid; //log("setting uid: %i gid: %i", uid, gid); xsetegid(gid); xseteuid(fsuid); if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } full_core_basename = core_basename; if (core_basename[0] != '/') core_basename = concat_path_file(user_pwd, core_basename); /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ struct stat sb; errno = 0; /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ int user_core_fd = open(core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW, 0600); /* kernel makes 0600 too */ xsetegid(0); xseteuid(0); if (user_core_fd < 0 || fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 /* kernel internal dumper checks this too: if (inode->i_uid != current->fsuid) <fail>, need to mimic? */ ) { if (user_core_fd < 0) perror_msg("Can't open '%s'", full_core_basename); else perror_msg("'%s' is not a regular file with link count 1", full_core_basename); return -1; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' to size 0", full_core_basename); unlink(core_basename); return -1; } return user_core_fd; } static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } fclose(fp); return true; } /* Like xopen, but on error, unlocks and deletes dd and user core */ static int create_or_die(const char *filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, DEFAULT_DUMP_DIR_MODE); if (fd >= 0) { IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid)); return fd; } int sv_errno = errno; if (dd) dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } errno = sv_errno; perror_msg_and_die("Can't open '%s'", filename); } int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, "/") != 0) ? rootdir : NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file(source_filename, dest_filename, 0640); //chown(dest_filename, dd->dd_uid, dd->dd_gid); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE); IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid)); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE); IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid)); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE); IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid)); strcpy(dest_base, FILENAME_OPEN_FDS); if (dump_fd_info(dest_filename, source_filename, source_base_ofs)) IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid)); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s'", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size); } return 0; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1592_0
crossvul-cpp_data_bad_825_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-59/c/bad_825_0
crossvul-cpp_data_bad_3262_0
/* * ProFTPD - FTP server daemon * Copyright (c) 1997, 1998 Public Flood Software * Copyright (c) 1999, 2000 MacGyver aka Habeeb J. Dihu <macgyver@tos.net> * Copyright (c) 2001-2016 The ProFTPD Project team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. * * As a special exemption, Public Flood Software/MacGyver aka Habeeb J. Dihu * and other respective copyright holders give permission to link this program * with OpenSSL, and distribute the resulting executable, without including * the source code for OpenSSL in the source distribution. */ /* Authentication module for ProFTPD */ #include "conf.h" #include "privs.h" extern pid_t mpid; module auth_module; #ifdef PR_USE_LASTLOG static unsigned char lastlog = FALSE; #endif /* PR_USE_LASTLOG */ static unsigned char mkhome = FALSE; static unsigned char authenticated_without_pass = FALSE; static int TimeoutLogin = PR_TUNABLE_TIMEOUTLOGIN; static int logged_in = 0; static int auth_tries = 0; static char *auth_pass_resp_code = R_230; static pr_fh_t *displaylogin_fh = NULL; static int TimeoutSession = 0; static int auth_scan_scoreboard(void); static int auth_count_scoreboard(cmd_rec *, char *); /* auth_cmd_chk_cb() is hooked into the main server's auth_hook function, * so that we can deny all commands until authentication is complete. * * Note: Once this function returns true (i.e. client has authenticated), * it will ALWAYS return true. At least until REIN is implemented. Thus * we have a flag for such a situation, to save on redundant lookups for * the "authenticated" record. */ static int auth_have_authenticated = FALSE; static int auth_cmd_chk_cb(cmd_rec *cmd) { if (auth_have_authenticated == FALSE) { unsigned char *authd; authd = get_param_ptr(cmd->server->conf, "authenticated", FALSE); if (authd == NULL || *authd == FALSE) { pr_response_send(R_530, _("Please login with USER and PASS")); return FALSE; } auth_have_authenticated = TRUE; } return TRUE; } static int auth_login_timeout_cb(CALLBACK_FRAME) { pr_response_send_async(R_421, _("Login timeout (%d %s): closing control connection"), TimeoutLogin, TimeoutLogin != 1 ? "seconds" : "second"); /* It's possible that any listeners of this event might terminate the * session process themselves (e.g. mod_ban). So write out that the * TimeoutLogin has been exceeded to the log here, in addition to the * scheduled session exit message. */ pr_log_pri(PR_LOG_NOTICE, "%s", "Login timeout exceeded, disconnected"); pr_event_generate("core.timeout-login", NULL); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT, "TimeoutLogin"); /* Do not restart the timer (should never be reached). */ return 0; } static int auth_session_timeout_cb(CALLBACK_FRAME) { pr_event_generate("core.timeout-session", NULL); pr_response_send_async(R_421, _("Session Timeout (%d seconds): closing control connection"), TimeoutSession); pr_log_pri(PR_LOG_NOTICE, "%s", "FTP session timed out, disconnected"); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT, "TimeoutSession"); /* no need to restart the timer -- session's over */ return 0; } /* Event listeners */ static void auth_exit_ev(const void *event_data, void *user_data) { /* Close the scoreboard descriptor that we opened. */ (void) pr_close_scoreboard(FALSE); } static int auth_sess_init(void) { config_rec *c = NULL; unsigned char *tmp = NULL; int res = 0; /* Check for a server-specific TimeoutLogin */ c = find_config(main_server->conf, CONF_PARAM, "TimeoutLogin", FALSE); if (c != NULL) { TimeoutLogin = *((int *) c->argv[0]); } /* Start the login timer */ if (TimeoutLogin) { pr_timer_remove(PR_TIMER_LOGIN, &auth_module); pr_timer_add(TimeoutLogin, PR_TIMER_LOGIN, &auth_module, auth_login_timeout_cb, "TimeoutLogin"); } PRIVS_ROOT res = pr_open_scoreboard(O_RDWR); PRIVS_RELINQUISH if (res < 0) { switch (res) { case PR_SCORE_ERR_BAD_MAGIC: pr_log_debug(DEBUG0, "error opening scoreboard: bad/corrupted file"); break; case PR_SCORE_ERR_OLDER_VERSION: pr_log_debug(DEBUG0, "error opening scoreboard: bad version (too old)"); break; case PR_SCORE_ERR_NEWER_VERSION: pr_log_debug(DEBUG0, "error opening scoreboard: bad version (too new)"); break; default: pr_log_debug(DEBUG0, "error opening scoreboard: %s", strerror(errno)); break; } } pr_event_register(&auth_module, "core.exit", auth_exit_ev, NULL); /* Create an entry in the scoreboard for this session, if we don't already * have one. */ if (pr_scoreboard_entry_get(PR_SCORE_CLIENT_ADDR) == NULL) { if (pr_scoreboard_entry_add() < 0) { pr_log_pri(PR_LOG_NOTICE, "notice: unable to add scoreboard entry: %s", strerror(errno)); } pr_scoreboard_entry_update(session.pid, PR_SCORE_USER, "(none)", PR_SCORE_SERVER_PORT, main_server->ServerPort, PR_SCORE_SERVER_ADDR, session.c->local_addr, session.c->local_port, PR_SCORE_SERVER_LABEL, main_server->ServerName, PR_SCORE_CLIENT_ADDR, session.c->remote_addr, PR_SCORE_CLIENT_NAME, session.c->remote_name, PR_SCORE_CLASS, session.conn_class ? session.conn_class->cls_name : "", PR_SCORE_PROTOCOL, "ftp", PR_SCORE_BEGIN_SESSION, time(NULL), NULL); } else { /* We're probably handling a HOST comand, and the server changed; just * update the SERVER_LABEL field. */ pr_scoreboard_entry_update(session.pid, PR_SCORE_SERVER_LABEL, main_server->ServerName, NULL); } /* Should we create the home for a user, if they don't have one? */ tmp = get_param_ptr(main_server->conf, "CreateHome", FALSE); if (tmp != NULL && *tmp == TRUE) { mkhome = TRUE; } else { mkhome = FALSE; } #ifdef PR_USE_LASTLOG /* Use the lastlog file, if supported and requested. */ tmp = get_param_ptr(main_server->conf, "UseLastlog", FALSE); if (tmp && *tmp == TRUE) { lastlog = TRUE; } else { lastlog = FALSE; } #endif /* PR_USE_LASTLOG */ /* Scan the scoreboard now, in order to tally up certain values for * substituting in any of the Display* file variables. This function * also performs the MaxConnectionsPerHost enforcement. */ auth_scan_scoreboard(); return 0; } static int auth_init(void) { /* Add the commands handled by this module to the HELP list. */ pr_help_add(C_USER, _("<sp> username"), TRUE); pr_help_add(C_PASS, _("<sp> password"), TRUE); pr_help_add(C_ACCT, _("is not implemented"), FALSE); pr_help_add(C_REIN, _("is not implemented"), FALSE); /* By default, enable auth checking */ set_auth_check(auth_cmd_chk_cb); return 0; } static int _do_auth(pool *p, xaset_t *conf, char *u, char *pw) { char *cpw = NULL; config_rec *c; if (conf) { c = find_config(conf, CONF_PARAM, "UserPassword", FALSE); while (c) { if (strcmp(c->argv[0], u) == 0) { cpw = (char *) c->argv[1]; break; } c = find_config_next(c, c->next, CONF_PARAM, "UserPassword", FALSE); } } if (cpw) { if (pr_auth_getpwnam(p, u) == NULL) { int xerrno = errno; if (xerrno == ENOENT) { pr_log_pri(PR_LOG_NOTICE, "no such user '%s'", u); } errno = xerrno; return PR_AUTH_NOPWD; } return pr_auth_check(p, cpw, u, pw); } return pr_auth_authenticate(p, u, pw); } /* Command handlers */ MODRET auth_post_host(cmd_rec *cmd) { /* If the HOST command changed the main_server pointer, reinitialize * ourselves. */ if (session.prev_server != NULL) { int res; /* Remove the TimeoutLogin timer. */ pr_timer_remove(PR_TIMER_LOGIN, &auth_module); pr_event_unregister(&auth_module, "core.exit", auth_exit_ev); /* Reset the CreateHome setting. */ mkhome = FALSE; #ifdef PR_USE_LASTLOG /* Reset the UseLastLog setting. */ lastlog = FALSE; #endif /* PR_USE_LASTLOG */ res = auth_sess_init(); if (res < 0) { pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_SESSION_INIT_FAILED, NULL); } } return PR_DECLINED(cmd); } MODRET auth_err_pass(cmd_rec *cmd) { /* Remove the stashed original USER name here in a LOG_CMD_ERR handler, so * that other modules, who may want to lookup the original USER parameter on * a failed login in an earlier command handler phase, have a chance to do * so. This removal of the USER parameter on failure was happening directly * in the CMD handler previously, thus preventing POST_CMD_ERR handlers from * using USER. */ pr_table_remove(session.notes, "mod_auth.orig-user", NULL); return PR_HANDLED(cmd); } MODRET auth_log_pass(cmd_rec *cmd) { size_t passwd_len; /* Only log, to the syslog, that the login has succeeded here, where we * know that the login has definitely succeeded. */ pr_log_auth(PR_LOG_INFO, "%s %s: Login successful.", (session.anon_config != NULL) ? "ANON" : C_USER, session.user); if (cmd->arg != NULL) { /* And scrub the memory holding the password sent by the client, for * safety/security. */ passwd_len = strlen(cmd->arg); pr_memscrub(cmd->arg, passwd_len); } return PR_DECLINED(cmd); } MODRET auth_post_pass(cmd_rec *cmd) { config_rec *c = NULL; char *grantmsg = NULL, *user; unsigned int ctxt_precedence = 0; unsigned char have_user_timeout, have_group_timeout, have_class_timeout, have_all_timeout, *root_revoke = NULL, *authenticated; struct stat st; /* Was there a precending USER command? Was the client successfully * authenticated? */ authenticated = get_param_ptr(cmd->server->conf, "authenticated", FALSE); /* Clear the list of auth-only modules. */ pr_auth_clear_auth_only_modules(); if (authenticated != NULL && *authenticated == TRUE) { /* At this point, we can look up the Protocols config if the client * has been authenticated, which may have been tweaked via mod_ifsession's * user/group/class-specific sections. */ c = find_config(main_server->conf, CONF_PARAM, "Protocols", FALSE); if (c) { register unsigned int i; array_header *protocols; char **elts; const char *protocol; protocols = c->argv[0]; elts = protocols->elts; protocol = pr_session_get_protocol(PR_SESS_PROTO_FL_LOGOUT); /* We only want to check for 'ftp' in the configured Protocols list * if a) a RFC2228 mechanism (e.g. SSL or GSS) is not in use, and * b) an SSH protocol is not in use. */ if (session.rfc2228_mech == NULL && strncmp(protocol, "SSH2", 5) != 0) { int allow_ftp = FALSE; for (i = 0; i < protocols->nelts; i++) { char *proto; proto = elts[i]; if (proto != NULL) { if (strncasecmp(proto, "ftp", 4) == 0) { allow_ftp = TRUE; break; } } } if (!allow_ftp) { pr_log_debug(DEBUG0, "%s", "ftp protocol denied by Protocols config"); pr_response_send(R_530, "%s", _("Login incorrect.")); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by Protocols setting"); } } } } user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); /* Count up various quantities in the scoreboard, checking them against * the Max* limits to see if the session should be barred from going * any further. */ auth_count_scoreboard(cmd, session.user); /* Check for dynamic configuration. This check needs to be after the * setting of any possible anon_config, as that context may be allowed * or denied .ftpaccess-parsing separately from the containing server. */ if (pr_fsio_stat(session.cwd, &st) != -1) build_dyn_config(cmd->tmp_pool, session.cwd, &st, TRUE); have_user_timeout = have_group_timeout = have_class_timeout = have_all_timeout = FALSE; c = find_config(TOPLEVEL_CONF, CONF_PARAM, "TimeoutSession", FALSE); while (c != NULL) { pr_signals_handle(); if (c->argc == 3) { if (strncmp(c->argv[1], "user", 5) == 0) { if (pr_expr_eval_user_or((char **) &c->argv[2]) == TRUE) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_group_timeout = have_class_timeout = have_all_timeout = FALSE; have_user_timeout = TRUE; } } } else if (strncmp(c->argv[1], "group", 6) == 0) { if (pr_expr_eval_group_and((char **) &c->argv[2]) == TRUE) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_class_timeout = have_all_timeout = FALSE; have_group_timeout = TRUE; } } } else if (strncmp(c->argv[1], "class", 6) == 0) { if (session.conn_class != NULL && strcmp(session.conn_class->cls_name, c->argv[2]) == 0) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_group_timeout = have_all_timeout = FALSE; have_class_timeout = TRUE; } } } } else { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_group_timeout = have_class_timeout = FALSE; have_all_timeout = TRUE; } } c = find_config_next(c, c->next, CONF_PARAM, "TimeoutSession", FALSE); } /* If configured, start a session timer. The timer ID value for * session timers will not be #defined, as I think that is a bad approach. * A better mechanism would be to use the random timer ID generation, and * store the returned ID in order to later remove the timer. */ if (have_user_timeout || have_group_timeout || have_class_timeout || have_all_timeout) { pr_log_debug(DEBUG4, "setting TimeoutSession of %d seconds for current %s", TimeoutSession, have_user_timeout ? "user" : have_group_timeout ? "group" : have_class_timeout ? "class" : "all"); pr_timer_add(TimeoutSession, PR_TIMER_SESSION, &auth_module, auth_session_timeout_cb, "TimeoutSession"); } /* Handle a DisplayLogin file. */ if (displaylogin_fh) { if (!(session.sf_flags & SF_ANON)) { if (pr_display_fh(displaylogin_fh, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin_fh->fh_path, strerror(errno)); } pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } else { /* We're an <Anonymous> login, but there was a previous DisplayLogin * configured which was picked up earlier. Close that filehandle, * and look for a new one. */ char *displaylogin; pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin) { if (pr_display_file(displaylogin, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } } } } else { char *displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin) { if (pr_display_file(displaylogin, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } } } grantmsg = get_param_ptr(TOPLEVEL_CONF, "AccessGrantMsg", FALSE); if (grantmsg == NULL) { /* Append the final greeting lines. */ if (session.sf_flags & SF_ANON) { pr_response_add(auth_pass_resp_code, "%s", _("Anonymous access granted, restrictions apply")); } else { pr_response_add(auth_pass_resp_code, _("User %s logged in"), user); } } else { /* Handle any AccessGrantMsg directive. */ grantmsg = sreplace(cmd->tmp_pool, grantmsg, "%u", user, NULL); pr_response_add(auth_pass_resp_code, "%s", grantmsg); } /* A RootRevoke value of 0 indicates 'false', 1 indicates 'true', and * 2 indicates 'NonCompliantActiveTransfer'. We will drop root privs for any * RootRevoke value greater than 0. */ root_revoke = get_param_ptr(TOPLEVEL_CONF, "RootRevoke", FALSE); if (root_revoke != NULL && *root_revoke > 0) { pr_signals_block(); PRIVS_ROOT PRIVS_REVOKE pr_signals_unblock(); /* Disable future attempts at UID/GID manipulation. */ session.disable_id_switching = TRUE; if (*root_revoke == 1) { /* If the server's listening port is less than 1024, block PORT * commands (effectively allowing only passive connections, which is * not necessarily a Bad Thing). Only log this here -- the blocking * will need to occur in mod_core's handling of the PORT/EPRT commands. */ if (session.c->local_port < 1024) { pr_log_debug(DEBUG0, "RootRevoke in effect, active data transfers may not succeed"); } } pr_log_debug(DEBUG0, "RootRevoke in effect, dropped root privs"); } return PR_DECLINED(cmd); } /* Handle group based authentication, only checked if pw * based fails */ static config_rec *_auth_group(pool *p, char *user, char **group, char **ournamep, char **anonnamep, char *pass) { config_rec *c; char *ourname = NULL,*anonname = NULL; char **grmem; struct group *grp; ourname = (char*)get_param_ptr(main_server->conf,"UserName",FALSE); if (ournamep && ourname) *ournamep = ourname; c = find_config(main_server->conf, CONF_PARAM, "GroupPassword", TRUE); if (c) do { grp = pr_auth_getgrnam(p, c->argv[0]); if (!grp) continue; for (grmem = grp->gr_mem; *grmem; grmem++) if (strcmp(*grmem, user) == 0) { if (pr_auth_check(p, c->argv[1], user, pass) == 0) break; } if (*grmem) { if (group) *group = c->argv[0]; if (c->parent) c = c->parent; if (c->config_type == CONF_ANON) anonname = (char*)get_param_ptr(c->subset,"UserName",FALSE); if (anonnamep) *anonnamep = anonname; if (anonnamep && !anonname && ourname) *anonnamep = ourname; break; } } while((c = find_config_next(c,c->next,CONF_PARAM,"GroupPassword",TRUE)) != NULL); return c; } /* Determine any applicable chdirs */ static char *get_default_chdir(pool *p, xaset_t *conf) { config_rec *c; char *dir = NULL; int ret; c = find_config(conf, CONF_PARAM, "DefaultChdir", FALSE); while (c) { /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } ret = pr_expr_eval_group_and(((char **) c->argv)+1); if (ret) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultChdir", FALSE); } /* If the directory is relative, concatenate w/ session.cwd. */ if (dir && *dir != '/' && *dir != '~') dir = pdircat(p, session.cwd, dir, NULL); /* Check for any expandable variables. */ if (dir) dir = path_subst_uservar(p, &dir); return dir; } /* Determine if the user (non-anon) needs a default root dir other than /. */ static int get_default_root(pool *p, int allow_symlinks, char **root) { config_rec *c = NULL; char *dir = NULL; int res; c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE); while (c) { pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE); } if (dir) { char *new_dir; /* Check for any expandable variables. */ new_dir = path_subst_uservar(p, &dir); if (new_dir != NULL) { dir = new_dir; } if (strncmp(dir, "/", 2) == 0) { dir = NULL; } else { char *realdir; int xerrno = 0; if (allow_symlinks == FALSE) { char *path, target_path[PR_TUNABLE_PATH_MAX + 1]; struct stat st; size_t pathlen; /* First, deal with any possible interpolation. dir_realpath() will * do this for us, but dir_realpath() ALSO automatically follows * symlinks, which is what we do NOT want to do here. */ path = dir; if (*path != '/') { if (*path == '~') { if (pr_fs_interpolate(dir, target_path, sizeof(target_path)-1) < 0) { return -1; } path = target_path; } } /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ pathlen = strlen(path); if (pathlen > 1 && path[pathlen-1] == '/') { path[pathlen-1] = '\0'; } pr_fs_clear_cache(); res = pr_fsio_lstat(path, &st); if (res < 0) { xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path, strerror(xerrno)); errno = xerrno; return -1; } if (S_ISLNK(st.st_mode)) { pr_log_pri(PR_LOG_WARNING, "error: DefaultRoot %s is a symlink (denied by AllowChrootSymlinks " "config)", path); errno = EPERM; return -1; } } /* We need to be the final user here so that if the user has their home * directory with a mode the user proftpd is running (i.e. the User * directive) as can not traverse down, we can still have the default * root. */ PRIVS_USER realdir = dir_realpath(p, dir); xerrno = errno; PRIVS_RELINQUISH if (realdir) { dir = realdir; } else { /* Try to provide a more informative message. */ char interp_dir[PR_TUNABLE_PATH_MAX + 1]; memset(interp_dir, '\0', sizeof(interp_dir)); (void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1); pr_log_pri(PR_LOG_NOTICE, "notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s", dir, interp_dir, strerror(xerrno)); errno = xerrno; } } } *root = dir; return 0; } static struct passwd *passwd_dup(pool *p, struct passwd *pw) { struct passwd *npw; npw = pcalloc(p, sizeof(struct passwd)); npw->pw_name = pstrdup(p, pw->pw_name); npw->pw_passwd = pstrdup(p, pw->pw_passwd); npw->pw_uid = pw->pw_uid; npw->pw_gid = pw->pw_gid; npw->pw_gecos = pstrdup(p, pw->pw_gecos); npw->pw_dir = pstrdup(p, pw->pw_dir); npw->pw_shell = pstrdup(p, pw->pw_shell); return npw; } static void ensure_open_passwd(pool *p) { /* Make sure pass/group is open. */ pr_auth_setpwent(p); pr_auth_setgrent(p); /* On some unices the following is necessary to ensure the files * are open. (BSDI 3.1) */ pr_auth_getpwent(p); pr_auth_getgrent(p); } /* Next function (the biggie) handles all authentication, setting * up chroot() jail, etc. */ static int setup_env(pool *p, cmd_rec *cmd, char *user, char *pass) { struct passwd *pw; config_rec *c, *tmpc; char *origuser, *ourname = NULL, *anonname = NULL, *anongroup = NULL, *ugroup = NULL; char *defaulttransfermode, *defroot = NULL,*defchdir = NULL,*xferlog = NULL; const char *sess_ttyname; int aclp, i, res = 0, allow_chroot_symlinks = TRUE, showsymlinks; unsigned char *wtmp_log = NULL, *anon_require_passwd = NULL; /********************* Authenticate the user here *********************/ session.hide_password = TRUE; origuser = user; c = pr_auth_get_anon_config(p, &user, &ourname, &anonname); if (c) session.anon_config = c; if (!user) { pr_log_auth(PR_LOG_NOTICE, "USER %s: user is not a UserAlias from %s [%s] " "to %s:%i", origuser, session.c->remote_name, pr_netaddr_get_ipstr(session.c->remote_addr), pr_netaddr_get_ipstr(session.c->local_addr), session.c->local_port); goto auth_failure; } pw = pr_auth_getpwnam(p, user); if (pw == NULL && c != NULL && ourname != NULL) { /* If the client is authenticating using an alias (e.g. "AuthAliasOnly on"), * then we need to try checking using the real username, too (Bug#4255). */ pr_trace_msg("auth", 16, "no user entry found for <Anonymous> alias '%s', using '%s'", user, ourname); pw = pr_auth_getpwnam(p, ourname); } if (pw == NULL) { int auth_code = PR_AUTH_NOPWD; pr_log_auth(PR_LOG_NOTICE, "USER %s: no such user found from %s [%s] to %s:%i", user, session.c->remote_name, pr_netaddr_get_ipstr(session.c->remote_addr), pr_netaddr_get_ipstr(session.c->local_addr), session.c->local_port); pr_event_generate("mod_auth.authentication-code", &auth_code); goto auth_failure; } /* Security: other functions perform pw lookups, thus we need to make * a local copy of the user just looked up. */ pw = passwd_dup(p, pw); if (pw->pw_uid == PR_ROOT_UID) { unsigned char *root_allow = NULL; pr_event_generate("mod_auth.root-login", NULL); /* If RootLogin is set to true, we allow this... even though we * still log a warning. :) */ if ((root_allow = get_param_ptr(c ? c->subset : main_server->conf, "RootLogin", FALSE)) == NULL || *root_allow != TRUE) { if (pass) { pr_memscrub(pass, strlen(pass)); } pr_log_auth(PR_LOG_NOTICE, "SECURITY VIOLATION: Root login attempted"); return 0; } } session.user = pstrdup(p, pw->pw_name); session.group = pstrdup(p, pr_auth_gid2name(p, pw->pw_gid)); /* Set the login_uid and login_uid */ session.login_uid = pw->pw_uid; session.login_gid = pw->pw_gid; /* Check for any expandable variables in session.cwd. */ pw->pw_dir = path_subst_uservar(p, &pw->pw_dir); /* Before we check for supplemental groups, check to see if the locally * resolved name of the user, returned via auth_getpwnam(), is different * from the USER argument sent by the client. The name can change, since * auth modules can play all sorts of neat tricks on us. * * If the names differ, assume that any cached data in the session.gids * and session.groups lists are stale, and clear them out. */ if (strcmp(pw->pw_name, user) != 0) { pr_log_debug(DEBUG10, "local user name '%s' differs from client-sent " "user name '%s', clearing cached group data", pw->pw_name, user); session.gids = NULL; session.groups = NULL; } if (!session.gids && !session.groups) { /* Get the supplemental groups. Note that we only look up the * supplemental group credentials if we have not cached the group * credentials before, in session.gids and session.groups. * * Those credentials may have already been retrieved, as part of the * pr_auth_get_anon_config() call. */ res = pr_auth_getgroups(p, pw->pw_name, &session.gids, &session.groups); if (res < 1) { pr_log_debug(DEBUG2, "no supplemental groups found for user '%s'", pw->pw_name); } } tmpc = find_config(main_server->conf, CONF_PARAM, "AllowChrootSymlinks", FALSE); if (tmpc != NULL) { allow_chroot_symlinks = *((int *) tmpc->argv[0]); } /* If c != NULL from this point on, we have an anonymous login */ aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); if (c) { anongroup = get_param_ptr(c->subset, "GroupName", FALSE); if (!anongroup) anongroup = get_param_ptr(main_server->conf, "GroupName",FALSE); /* Check for configured AnonRejectPasswords regex here, and fail the login * if the given password matches the regex. */ #ifdef PR_USE_REGEX if ((tmpc = find_config(c->subset, CONF_PARAM, "AnonRejectPasswords", FALSE)) != NULL) { int re_res; pr_regex_t *pw_regex = (pr_regex_t *) tmpc->argv[0]; if (pw_regex && pass && ((re_res = pr_regexp_exec(pw_regex, pass, 0, NULL, 0, 0, 0)) == 0)) { char errstr[200] = {'\0'}; pr_regexp_error(re_res, pw_regex, errstr, sizeof(errstr)); pr_log_auth(PR_LOG_NOTICE, "ANON %s: AnonRejectPasswords denies login", origuser); pr_event_generate("mod_auth.anon-reject-passwords", session.c); goto auth_failure; } } #endif if (!login_check_limits(c->subset, FALSE, TRUE, &i) || (!aclp && !i) ){ pr_log_auth(PR_LOG_NOTICE, "ANON %s (Login failed): Limit access denies " "login", origuser); goto auth_failure; } } if (c == NULL && aclp == 0) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Limit access denies login", origuser); goto auth_failure; } if (c) { anon_require_passwd = get_param_ptr(c->subset, "AnonRequirePassword", FALSE); } if (!c || (anon_require_passwd && *anon_require_passwd == TRUE)) { int auth_code; char *user_name = user; if (c && origuser && strcasecmp(user, origuser) != 0) { unsigned char *auth_using_alias = get_param_ptr(c->subset, "AuthUsingAlias", FALSE); /* If 'AuthUsingAlias' set and we're logging in under an alias, * then auth using that alias. */ if (auth_using_alias && *auth_using_alias == TRUE) { user_name = origuser; pr_log_auth(PR_LOG_INFO, "ANON AUTH: User %s, authenticating using alias %s", user, user_name); } } /* It is possible for the user to have already been authenticated during * the handling of the USER command, as by an RFC2228 mechanism. If * that had happened, we won't need to call _do_auth() here. */ if (!authenticated_without_pass) { auth_code = _do_auth(p, c ? c->subset : main_server->conf, user_name, pass); } else { auth_code = PR_AUTH_OK_NO_PASS; } pr_event_generate("mod_auth.authentication-code", &auth_code); if (auth_code < 0) { /* Normal authentication has failed, see if group authentication * passes */ c = _auth_group(p, user, &anongroup, &ourname, &anonname, pass); if (c != NULL) { if (c->config_type != CONF_ANON) { c = NULL; ugroup = anongroup; anongroup = NULL; } auth_code = PR_AUTH_OK; } } if (pass) pr_memscrub(pass, strlen(pass)); if (session.auth_mech) pr_log_debug(DEBUG2, "user '%s' authenticated by %s", user, session.auth_mech); switch (auth_code) { case PR_AUTH_OK_NO_PASS: auth_pass_resp_code = R_232; break; case PR_AUTH_OK: auth_pass_resp_code = R_230; break; case PR_AUTH_NOPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): No such user found", user); goto auth_failure; case PR_AUTH_BADPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Incorrect password", origuser); goto auth_failure; case PR_AUTH_AGEPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Password expired", user); goto auth_failure; case PR_AUTH_DISABLEDPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Account disabled", user); goto auth_failure; default: break; }; /* Catch the case where we forgot to handle a bad auth code above. */ if (auth_code < 0) goto auth_failure; if (pw->pw_uid == PR_ROOT_UID) { pr_log_auth(PR_LOG_WARNING, "ROOT FTP login successful"); } } else if (c && (!anon_require_passwd || *anon_require_passwd == FALSE)) { session.hide_password = FALSE; } pr_auth_setgrent(p); res = pr_auth_is_valid_shell(c ? c->subset : main_server->conf, pw->pw_shell); if (res == FALSE) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Invalid shell: '%s'", user, pw->pw_shell); goto auth_failure; } res = pr_auth_banned_by_ftpusers(c ? c->subset : main_server->conf, pw->pw_name); if (res == TRUE) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): User in " PR_FTPUSERS_PATH, user); goto auth_failure; } if (c) { struct group *grp = NULL; unsigned char *add_userdir = NULL; char *u, *chroot_dir; u = pr_table_get(session.notes, "mod_auth.orig-user", NULL); add_userdir = get_param_ptr(c->subset, "UserDirRoot", FALSE); /* If resolving an <Anonymous> user, make sure that user's groups * are set properly for the check of the home directory path (which * depend on those supplemental group memberships). Additionally, * temporarily switch to the new user's uid. */ pr_signals_block(); PRIVS_ROOT res = set_groups(p, pw->pw_gid, session.gids); if (res < 0) { pr_log_pri(PR_LOG_WARNING, "error: unable to set groups: %s", strerror(errno)); } #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(pw->pw_uid, pw->pw_gid) if ((add_userdir && *add_userdir == TRUE) && strcmp(u, user) != 0) { chroot_dir = pdircat(p, c->name, u, NULL); } else { chroot_dir = c->name; } if (allow_chroot_symlinks == FALSE) { char *chroot_path, target_path[PR_TUNABLE_PATH_MAX+1]; struct stat st; chroot_path = chroot_dir; if (chroot_path[0] != '/') { if (chroot_path[0] == '~') { if (pr_fs_interpolate(chroot_path, target_path, sizeof(target_path)-1) == 0) { chroot_path = target_path; } else { chroot_path = NULL; } } } if (chroot_path != NULL) { size_t chroot_pathlen; /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ chroot_pathlen = strlen(chroot_path); if (chroot_pathlen > 1 && chroot_path[chroot_pathlen-1] == '/') { chroot_path[chroot_pathlen-1] = '\0'; } pr_fs_clear_cache(); res = pr_fsio_lstat(chroot_path, &st); if (res < 0) { int xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", chroot_path, strerror(xerrno)); errno = xerrno; chroot_path = NULL; } else { if (S_ISLNK(st.st_mode)) { pr_log_pri(PR_LOG_WARNING, "error: <Anonymous %s> is a symlink (denied by " "AllowChrootSymlinks config)", chroot_path); errno = EPERM; chroot_path = NULL; } } } if (chroot_path != NULL) { session.chroot_path = dir_realpath(p, chroot_dir); } else { session.chroot_path = NULL; } if (session.chroot_path == NULL) { pr_log_debug(DEBUG8, "error resolving '%s': %s", chroot_dir, strerror(errno)); } } else { session.chroot_path = dir_realpath(p, chroot_dir); if (session.chroot_path == NULL) { pr_log_debug(DEBUG8, "error resolving '%s': %s", chroot_dir, strerror(errno)); } } if (session.chroot_path && pr_fsio_access(session.chroot_path, X_OK, session.uid, session.gid, session.gids) != 0) { session.chroot_path = NULL; } else { session.chroot_path = pstrdup(session.pool, session.chroot_path); } /* Return all privileges back to that of the daemon, for now. */ PRIVS_ROOT res = set_groups(p, daemon_gid, daemon_gids); if (res < 0) { pr_log_pri(PR_LOG_ERR, "error: unable to set groups: %s", strerror(errno)); } #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(daemon_uid, daemon_gid) pr_signals_unblock(); /* Sanity check, make sure we have daemon_uid and daemon_gid back */ #ifdef HAVE_GETEUID if (getegid() != daemon_gid || geteuid() != daemon_uid) { PRIVS_RELINQUISH pr_log_pri(PR_LOG_WARNING, "switching IDs from user %s back to daemon uid/gid failed: %s", session.user, strerror(errno)); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL); } #endif /* HAVE_GETEUID */ if (anon_require_passwd && *anon_require_passwd == TRUE) { session.anon_user = pstrdup(session.pool, origuser); } else { session.anon_user = pstrdup(session.pool, pass); } if (!session.chroot_path) { pr_log_pri(PR_LOG_NOTICE, "%s: Directory %s is not accessible", session.user, c->name); pr_response_add_err(R_530, _("Unable to set anonymous privileges.")); goto auth_failure; } sstrncpy(session.cwd, "/", sizeof(session.cwd)); xferlog = get_param_ptr(c->subset, "TransferLog", FALSE); if (anongroup) { grp = pr_auth_getgrnam(p, anongroup); if (grp) { pw->pw_gid = grp->gr_gid; session.group = pstrdup(p, grp->gr_name); } } } else { struct group *grp; char *homedir; if (ugroup) { grp = pr_auth_getgrnam(p, ugroup); if (grp) { pw->pw_gid = grp->gr_gid; session.group = pstrdup(p, grp->gr_name); } } /* Attempt to resolve any possible symlinks. */ PRIVS_USER homedir = dir_realpath(p, pw->pw_dir); PRIVS_RELINQUISH if (homedir) sstrncpy(session.cwd, homedir, sizeof(session.cwd)); else sstrncpy(session.cwd, pw->pw_dir, sizeof(session.cwd)); } /* Create the home directory, if need be. */ if (!c && mkhome) { if (create_home(p, session.cwd, origuser, pw->pw_uid, pw->pw_gid) < 0) { /* NOTE: should this cause the login to fail? */ goto auth_failure; } } /* Get default chdir (if any) */ defchdir = get_default_chdir(p, (c ? c->subset : main_server->conf)); if (defchdir) sstrncpy(session.cwd, defchdir, sizeof(session.cwd)); /* Check limits again to make sure deny/allow directives still permit * access. */ if (!login_check_limits((c ? c->subset : main_server->conf), FALSE, TRUE, &i)) { pr_log_auth(PR_LOG_NOTICE, "%s %s: Limit access denies login", (c != NULL) ? "ANON" : C_USER, origuser); goto auth_failure; } /* Perform a directory fixup. */ resolve_deferred_dirs(main_server); fixup_dirs(main_server, CF_DEFER); /* If running under an anonymous context, resolve all <Directory> * blocks inside it. */ if (c && c->subset) resolve_anonymous_dirs(c->subset); /* Write the login to wtmp. This must be done here because we won't * have access after we give up root. This can result in falsified * wtmp entries if an error kicks the user out before we get * through with the login process. Oh well. */ sess_ttyname = pr_session_get_ttyname(p); /* Perform wtmp logging only if not turned off in <Anonymous> * or the current server */ if (c) wtmp_log = get_param_ptr(c->subset, "WtmpLog", FALSE); if (wtmp_log == NULL) wtmp_log = get_param_ptr(main_server->conf, "WtmpLog", FALSE); /* As per Bug#3482, we need to disable WtmpLog for FreeBSD 9.0, as * an interim measure. * * The issue is that some platforms update multiple files for a single * pututxline(3) call; proftpd tries to update those files manually, * do to chroots (after which a pututxline(3) call will fail). A proper * solution requires a separate process, running with the correct * privileges, which would handle wtmp logging. The proftpd session * processes would send messages to this logging daemon (via Unix domain * socket, or FIFO, or TCP socket). * * Also note that this hack to disable WtmpLog may need to be extended * to other platforms in the future. */ #if defined(HAVE_UTMPX_H) && \ defined(__FreeBSD_version) && __FreeBSD_version >= 900007 if (wtmp_log == NULL || *wtmp_log == TRUE) { wtmp_log = pcalloc(p, sizeof(unsigned char)); *wtmp_log = FALSE; pr_log_debug(DEBUG5, "WtpmLog automatically disabled; see Bug#3482 for details"); } #endif PRIVS_ROOT if (wtmp_log == NULL || *wtmp_log == TRUE) { log_wtmp(sess_ttyname, session.user, session.c->remote_name, session.c->remote_addr); session.wtmp_log = TRUE; } #ifdef PR_USE_LASTLOG if (lastlog) { log_lastlog(pw->pw_uid, session.user, sess_ttyname, session.c->remote_addr); } #endif /* PR_USE_LASTLOG */ /* Open any TransferLogs */ if (!xferlog) { if (c) xferlog = get_param_ptr(c->subset, "TransferLog", FALSE); if (!xferlog) xferlog = get_param_ptr(main_server->conf, "TransferLog", FALSE); if (!xferlog) xferlog = PR_XFERLOG_PATH; } if (strcasecmp(xferlog, "NONE") == 0) { xferlog_open(NULL); } else { xferlog_open(xferlog); } res = set_groups(p, pw->pw_gid, session.gids); if (res < 0) { pr_log_pri(PR_LOG_ERR, "error: unable to set groups: %s", strerror(errno)); } PRIVS_RELINQUISH /* Now check to see if the user has an applicable DefaultRoot */ if (c == NULL) { if (get_default_root(session.pool, allow_chroot_symlinks, &defroot) < 0) { pr_log_pri(PR_LOG_NOTICE, "error: unable to determine DefaultRoot directory"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } ensure_open_passwd(p); if (defroot != NULL) { if (pr_auth_chroot(defroot) == -1) { pr_log_pri(PR_LOG_NOTICE, "error: unable to set DefaultRoot directory"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } /* Re-calc the new cwd based on this root dir. If not applicable * place the user in / (of defroot) */ if (strncmp(session.cwd, defroot, strlen(defroot)) == 0) { char *newcwd = &session.cwd[strlen(defroot)]; if (*newcwd == '/') newcwd++; session.cwd[0] = '/'; sstrncpy(&session.cwd[1], newcwd, sizeof(session.cwd)); } } } if (c) ensure_open_passwd(p); if (c && pr_auth_chroot(session.chroot_path) == -1) { pr_log_pri(PR_LOG_NOTICE, "error: unable to set anonymous privileges"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } /* new in 1.1.x, I gave in and we don't give up root permanently.. * sigh. */ PRIVS_ROOT #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(pw->pw_uid, pw->pw_gid) #ifdef HAVE_GETEUID if (getegid() != pw->pw_gid || geteuid() != pw->pw_uid) { PRIVS_RELINQUISH pr_log_pri(PR_LOG_ERR, "error: %s setregid() or setreuid(): %s", session.user, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } #endif /* If the home directory is NULL or "", reject the login. */ if (pw->pw_dir == NULL || strncmp(pw->pw_dir, "", 1) == 0) { pr_log_pri(PR_LOG_WARNING, "error: user %s home directory is NULL or \"\"", session.user); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } { unsigned char *show_symlinks = get_param_ptr( c ? c->subset : main_server->conf, "ShowSymlinks", FALSE); if (!show_symlinks || *show_symlinks == TRUE) showsymlinks = TRUE; else showsymlinks = FALSE; } /* chdir to the proper directory, do this even if anonymous * to make sure we aren't outside our chrooted space. */ /* Attempt to change to the correct directory -- use session.cwd first. * This will contain the DefaultChdir directory, if configured... */ if (pr_fsio_chdir_canon(session.cwd, !showsymlinks) == -1) { /* if we've got DefaultRoot or anonymous login, ignore this error * and chdir to / */ if (session.chroot_path != NULL || defroot) { pr_log_debug(DEBUG2, "unable to chdir to %s (%s), defaulting to chroot " "directory %s", session.cwd, strerror(errno), (session.chroot_path ? session.chroot_path : defroot)); if (pr_fsio_chdir_canon("/", !showsymlinks) == -1) { pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"/\") failed: %s", session.user, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } else if (defchdir) { /* If we've got defchdir, failure is ok as well, simply switch to * user's homedir. */ pr_log_debug(DEBUG2, "unable to chdir to %s (%s), defaulting to home " "directory %s", session.cwd, strerror(errno), pw->pw_dir); if (pr_fsio_chdir_canon(pw->pw_dir, !showsymlinks) == -1) { pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"%s\") failed: %s", session.user, session.cwd, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } else { /* Unable to switch to user's real home directory, which is not * allowed. */ pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"%s\") failed: %s", session.user, session.cwd, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } sstrncpy(session.cwd, pr_fs_getcwd(), sizeof(session.cwd)); sstrncpy(session.vwd, pr_fs_getvwd(), sizeof(session.vwd)); /* Make sure directory config pointers are set correctly */ dir_check_full(p, cmd, G_NONE, session.cwd, NULL); if (c) { if (!session.hide_password) { session.proc_prefix = pstrcat(session.pool, session.c->remote_name, ": anonymous/", pass, NULL); } else { session.proc_prefix = pstrcat(session.pool, session.c->remote_name, ": anonymous", NULL); } session.sf_flags = SF_ANON; } else { session.proc_prefix = pstrdup(session.pool, session.c->remote_name); session.sf_flags = 0; } /* While closing the pointer to the password database would avoid any * potential attempt to hijack this information, it is unfortunately needed * in a chroot()ed environment. Otherwise, mappings from UIDs to names, * among other things, would fail. */ /* pr_auth_endpwent(p); */ /* Default transfer mode is ASCII */ defaulttransfermode = (char *) get_param_ptr(main_server->conf, "DefaultTransferMode", FALSE); if (defaulttransfermode && strcasecmp(defaulttransfermode, "binary") == 0) { session.sf_flags &= (SF_ALL^SF_ASCII); } else { session.sf_flags |= SF_ASCII; } /* Authentication complete, user logged in, now kill the login * timer. */ /* Update the scoreboard entry */ pr_scoreboard_entry_update(session.pid, PR_SCORE_USER, session.user, PR_SCORE_CWD, session.cwd, NULL); pr_session_set_idle(); pr_timer_remove(PR_TIMER_LOGIN, &auth_module); /* These copies are made from the session.pool, instead of the more * volatile pool used originally, in order that the copied data maintain * its integrity for the lifetime of the session. */ session.user = pstrdup(session.pool, session.user); if (session.group) session.group = pstrdup(session.pool, session.group); if (session.gids) session.gids = copy_array(session.pool, session.gids); /* session.groups is an array of strings, so we must copy the string data * as well as the pointers. */ session.groups = copy_array_str(session.pool, session.groups); /* Resolve any deferred-resolution paths in the FS layer */ pr_resolve_fs_map(); return 1; auth_failure: if (pass) pr_memscrub(pass, strlen(pass)); session.user = session.group = NULL; session.gids = session.groups = NULL; session.wtmp_log = FALSE; return 0; } /* This function counts the number of connected users. It only fills in the * Class-based counters and an estimate for the number of clients. The primary * purpose is to make it so that the %N/%y escapes work in a DisplayConnect * greeting. A secondary purpose is to enforce any configured * MaxConnectionsPerHost limit. */ static int auth_scan_scoreboard(void) { char *key; void *v; config_rec *c = NULL; pr_scoreboard_entry_t *score = NULL; unsigned int cur = 0, ccur = 0, hcur = 0; char curr_server_addr[80] = {'\0'}; const char *client_addr = pr_netaddr_get_ipstr(session.c->remote_addr); snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; /* Determine how many users are currently connected */ if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { pr_signals_handle(); /* Make sure it matches our current server */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { cur++; if (strcmp(score->sce_client_addr, client_addr) == 0) hcur++; /* Only count up authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) continue; /* Note: the class member of the scoreboard entry will never be * NULL. At most, it may be the empty string. */ if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Lookup any configured MaxConnectionsPerHost. */ c = find_config(main_server->conf, CONF_PARAM, "MaxConnectionsPerHost", FALSE); if (c) { unsigned int *max = c->argv[0]; if (*max && hcur > *max) { char maxstr[20]; char *msg = "Sorry, the maximum number of connections (%m) for your host " "are already connected."; pr_event_generate("mod_auth.max-connections-per-host", session.c); if (c->argc == 2) msg = c->argv[1]; memset(maxstr, '\0', sizeof(maxstr)); snprintf(maxstr, sizeof(maxstr), "%u", *max); maxstr[sizeof(maxstr)-1] = '\0'; pr_response_send(R_530, "%s", sreplace(session.pool, msg, "%m", maxstr, NULL)); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxConnectionsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxConnectionsPerHost"); } } return 0; } static int have_client_limits(cmd_rec *cmd) { if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerClass", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE) != NULL) { return TRUE; } return FALSE; } static int auth_count_scoreboard(cmd_rec *cmd, char *user) { char *key; void *v; pr_scoreboard_entry_t *score = NULL; long cur = 0, hcur = 0, ccur = 0, hostsperuser = 1, usersessions = 0; config_rec *c = NULL, *maxc = NULL; /* First, check to see which Max* directives are configured. If none * are configured, then there is no need for us to needlessly scan the * ScoreboardFile. */ if (have_client_limits(cmd) == FALSE) { return 0; } /* Determine how many users are currently connected. */ /* We use this call to get the possibly-changed user name. */ (void) pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Gather our statistics. */ if (user) { char curr_server_addr[80] = {'\0'}; snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { unsigned char same_host = FALSE; pr_signals_handle(); /* Make sure it matches our current server. */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { if ((c && c->config_type == CONF_ANON && !strcmp(score->sce_user, user)) || !c) { /* This small hack makes sure that cur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c && c->config_type == CONF_ANON && cur == 0) cur = 1; /* Only count authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) continue; cur++; /* Count up sessions on a per-host basis. */ if (!strcmp(score->sce_client_addr, pr_netaddr_get_ipstr(session.c->remote_addr))) { same_host = TRUE; /* This small hack makes sure that hcur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c && c->config_type == CONF_ANON && hcur == 0) hcur = 1; hcur++; } /* Take a per-user count of connections. */ if (strcmp(score->sce_user, user) == 0) { usersessions++; /* Count up unique hosts. */ if (!same_host) hostsperuser++; } } if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); PRIVS_RELINQUISH } key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Try to determine what MaxClients/MaxHosts limits apply to this session * (if any) and count through the runtime file to see if this limit would * be exceeded. */ maxc = find_config(cmd->server->conf, CONF_PARAM, "MaxClientsPerClass", FALSE); while (session.conn_class != NULL && maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your class " "are already connected."; unsigned int *max = maxc->argv[1]; if (strcmp(maxc->argv[0], session.conn_class->cls_name) != 0) { maxc = find_config_next(maxc, maxc->next, CONF_PARAM, "MaxClientsPerClass", FALSE); continue; } if (maxc->argc > 2) maxstr = maxc->argv[2]; if (*max && ccur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-class", session.conn_class->cls_name); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerClass %s %u)", session.conn_class->cls_name, *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerClass"); } break; } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your host " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) maxstr = maxc->argv[1]; if (*max && hcur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-host", session.c); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerHost"); } } /* Check for any configured MaxClientsPerUser. */ maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) for this user " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) maxstr = maxc->argv[1]; if (*max && usersessions > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerUser %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerUser"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of allowed clients (%m) are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) maxstr = maxc->argv[1]; if (*max && cur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients", NULL); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClients %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClients"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of hosts (%m) for this user are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) maxstr = maxc->argv[1]; if (*max && hostsperuser > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-hosts-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxHostsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxHostsPerUser"); } } return 0; } MODRET auth_pre_user(cmd_rec *cmd) { if (logged_in) return PR_DECLINED(cmd); /* Close the passwd and group databases, because libc won't let us see new * entries to these files without this (only in PersistentPasswd mode). */ pr_auth_endpwent(cmd->tmp_pool); pr_auth_endgrent(cmd->tmp_pool); /* Check for a user name that exceeds PR_TUNABLE_LOGIN_MAX. */ if (strlen(cmd->arg) > PR_TUNABLE_LOGIN_MAX) { pr_log_pri(PR_LOG_NOTICE, "USER %s (Login failed): " "maximum USER length exceeded", cmd->arg); pr_response_add_err(R_501, _("Login incorrect.")); return PR_ERROR(cmd); } return PR_DECLINED(cmd); } MODRET auth_user(cmd_rec *cmd) { int nopass = FALSE; config_rec *c; char *denymsg = NULL, *user, *origuser; int failnopwprompt = 0, aclp, i; unsigned char *anon_require_passwd = NULL, *login_passwd_prompt = NULL; if (cmd->argc < 2) { return PR_ERROR_MSG(cmd, R_500, _("USER: command requires a parameter")); } if (logged_in) { /* If the client has already authenticated, BUT the given USER command * here is for the exact same user name, then allow the command to * succeed (Bug#4217). */ origuser = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (origuser != NULL && strcmp(origuser, cmd->arg) == 0) { pr_response_add(R_230, _("User %s logged in"), origuser); return PR_HANDLED(cmd); } pr_response_add_err(R_501, "%s", _("Reauthentication not supported")); return PR_ERROR(cmd); } user = cmd->arg; (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (pr_table_add_dup(session.notes, "mod_auth.orig-user", user, 0) < 0) { pr_log_debug(DEBUG3, "error stashing 'mod_auth.orig-user' in " "session.notes: %s", strerror(errno)); } origuser = user; c = pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Check for AccessDenyMsg */ denymsg = get_param_ptr((c ? c->subset : cmd->server->conf), "AccessDenyMsg", FALSE); if (denymsg != NULL) { if (strstr(denymsg, "%u") != NULL) { denymsg = sreplace(cmd->tmp_pool, denymsg, "%u", user, NULL); } } login_passwd_prompt = get_param_ptr( (c && c->config_type == CONF_ANON) ? c->subset : main_server->conf, "LoginPasswordPrompt", FALSE); if (login_passwd_prompt && *login_passwd_prompt == FALSE) { failnopwprompt = TRUE; } else { failnopwprompt = FALSE; } if (failnopwprompt) { if (!user) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_pri(PR_LOG_NOTICE, "USER %s (Login failed): Not a UserAlias", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, _("Login incorrect.")); } pr_session_end(0); } aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); if (c && c->config_type != CONF_ANON) { c = (config_rec *) pcalloc(session.pool, sizeof(config_rec)); c->config_type = CONF_ANON; c->name = ""; /* don't really need this yet */ c->subset = main_server->conf; } if (c) { if (!login_check_limits(c->subset, FALSE, TRUE, &i) || (!aclp && !i) ) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_auth(PR_LOG_NOTICE, "ANON %s: Limit access denies login", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, _("Login incorrect.")); } pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by <Limit LOGIN>"); } } if (c == NULL && aclp == 0) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_auth(PR_LOG_NOTICE, "USER %s: Limit access denies login", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, "%s", _("Login incorrect.")); } pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by <Limit LOGIN>"); } } if (c) anon_require_passwd = get_param_ptr(c->subset, "AnonRequirePassword", FALSE); if (c && user && (!anon_require_passwd || *anon_require_passwd == FALSE)) nopass = TRUE; session.gids = NULL; session.groups = NULL; session.user = NULL; session.group = NULL; if (nopass) { pr_response_add(R_331, _("Anonymous login ok, send your complete email " "address as your password")); } else if (pr_auth_requires_pass(cmd->tmp_pool, user) == FALSE) { /* Check to see if a password from the client is required. In the * vast majority of cases, a password will be required. */ /* Act as if we received a PASS command from the client. */ cmd_rec *fakecmd = pr_cmd_alloc(cmd->pool, 2, NULL); /* We use pstrdup() here, rather than assigning C_PASS directly, since * code elsewhere will attempt to modify this buffer, and C_PASS is * a string literal. */ fakecmd->argv[0] = pstrdup(fakecmd->pool, C_PASS); fakecmd->argv[1] = NULL; fakecmd->arg = NULL; c = add_config_param_set(&cmd->server->conf, "authenticated", 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = TRUE; authenticated_without_pass = TRUE; pr_log_auth(PR_LOG_NOTICE, "USER %s: Authenticated without password", user); pr_cmd_dispatch(fakecmd); } else { pr_response_add(R_331, _("Password required for %s"), cmd->argv[1]); } return PR_HANDLED(cmd); } /* Close the passwd and group databases, similar to auth_pre_user(). */ MODRET auth_pre_pass(cmd_rec *cmd) { char *displaylogin; pr_auth_endpwent(cmd->tmp_pool); pr_auth_endgrent(cmd->tmp_pool); /* Look for a DisplayLogin file which has an absolute path. If we find one, * open a filehandle, such that that file can be displayed even if the * session is chrooted. DisplayLogin files with relative paths will be * handled after chroot, preserving the old behavior. */ displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin && *displaylogin == '/') { struct stat st; displaylogin_fh = pr_fsio_open(displaylogin, O_RDONLY); if (displaylogin_fh == NULL) { pr_log_debug(DEBUG6, "unable to open DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } else { if (pr_fsio_fstat(displaylogin_fh, &st) < 0) { pr_log_debug(DEBUG6, "unable to stat DisplayLogin file '%s': %s", displaylogin, strerror(errno)); pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } else { if (S_ISDIR(st.st_mode)) { errno = EISDIR; pr_log_debug(DEBUG6, "unable to use DisplayLogin file '%s': %s", displaylogin, strerror(errno)); pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } } } } return PR_DECLINED(cmd); } MODRET auth_pass(cmd_rec *cmd) { char *user = NULL; int res = 0; if (logged_in) return PR_ERROR_MSG(cmd, R_503, _("You are already logged in")); user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (!user) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); return PR_ERROR_MSG(cmd, R_503, _("Login with USER first")); } /* Clear any potentially cached directory config */ session.anon_config = NULL; session.dir_config = NULL; res = setup_env(cmd->tmp_pool, cmd, user, cmd->arg); if (res == 1) { config_rec *c = NULL; c = add_config_param_set(&cmd->server->conf, "authenticated", 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = TRUE; set_auth_check(NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (session.sf_flags & SF_ANON) { if (pr_table_add_dup(session.notes, "mod_auth.anon-passwd", pr_fs_decode_path(cmd->server->pool, cmd->arg), 0) < 0) { pr_log_debug(DEBUG3, "error stashing anonymous password in session.notes: %s", strerror(errno)); } } logged_in = 1; return PR_HANDLED(cmd); } (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (res == 0) { unsigned int max_logins, *max = NULL; char *denymsg = NULL; /* check for AccessDenyMsg */ if ((denymsg = get_param_ptr((session.anon_config ? session.anon_config->subset : cmd->server->conf), "AccessDenyMsg", FALSE)) != NULL) { if (strstr(denymsg, "%u") != NULL) { denymsg = sreplace(cmd->tmp_pool, denymsg, "%u", user, NULL); } } max = get_param_ptr(main_server->conf, "MaxLoginAttempts", FALSE); if (max != NULL) { max_logins = *max; } else { max_logins = 3; } if (max_logins > 0 && ++auth_tries >= max_logins) { if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, "%s", _("Login incorrect.")); } pr_log_auth(PR_LOG_NOTICE, "Maximum login attempts (%u) exceeded, connection refused", max_logins); /* Generate an event about this limit being exceeded. */ pr_event_generate("mod_auth.max-login-attempts", session.c); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxLoginAttempts"); } return PR_ERROR_MSG(cmd, R_530, denymsg ? denymsg : _("Login incorrect.")); } return PR_HANDLED(cmd); } MODRET auth_acct(cmd_rec *cmd) { pr_response_add(R_502, _("ACCT command not implemented")); return PR_HANDLED(cmd); } MODRET auth_rein(cmd_rec *cmd) { pr_response_add(R_502, _("REIN command not implemented")); return PR_HANDLED(cmd); } /* Configuration handlers */ MODRET set_accessdenymsg(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_accessgrantmsg(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: AllowChrootSymlinks on|off */ MODRET set_allowchrootsymlinks(cmd_rec *cmd) { int b = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); b = get_boolean(cmd, 1); if (b == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = b; return PR_HANDLED(cmd); } MODRET set_anonrequirepassword(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_anonrejectpasswords(cmd_rec *cmd) { #ifdef PR_USE_REGEX pr_regex_t *pre = NULL; int res; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); pre = pr_regexp_alloc(&auth_module); res = pr_regexp_compile(pre, cmd->argv[1], REG_EXTENDED|REG_NOSUB); if (res != 0) { char errstr[200] = {'\0'}; pr_regexp_error(res, pre, errstr, 200); pr_regexp_free(NULL, pre); CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "Unable to compile regex '", cmd->argv[1], "': ", errstr, NULL)); } (void) add_config_param(cmd->argv[0], 1, (void *) pre); return PR_HANDLED(cmd); #else CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0], " directive " "cannot be used on this system, as you do not have POSIX compliant " "regex support", NULL)); #endif } MODRET set_authaliasonly(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_authusingalias(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_createhome(cmd_rec *cmd) { int bool = -1, start = 2; mode_t mode = (mode_t) 0700, dirmode = (mode_t) 0711; char *skel_path = NULL; config_rec *c = NULL; uid_t cuid = 0; gid_t cgid = 0, hgid = -1; unsigned long flags = 0UL; if (cmd->argc-1 < 1) { CONF_ERROR(cmd, "wrong number of parameters"); } CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } /* No need to process the rest if bool is FALSE. */ if (bool == FALSE) { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } /* Check the mode parameter, if present */ if (cmd->argc-1 >= 2 && strcasecmp(cmd->argv[2], "dirmode") != 0 && strcasecmp(cmd->argv[2], "skel") != 0) { char *tmp = NULL; mode = strtol(cmd->argv[2], &tmp, 8); if (tmp && *tmp) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": bad mode parameter: '", cmd->argv[2], "'", NULL)); start = 3; } if (cmd->argc-1 > 2) { register unsigned int i; /* Cycle through the rest of the parameters */ for (i = start; i < cmd->argc;) { if (strcasecmp(cmd->argv[i], "skel") == 0) { struct stat st; /* Check that the skel directory, if configured, meets the * requirements. */ skel_path = cmd->argv[++i]; if (*skel_path != '/') { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "skel path '", skel_path, "' is not a full path", NULL)); } if (pr_fsio_stat(skel_path, &st) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to stat '", skel_path, "': ", strerror(errno), NULL)); } if (!S_ISDIR(st.st_mode)) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", skel_path, "' is not a directory", NULL)); } /* Must not be world-writable. */ if (st.st_mode & S_IWOTH) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", skel_path, "' is world-writable", NULL)); } /* Move the index past the skel parameter */ i++; } else if (strcasecmp(cmd->argv[i], "dirmode") == 0) { char *tmp = NULL; dirmode = strtol(cmd->argv[++i], &tmp, 8); if (tmp && *tmp) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad mode parameter: '", cmd->argv[i], "'", NULL)); /* Move the index past the dirmode parameter */ i++; } else if (strcasecmp(cmd->argv[i], "uid") == 0) { /* Check for a "~" parameter. */ if (strncmp(cmd->argv[i+1], "~", 2) != 0) { char *tmp = NULL; uid_t uid; uid = strtol(cmd->argv[++i], &tmp, 10); if (tmp && *tmp) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad UID parameter: '", cmd->argv[i], "'", NULL)); } cuid = uid; } else { cuid = (uid_t) -1; i++; } /* Move the index past the uid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "gid") == 0) { /* Check for a "~" parameter. */ if (strncmp(cmd->argv[i+1], "~", 2) != 0) { char *tmp = NULL; gid_t gid; gid = strtol(cmd->argv[++i], &tmp, 10); if (tmp && *tmp) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad GID parameter: '", cmd->argv[i], "'", NULL)); } cgid = gid; } else { cgid = (gid_t) -1; i++; } /* Move the index past the gid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "homegid") == 0) { char *tmp = NULL; gid_t gid; gid = strtol(cmd->argv[++i], &tmp, 10); if (tmp && *tmp) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad GID parameter: '", cmd->argv[i], "'", NULL)); } hgid = gid; /* Move the index past the homegid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "NoRootPrivs") == 0) { flags |= PR_MKHOME_FL_USE_USER_PRIVS; i++; } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown parameter: '", cmd->argv[i], "'", NULL)); } } } c = add_config_param(cmd->argv[0], 8, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->argv[1] = pcalloc(c->pool, sizeof(mode_t)); *((mode_t *) c->argv[1]) = mode; c->argv[2] = pcalloc(c->pool, sizeof(mode_t)); *((mode_t *) c->argv[2]) = dirmode; if (skel_path) { c->argv[3] = pstrdup(c->pool, skel_path); } c->argv[4] = pcalloc(c->pool, sizeof(uid_t)); *((uid_t *) c->argv[4]) = cuid; c->argv[5] = pcalloc(c->pool, sizeof(gid_t)); *((gid_t *) c->argv[5]) = cgid; c->argv[6] = pcalloc(c->pool, sizeof(gid_t)); *((gid_t *) c->argv[6]) = hgid; c->argv[7] = pcalloc(c->pool, sizeof(unsigned long)); *((unsigned long *) c->argv[7]) = flags; return PR_HANDLED(cmd); } MODRET add_defaultroot(cmd_rec *cmd) { config_rec *c; char *dir,**argv; int argc; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (cmd->argc < 2) CONF_ERROR(cmd,"syntax: DefaultRoot <directory> [<group-expression>]"); argv = cmd->argv; argc = cmd->argc - 2; dir = *++argv; /* dir must be / or ~. */ if (*dir != '/' && *dir != '~') CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") absolute pathname " "required", NULL)); if (strchr(dir, '*')) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); if (*(dir + strlen(dir) - 1) != '/') dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); acl = pr_expr_create(cmd->tmp_pool, &argc, argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(char *)); argv = (char **) c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } *argv = NULL; return PR_HANDLED(cmd); } MODRET add_defaultchdir(cmd_rec *cmd) { config_rec *c; char *dir,**argv; int argc; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2) CONF_ERROR(cmd, "syntax: DefaultChdir <directory> [<group-expression>]"); argv = cmd->argv; argc = cmd->argc - 2; dir = *++argv; if (strchr(dir, '*')) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); if (*(dir + strlen(dir) - 1) != '/') dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); acl = pr_expr_create(cmd->tmp_pool, &argc, argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(char *)); argv = (char **) c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } *argv = NULL; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_displaylogin(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_grouppassword(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_loginpasswordprompt(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerClass class max|"none" ["message"] */ MODRET set_maxclientsclass(cmd_rec *cmd) { int max; config_rec *c; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[2], "none") == 0) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[2], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "max must be 'none' or a number greater than 0"); } if (cmd->argc == 4) { c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL); c->argv[0] = pstrdup(c->pool, cmd->argv[1]); c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = max; c->argv[2] = pstrdup(c->pool, cmd->argv[3]); } else { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pstrdup(c->pool, cmd->argv[1]); c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = max; } return PR_HANDLED(cmd); } /* usage: MaxClients max|"none" ["message"] */ MODRET set_maxclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerHost max|"none" ["message"] */ MODRET set_maxhostclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerUser max|"none" ["message"] */ MODRET set_maxuserclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxConnectionsPerHost max|"none" ["message"] */ MODRET set_maxconnectsperhost(cmd_rec *cmd) { int max; config_rec *c; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[1], "none") == 0) max = 0; else { char *tmp = NULL; max = (int) strtol(cmd->argv[1], &tmp, 10); if ((tmp && *tmp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; return PR_HANDLED(cmd); } /* usage: MaxHostsPerUser max|"none" ["message"] */ MODRET set_maxhostsperuser(cmd_rec *cmd) { int max; config_rec *c = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_maxloginattempts(cmd_rec *cmd) { int max; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[1], "none") == 0) { max = 0; } else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; return PR_HANDLED(cmd); } MODRET set_requirevalidshell(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: RewriteHome on|off */ MODRET set_rewritehome(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_rootlogin(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd,1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = (unsigned char) bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: RootRevoke on|off|UseNonCompliantActiveTransfer */ MODRET set_rootrevoke(cmd_rec *cmd) { int root_revoke = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* A RootRevoke value of 0 indicates 'false', 1 indicates 'true', and * 2 indicates 'NonCompliantActiveTransfer'. */ root_revoke = get_boolean(cmd, 1); if (root_revoke == -1) { if (strcasecmp(cmd->argv[1], "UseNonCompliantActiveTransfer") != 0 && strcasecmp(cmd->argv[1], "UseNonCompliantActiveTransfers") != 0) { CONF_ERROR(cmd, "expected Boolean parameter"); } root_revoke = 2; } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = (unsigned char) root_revoke; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_timeoutlogin(cmd_rec *cmd) { int timeout = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; return PR_HANDLED(cmd); } MODRET set_timeoutsession(cmd_rec *cmd) { int timeout = 0, precedence = 0; config_rec *c = NULL; int ctxt = (cmd->config && cmd->config->config_type != CONF_PARAM ? cmd->config->config_type : cmd->server->config_type ? cmd->server->config_type : CONF_ROOT); /* this directive must have either 1 or 3 arguments */ if (cmd->argc-1 != 1 && cmd->argc-1 != 3) CONF_ERROR(cmd, "missing arguments"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Set the precedence for this config_rec based on its configuration * context. */ if (ctxt & CONF_GLOBAL) { precedence = 1; /* These will never appear simultaneously */ } else if ((ctxt & CONF_ROOT) || (ctxt & CONF_VIRTUAL)) { precedence = 2; } else if (ctxt & CONF_ANON) { precedence = 3; } if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } if (timeout == 0) { /* do nothing */ return PR_HANDLED(cmd); } if (cmd->argc-1 == 3) { if (strncmp(cmd->argv[2], "user", 5) == 0 || strncmp(cmd->argv[2], "group", 6) == 0 || strncmp(cmd->argv[2], "class", 6) == 0) { /* no op */ } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[0], ": unknown classifier used: '", cmd->argv[2], "'", NULL)); } } if (cmd->argc-1 == 1) { c = add_config_param(cmd->argv[0], 2, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = precedence; } else if (cmd->argc-1 == 3) { array_header *acl = NULL; int argc = cmd->argc - 3; char **argv = cmd->argv + 2; acl = pr_expr_create(cmd->tmp_pool, &argc, argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 2; /* add 3 to argc for the argv of the config_rec: one for the * seconds value, one for the precedence, one for the classifier, * and one for the terminating NULL */ c->argv = pcalloc(c->pool, ((argc + 4) * sizeof(char *))); /* capture the config_rec's argv pointer for doing the by-hand * population */ argv = (char **) c->argv; /* Copy in the seconds. */ *argv = pcalloc(c->pool, sizeof(int)); *((int *) *argv++) = timeout; /* Copy in the precedence. */ *argv = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) *argv++) = precedence; /* Copy in the classifier. */ *argv++ = pstrdup(c->pool, cmd->argv[2]); /* now, copy in the expression arguments */ if (argc && acl) { while (argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } } /* don't forget the terminating NULL */ *argv = NULL; } else { /* Should never reach here. */ CONF_ERROR(cmd, "wrong number of parameters"); } c->flags |= CF_MERGEDOWN_MULTI; return PR_HANDLED(cmd); } MODRET set_useftpusers(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: UseLastlog on|off */ MODRET set_uselastlog(cmd_rec *cmd) { #ifdef PR_USE_LASTLOG int bool; config_rec *c; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); #else CONF_ERROR(cmd, "requires lastlog support (--with-lastlog)"); #endif /* PR_USE_LASTLOG */ } /* usage: UserAlias alias real-user */ MODRET set_useralias(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Make sure that the given names differ. */ if (strcmp(cmd->argv[1], cmd->argv[2]) == 0) CONF_ERROR(cmd, "alias and real user names must differ"); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); /* Note: only merge this directive down if it is not appearing in an * <Anonymous> context. */ if (!check_context(cmd, CONF_ANON)) { c->flags |= CF_MERGEDOWN_MULTI; } return PR_HANDLED(cmd); } MODRET set_userdirroot(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_userpassword(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* Module API tables */ static conftable auth_conftab[] = { { "AccessDenyMsg", set_accessdenymsg, NULL }, { "AccessGrantMsg", set_accessgrantmsg, NULL }, { "AllowChrootSymlinks", set_allowchrootsymlinks, NULL }, { "AnonRequirePassword", set_anonrequirepassword, NULL }, { "AnonRejectPasswords", set_anonrejectpasswords, NULL }, { "AuthAliasOnly", set_authaliasonly, NULL }, { "AuthUsingAlias", set_authusingalias, NULL }, { "CreateHome", set_createhome, NULL }, { "DefaultChdir", add_defaultchdir, NULL }, { "DefaultRoot", add_defaultroot, NULL }, { "DisplayLogin", set_displaylogin, NULL }, { "GroupPassword", set_grouppassword, NULL }, { "LoginPasswordPrompt", set_loginpasswordprompt, NULL }, { "MaxClients", set_maxclients, NULL }, { "MaxClientsPerClass", set_maxclientsclass, NULL }, { "MaxClientsPerHost", set_maxhostclients, NULL }, { "MaxClientsPerUser", set_maxuserclients, NULL }, { "MaxConnectionsPerHost", set_maxconnectsperhost, NULL }, { "MaxHostsPerUser", set_maxhostsperuser, NULL }, { "MaxLoginAttempts", set_maxloginattempts, NULL }, { "RequireValidShell", set_requirevalidshell, NULL }, { "RewriteHome", set_rewritehome, NULL }, { "RootLogin", set_rootlogin, NULL }, { "RootRevoke", set_rootrevoke, NULL }, { "TimeoutLogin", set_timeoutlogin, NULL }, { "TimeoutSession", set_timeoutsession, NULL }, { "UseFtpUsers", set_useftpusers, NULL }, { "UseLastlog", set_uselastlog, NULL }, { "UserAlias", set_useralias, NULL }, { "UserDirRoot", set_userdirroot, NULL }, { "UserPassword", set_userpassword, NULL }, { NULL, NULL, NULL } }; static cmdtable auth_cmdtab[] = { { PRE_CMD, C_USER, G_NONE, auth_pre_user, FALSE, FALSE, CL_AUTH }, { CMD, C_USER, G_NONE, auth_user, FALSE, FALSE, CL_AUTH }, { PRE_CMD, C_PASS, G_NONE, auth_pre_pass, FALSE, FALSE, CL_AUTH }, { CMD, C_PASS, G_NONE, auth_pass, FALSE, FALSE, CL_AUTH }, { POST_CMD, C_PASS, G_NONE, auth_post_pass, FALSE, FALSE, CL_AUTH }, { LOG_CMD, C_PASS, G_NONE, auth_log_pass, FALSE, FALSE }, { LOG_CMD_ERR,C_PASS, G_NONE, auth_err_pass, FALSE, FALSE }, { CMD, C_ACCT, G_NONE, auth_acct, FALSE, FALSE, CL_AUTH }, { CMD, C_REIN, G_NONE, auth_rein, FALSE, FALSE, CL_AUTH }, { POST_CMD, C_HOST, G_NONE, auth_post_host, FALSE, FALSE }, { 0, NULL } }; /* Module interface */ module auth_module = { NULL, NULL, /* Module API version */ 0x20, /* Module name */ "auth", /* Module configuration directive table */ auth_conftab, /* Module command handler table */ auth_cmdtab, /* Module authentication handler table */ NULL, /* Module initialization function */ auth_init, /* Session initialization function */ auth_sess_init };
./CrossVul/dataset_final_sorted/CWE-59/c/bad_3262_0
crossvul-cpp_data_good_436_9
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Memory management framework. This framework is used to * find any memory leak. * * Authors: Alexandre Cassen, <acassen@linux-vs.org> * Jan Holmberg, <jan@artech.net> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #ifdef _MEM_CHECK_ #include <assert.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <time.h> #include <limits.h> #endif #include <errno.h> #include <string.h> #include "memory.h" #include "utils.h" #include "bitops.h" #include "logger.h" #ifdef _MEM_CHECK_ #include "timer.h" #include "rbtree.h" #include "list_head.h" /* Global var */ size_t mem_allocated; /* Total memory used in Bytes */ static size_t max_mem_allocated; /* Maximum memory used in Bytes */ static const char *terminate_banner; /* banner string for report file */ static bool skip_mem_check_final; #endif static void * xalloc(unsigned long size) { void *mem = malloc(size); if (mem == NULL) { if (__test_bit(DONT_FORK_BIT, &debug)) perror("Keepalived"); else log_message(LOG_INFO, "Keepalived xalloc() error - %s", strerror(errno)); exit(EXIT_FAILURE); } #ifdef _MEM_CHECK_ mem_allocated += size - sizeof(long); if (mem_allocated > max_mem_allocated) max_mem_allocated = mem_allocated; #endif return mem; } void * zalloc(unsigned long size) { void *mem = xalloc(size); if (mem) memset(mem, 0, size); return mem; } /* KeepAlived memory management. in debug mode, * help finding eventual memory leak. * Allocation memory types manipulated are : * * +-type------------------+-meaning------------------+ * ! FREE_SLOT ! Free slot ! * ! OVERRUN ! Overrun ! * ! FREE_NULL ! free null ! * ! REALLOC_NULL ! realloc null ! * ! DOUBLE_FREE ! double free ! * ! REALLOC_DOUBLE_FREE ! realloc freed block ! * ! FREE_NOT_ALLOC ! Not previously allocated ! * ! REALLOC_NOT_ALLOC ! Not previously allocated ! * ! MALLOC_ZERO_SIZE ! malloc with size 0 ! * ! REALLOC_ZERO_SIZE ! realloc with size 0 ! * ! LAST_FREE ! Last free list ! * ! ALLOCATED ! Allocated ! * +-----------------------+--------------------------+ * * global variable debug bit MEM_ERR_DETECT_BIT used to * flag some memory error. * */ #ifdef _MEM_CHECK_ enum slot_type { FREE_SLOT = 0, OVERRUN, FREE_NULL, REALLOC_NULL, DOUBLE_FREE, REALLOC_DOUBLE_FREE, FREE_NOT_ALLOC, REALLOC_NOT_ALLOC, MALLOC_ZERO_SIZE, REALLOC_ZERO_SIZE, LAST_FREE, ALLOCATED, } ; #define TIME_STR_LEN 9 #if ULONG_MAX == 0xffffffffffffffffUL #define CHECK_VAL 0xa5a55a5aa5a55a5aUL #elif ULONG_MAX == 0xffffffffUL #define CHECK_VAL 0xa5a55a5aUL #else #define CHECK_VAL 0xa5a5 #endif #define FREE_LIST_SIZE 256 typedef struct { enum slot_type type; int line; const char *func; const char *file; void *ptr; size_t size; union { list_head_t l; /* When on free list */ rb_node_t t; }; unsigned seq_num; } MEMCHECK; /* Last free pointers */ static LH_LIST_HEAD(free_list); static unsigned free_list_size; /* alloc_list entries used for 1000 VRRP instance each with VMAC interfaces is 33589 */ static rb_root_t alloc_list = RB_ROOT; static LH_LIST_HEAD(bad_list); static unsigned number_alloc_list; /* number of alloc_list allocation entries */ static unsigned max_alloc_list; static unsigned num_mallocs; static unsigned num_reallocs; static unsigned seq_num; static FILE *log_op = NULL; static inline int memcheck_ptr_cmp(MEMCHECK *m1, MEMCHECK *m2) { return m1->ptr - m2->ptr; } static inline int memcheck_seq_cmp(MEMCHECK *m1, MEMCHECK *m2) { return m1->seq_num - m2->seq_num; } static const char * format_time(void) { static char time_buf[TIME_STR_LEN+1]; strftime(time_buf, sizeof time_buf, "%T ", localtime(&time_now.tv_sec)); return time_buf; } void memcheck_log(const char *called_func, const char *param, const char *file, const char *function, int line) { int len = strlen(called_func) + (param ? strlen(param) : 0); if ((len = 36 - len) < 0) len = 0; fprintf(log_op, "%s%*s%s(%s) at %s, %d, %s\n", format_time(), len, "", called_func, param ? param : "", file, line, function); } static MEMCHECK * get_free_alloc_entry(void) { MEMCHECK *entry; /* If number on free list < 256, allocate new entry, otherwise take head */ if (free_list_size < 256) entry = malloc(sizeof *entry); else { entry = list_first_entry(&free_list, MEMCHECK, l); list_head_del(&entry->l); free_list_size--; } entry->seq_num = seq_num++; return entry; } void * keepalived_malloc(size_t size, const char *file, const char *function, int line) { void *buf; MEMCHECK *entry, *entry2; buf = zalloc(size + sizeof (unsigned long)); *(unsigned long *) ((char *) buf + size) = size + CHECK_VAL; entry = get_free_alloc_entry(); entry->ptr = buf; entry->size = size; entry->file = file; entry->func = function; entry->line = line; entry->type = ALLOCATED; rb_insert_sort(&alloc_list, entry, t, memcheck_ptr_cmp); if (++number_alloc_list > max_alloc_list) max_alloc_list = number_alloc_list; fprintf(log_op, "%szalloc [%3d:%3d], %9p, %4zu at %s, %3d, %s%s\n", format_time(), entry->seq_num, number_alloc_list, buf, size, file, line, function, !size ? " - size is 0" : ""); #ifdef _MEM_CHECK_LOG_ if (__test_bit(MEM_CHECK_LOG_BIT, &debug)) log_message(LOG_INFO, "zalloc[%3d:%3d], %9p, %4zu at %s, %3d, %s", entry->seq_num, number_alloc_list, buf, size, file, line, function); #endif num_mallocs++; if (!size) { /* Record malloc with 0 size */ entry2 = get_free_alloc_entry(); *entry2 = *entry; entry2->type = MALLOC_ZERO_SIZE; list_add_tail(&entry2->l, &bad_list); } return buf; } static void * keepalived_free_realloc_common(void *buffer, size_t size, const char *file, const char *function, int line, bool is_realloc) { unsigned long check; MEMCHECK *entry, *entry2, *le; MEMCHECK search = {.ptr = buffer}; /* If nullpointer remember */ if (buffer == NULL) { entry = get_free_alloc_entry(); entry->ptr = NULL; entry->size = size; entry->file = file; entry->func = function; entry->line = line; entry->type = !size ? FREE_NULL : REALLOC_NULL; if (!is_realloc) fprintf(log_op, "%s%-7s%9s, %9s, %4s at %s, %3d, %s\n", format_time(), "free", "ERROR", "NULL", "", file, line, function); else fprintf(log_op, "%s%-7s%9s, %9s, %4zu at %s, %3d, %s%s\n", format_time(), "realloc", "ERROR", "NULL", size, file, line, function, size ? " *** converted to malloc" : ""); __set_bit(MEM_ERR_DETECT_BIT, &debug); list_add_tail(&entry->l, &bad_list); return !size ? NULL : keepalived_malloc(size, file, function, line); } entry = rb_search(&alloc_list, &search, t, memcheck_ptr_cmp); /* Not found */ if (!entry) { entry = get_free_alloc_entry(); entry->ptr = buffer; entry->size = size; entry->file = file; entry->func = function; entry->line = line; entry->type = !size ? FREE_NOT_ALLOC : REALLOC_NOT_ALLOC; entry->seq_num = seq_num++; if (!is_realloc) fprintf(log_op, "%s%-7s%9s, %9p, at %s, %3d, %s - not found\n", format_time(), "free", "ERROR", buffer, file, line, function); else fprintf(log_op, "%s%-7s%9s, %9p, %4zu at %s, %3d, %s - not found\n", format_time(), "realloc", "ERROR", buffer, size, file, line, function); __set_bit(MEM_ERR_DETECT_BIT, &debug); list_for_each_entry_reverse(le, &free_list, l) { if (le->ptr == buffer && le->type == LAST_FREE) { fprintf (log_op, "%11s-> pointer last released at [%3d:%3d], at %s, %3d, %s\n", "", le->seq_num, number_alloc_list, le->file, le->line, le->func); entry->type = !size ? DOUBLE_FREE : REALLOC_DOUBLE_FREE; break; } }; list_add_tail(&entry->l, &bad_list); return NULL; } check = entry->size + CHECK_VAL; if (*(unsigned long *)((char *)buffer + entry->size) != check) { entry2 = get_free_alloc_entry(); *entry2 = *entry; entry2->type = OVERRUN; list_add_tail(&entry2->l, &bad_list); fprintf(log_op, "%s%s corrupt, buffer overrun [%3d:%3d], %9p, %4zu at %s, %3d, %s\n", format_time(), !is_realloc ? "free" : "realloc", entry->seq_num, number_alloc_list, buffer, entry->size, file, line, function); dump_buffer(entry->ptr, entry->size + sizeof (check), log_op, TIME_STR_LEN); fprintf(log_op, "%*sCheck_sum\n", TIME_STR_LEN, ""); dump_buffer((char *) &check, sizeof(check), log_op, TIME_STR_LEN); __set_bit(MEM_ERR_DETECT_BIT, &debug); } mem_allocated -= entry->size; if (!size) { free(buffer); if (is_realloc) { fprintf(log_op, "%s%-7s[%3d:%3d], %9p, %4zu at %s, %3d, %s -> %9s, %4s at %s, %3d, %s\n", format_time(), "realloc", entry->seq_num, number_alloc_list, entry->ptr, entry->size, entry->file, entry->line, entry->func, "made free", "", file, line, function); /* Record bad realloc */ entry2 = get_free_alloc_entry(); *entry2 = *entry; entry2->type = REALLOC_ZERO_SIZE; entry2->file = file; entry2->line = line; entry2->func = function; list_add_tail(&entry2->l, &bad_list); } else fprintf(log_op, "%s%-7s[%3d:%3d], %9p, %4zu at %s, %3d, %s -> %9s, %4s at %s, %3d, %s\n", format_time(), "free", entry->seq_num, number_alloc_list, entry->ptr, entry->size, entry->file, entry->line, entry->func, "NULL", "", file, line, function); #ifdef _MEM_CHECK_LOG_ if (__test_bit(MEM_CHECK_LOG_BIT, &debug)) log_message(LOG_INFO, "%-7s[%3d:%3d], %9p, %4zu at %s, %3d, %s", is_realloc ? "realloc" : "free", entry->seq_num, number_alloc_list, buffer, entry->size, file, line, function); #endif entry->file = file; entry->line = line; entry->func = function; entry->type = LAST_FREE; rb_erase(&entry->t, &alloc_list); list_add_tail(&entry->l, &free_list); free_list_size++; number_alloc_list--; return NULL; } buffer = realloc(buffer, size + sizeof (unsigned long)); mem_allocated += size; if (mem_allocated > max_mem_allocated) max_mem_allocated = mem_allocated; fprintf(log_op, "%srealloc[%3d:%3d], %9p, %4zu at %s, %3d, %s -> %9p, %4zu at %s, %3d, %s\n", format_time(), entry->seq_num, number_alloc_list, entry->ptr, entry->size, entry->file, entry->line, entry->func, buffer, size, file, line, function); #ifdef _MEM_CHECK_LOG_ if (__test_bit(MEM_CHECK_LOG_BIT, &debug)) log_message(LOG_INFO, "realloc[%3d:%3d], %9p, %4zu at %s, %3d, %s -> %9p, %4zu at %s, %3d, %s", entry->seq_num, number_alloc_list, entry->ptr, entry->size, entry->file, entry->line, entry->func, buffer, size, file, line, function); #endif *(unsigned long *) ((char *) buffer + size) = size + CHECK_VAL; if (entry->ptr != buffer) { rb_erase(&entry->t, &alloc_list); entry->ptr = buffer; rb_insert_sort(&alloc_list, entry, t, memcheck_ptr_cmp); } else entry->ptr = buffer; entry->size = size; entry->file = file; entry->line = line; entry->func = function; num_reallocs++; return buffer; } void keepalived_free(void *buffer, const char *file, const char *function, int line) { keepalived_free_realloc_common(buffer, 0, file, function, line, false); } void * keepalived_realloc(void *buffer, size_t size, const char *file, const char *function, int line) { return keepalived_free_realloc_common(buffer, size, file, function, line, true); } static void keepalived_alloc_log(bool final) { unsigned int overrun = 0, badptr = 0, zero_size = 0; size_t sum = 0; MEMCHECK *entry; if (final) { /* If this is a forked child, we don't want the dump */ if (skip_mem_check_final) return; fprintf(log_op, "\n---[ Keepalived memory dump for (%s) ]---\n\n", terminate_banner); } else fprintf(log_op, "\n---[ Keepalived memory dump for (%s) at %s ]---\n\n", terminate_banner, format_time()); /* List the blocks currently allocated */ if (!RB_EMPTY_ROOT(&alloc_list)) { fprintf(log_op, "Entries %s\n\n", final ? "not released" : "currently allocated"); rb_for_each_entry(entry, &alloc_list, t) { sum += entry->size; fprintf(log_op, "%9p [%3d:%3d], %4zu at %s, %3d, %s", entry->ptr, entry->seq_num, number_alloc_list, entry->size, entry->file, entry->line, entry->func); if (entry->type != ALLOCATED) fprintf(log_op, " type = %d", entry->type); fprintf(log_op, "\n"); } } if (!list_empty(&bad_list)) { if (!RB_EMPTY_ROOT(&alloc_list)) fprintf(log_op, "\n"); fprintf(log_op, "Bad entry list\n\n"); list_for_each_entry(entry, &bad_list, l) { switch (entry->type) { case FREE_NULL: badptr++; fprintf(log_op, "%9s %9s, %4s at %s, %3d, %s - null pointer to free\n", "NULL", "", "", entry->file, entry->line, entry->func); break; case REALLOC_NULL: badptr++; fprintf(log_op, "%9s %9s, %4zu at %s, %3d, %s - null pointer to realloc (converted to malloc)\n", "NULL", "", entry->size, entry->file, entry->line, entry->func); break; case FREE_NOT_ALLOC: badptr++; fprintf(log_op, "%9p %9s, %4s at %s, %3d, %s - pointer not found for free\n", entry->ptr, "", "", entry->file, entry->line, entry->func); break; case REALLOC_NOT_ALLOC: badptr++; fprintf(log_op, "%9p %9s, %4zu at %s, %3d, %s - pointer not found for realloc\n", entry->ptr, "", entry->size, entry->file, entry->line, entry->func); break; case DOUBLE_FREE: badptr++; fprintf(log_op, "%9p %9s, %4s at %s, %3d, %s - double free of pointer\n", entry->ptr, "", "", entry->file, entry->line, entry->func); break; case REALLOC_DOUBLE_FREE: badptr++; fprintf(log_op, "%9p %9s, %4zu at %s, %3d, %s - realloc 0 size already freed\n", entry->ptr, "", entry->size, entry->file, entry->line, entry->func); break; case OVERRUN: overrun++; fprintf(log_op, "%9p [%3d:%3d], %4zu at %s, %3d, %s - buffer overrun\n", entry->ptr, entry->seq_num, number_alloc_list, entry->size, entry->file, entry->line, entry->func); break; case MALLOC_ZERO_SIZE: zero_size++; fprintf(log_op, "%9p [%3d:%3d], %4zu at %s, %3d, %s - malloc zero size\n", entry->ptr, entry->seq_num, number_alloc_list, entry->size, entry->file, entry->line, entry->func); break; case REALLOC_ZERO_SIZE: zero_size++; fprintf(log_op, "%9p [%3d:%3d], %4zu at %s, %3d, %s - realloc zero size (handled as free)\n", entry->ptr, entry->seq_num, number_alloc_list, entry->size, entry->file, entry->line, entry->func); break; case ALLOCATED: /* not used - avoid compiler warning */ case FREE_SLOT: case LAST_FREE: break; } } } fprintf(log_op, "\n\n---[ Keepalived memory dump summary for (%s) ]---\n", terminate_banner); fprintf(log_op, "Total number of bytes %s...: %zu\n", final ? "not freed" : "allocated", sum); fprintf(log_op, "Number of entries %s.......: %d\n", final ? "not freed" : "allocated", number_alloc_list); fprintf(log_op, "Maximum allocated entries.........: %d\n", max_alloc_list); fprintf(log_op, "Maximum memory allocated..........: %zu\n", max_mem_allocated); fprintf(log_op, "Number of mallocs.................: %d\n", num_mallocs); fprintf(log_op, "Number of reallocs................: %d\n", num_reallocs); fprintf(log_op, "Number of bad entries.............: %d\n", badptr); fprintf(log_op, "Number of buffer overrun..........: %d\n", overrun); fprintf(log_op, "Number of 0 size allocations......: %d\n\n", zero_size); if (sum != mem_allocated) fprintf(log_op, "ERROR - sum of allocated %zu != mem_allocated %zu\n", sum, mem_allocated); if (final) { if (sum || number_alloc_list || badptr || overrun) fprintf(log_op, "=> Program seems to have some memory problem !!!\n\n"); else fprintf(log_op, "=> Program seems to be memory allocation safe...\n\n"); } } static void keepalived_free_final(void) { keepalived_alloc_log(true); } void keepalived_alloc_dump(void) { keepalived_alloc_log(false); } void mem_log_init(const char* prog_name, const char *banner) { size_t log_name_len; char *log_name; if (__test_bit(LOG_CONSOLE_BIT, &debug)) { log_op = stderr; return; } if (log_op) fclose(log_op); log_name_len = 5 + strlen(prog_name) + 5 + 7 + 4 + 1; /* "/tmp/" + prog_name + "_mem." + PID + ".log" + '\0" */ log_name = malloc(log_name_len); if (!log_name) { log_message(LOG_INFO, "Unable to malloc log file name"); log_op = stderr; return; } snprintf(log_name, log_name_len, "/tmp/%s_mem.%d.log", prog_name, getpid()); log_op = fopen_safe(log_name, "a"); if (log_op == NULL) { log_message(LOG_INFO, "Unable to open %s for appending", log_name); log_op = stderr; } else { int fd = fileno(log_op); /* We don't want any children to inherit the log file */ fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC); /* Make the log output line buffered. This was to ensure that * children didn't inherit the buffer, but the CLOEXEC above * should resolve that. */ setlinebuf(log_op); fprintf(log_op, "\n"); } free(log_name); terminate_banner = banner; } void skip_mem_dump(void) { skip_mem_check_final = true; } void enable_mem_log_termination(void) { atexit(keepalived_free_final); } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_9
crossvul-cpp_data_bad_1471_2
404: Not Found
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1471_2
crossvul-cpp_data_bad_2235_0
/* * * Copyright (C) 2006-2011 Anders Brander <anders@brander.dk>, * * Anders Kvist <akv@lnxbx.dk> and Klaus Post <klauspost@gmail.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdlib.h> /* system() */ #include <rawstudio.h> #include "rs-filter.h" #if 0 /* Change to 1 to enable performance info */ #define filter_performance printf #define FILTER_SHOW_PERFORMANCE #else #define filter_performance(...) {} #endif /* How much time should a filter at least have taken to show performance number */ #define FILTER_PERF_ELAPSED_MIN 0.001 #define CHAIN_PERF_ELAPSED_MIN 0.001 G_DEFINE_TYPE (RSFilter, rs_filter, G_TYPE_OBJECT) enum { CHANGED_SIGNAL, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = { 0 }; static void dispose(GObject *obj) { RSFilter *filter = RS_FILTER(obj); if (!filter->dispose_has_run) { filter->dispose_has_run = TRUE; if (filter->previous) { filter->previous->next_filters = g_slist_remove(filter->previous->next_filters, filter); g_object_unref(filter->previous); } } } static void rs_filter_class_init(RSFilterClass *klass) { RS_DEBUG(FILTERS, "rs_filter_class_init(%p)", klass); GObjectClass *object_class = G_OBJECT_CLASS(klass); signals[CHANGED_SIGNAL] = g_signal_new ("changed", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION, 0, NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); klass->get_image = NULL; klass->get_image8 = NULL; klass->get_size = NULL; klass->previous_changed = NULL; object_class->dispose = dispose; } static void rs_filter_init(RSFilter *self) { RS_DEBUG(FILTERS, "rs_filter_init(%p)", self); self->previous = NULL; self->next_filters = NULL; self->enabled = TRUE; } /** * Return a new instance of a RSFilter * @param name The name of the filter * @param previous The previous filter or NULL * @return The newly instantiated RSFilter or NULL */ RSFilter * rs_filter_new(const gchar *name, RSFilter *previous) { RS_DEBUG(FILTERS, "rs_filter_new(%s, %s [%p])", name, RS_FILTER_NAME(previous), previous); g_return_val_if_fail(name != NULL, NULL); g_return_val_if_fail((previous == NULL) || RS_IS_FILTER(previous), NULL); GType type = g_type_from_name(name); RSFilter *filter = NULL; if (g_type_is_a (type, RS_TYPE_FILTER)) filter = g_object_new(type, NULL); if (!RS_IS_FILTER(filter)) g_warning("Could not instantiate filter of type \"%s\"", name); if (previous) rs_filter_set_previous(filter, previous); return filter; } /** * Set the previous RSFilter in a RSFilter-chain * @param filter A RSFilter * @param previous A previous RSFilter */ void rs_filter_set_previous(RSFilter *filter, RSFilter *previous) { RS_DEBUG(FILTERS, "rs_filter_set_previous(%p, %p)", filter, previous); g_return_if_fail(RS_IS_FILTER(filter)); g_return_if_fail(RS_IS_FILTER(previous)); /* We will only set the previous filter if it differs from current previous filter */ if (filter->previous != previous) { if (filter->previous) { /* If we already got a previous filter, clean up */ filter->previous->next_filters = g_slist_remove(filter->previous->next_filters, filter); g_object_unref(filter->previous); } filter->previous = g_object_ref(previous); previous->next_filters = g_slist_append(previous->next_filters, filter); } } /** * Signal that a filter has changed, filters depending on this will be invoked * This should only be called from filter code * @param filter The changed filter * @param mask A mask indicating what changed */ void rs_filter_changed(RSFilter *filter, RSFilterChangedMask mask) { RS_DEBUG(FILTERS, "rs_filter_changed(%s [%p], %04x)", RS_FILTER_NAME(filter), filter, mask); g_return_if_fail(RS_IS_FILTER(filter)); gint i, n_next = g_slist_length(filter->next_filters); for(i=0; i<n_next; i++) { RSFilter *next = RS_FILTER(g_slist_nth_data(filter->next_filters, i)); g_assert(RS_IS_FILTER(next)); /* Notify "next" filter or try "next next" filter */ if (RS_FILTER_GET_CLASS(next)->previous_changed) RS_FILTER_GET_CLASS(next)->previous_changed(next, filter, mask); else rs_filter_changed(next, mask); } g_signal_emit(G_OBJECT(filter), signals[CHANGED_SIGNAL], 0, mask); } /* Clamps ROI rectangle to image size */ /* Returns a new rectangle, or NULL if ROI was within bounds*/ static GdkRectangle* clamp_roi(const GdkRectangle *roi, RSFilter *filter, const RSFilterRequest *request) { RSFilterResponse *response = rs_filter_get_size(filter, request); gint w = rs_filter_response_get_width(response); gint h = rs_filter_response_get_height(response); g_object_unref(response); if ((roi->x >= 0) && (roi->y >=0) && (roi->x + roi->width <= w) && (roi->y + roi->height <= h)) return NULL; GdkRectangle* new_roi = g_new(GdkRectangle, 1); new_roi->x = MAX(0, roi->x); new_roi->y = MAX(0, roi->y); new_roi->width = MIN(w - new_roi->x, roi->width); new_roi->height = MAX(h - new_roi->y, roi->height); return new_roi; } /** * Get the output image from a RSFilter * @param filter A RSFilter * @param param A RSFilterRequest defining parameters for a image request * @return A RS_IMAGE16, this must be unref'ed */ RSFilterResponse * rs_filter_get_image(RSFilter *filter, const RSFilterRequest *request) { GdkRectangle* roi = NULL; RSFilterRequest *r = NULL; g_return_val_if_fail(RS_IS_FILTER(filter), NULL); g_return_val_if_fail(RS_IS_FILTER_REQUEST(request), NULL); RS_DEBUG(FILTERS, "rs_filter_get_image(%s [%p])", RS_FILTER_NAME(filter), filter); /* This timer-hack will break badly when multithreaded! */ static gfloat last_elapsed = 0.0; static gint count = -1; gfloat elapsed; static GTimer *gt = NULL; RSFilterResponse *response; RS_IMAGE16 *image; if (count == -1) gt = g_timer_new(); count++; if (filter->enabled && (roi = rs_filter_request_get_roi(request))) { roi = clamp_roi(roi, filter, request); if (roi) { r = rs_filter_request_clone(request); rs_filter_request_set_roi(r, roi); request = r; } } if (RS_FILTER_GET_CLASS(filter)->get_image && filter->enabled) response = RS_FILTER_GET_CLASS(filter)->get_image(filter, request); else response = rs_filter_get_image(filter->previous, request); g_assert(RS_IS_FILTER_RESPONSE(response)); image = rs_filter_response_get_image(response); elapsed = g_timer_elapsed(gt, NULL) - last_elapsed; if (roi) g_free(roi); if (r) g_object_unref(r); #ifdef FILTER_SHOW_PERFORMANCE if ((elapsed > FILTER_PERF_ELAPSED_MIN) && (image != NULL)) { gint iw = image->w; gint ih = image->h; if (rs_filter_response_get_roi(response)) { roi = rs_filter_response_get_roi(response); iw = roi->width; ih = roi->height; } filter_performance("%s took: \033[32m%.0f\033[0mms", RS_FILTER_NAME(filter), elapsed*1000); if ((elapsed > 0.001) && (image != NULL)) filter_performance(" [\033[33m%.01f\033[0mMpix/s]", ((gfloat)(iw*ih))/elapsed/1000000.0); if (image) filter_performance(" [w: %d, h: %d, roi-w:%d, roi-h:%d, channels: %d, pixelsize: %d, rowstride: %d]", image->w, image->h, iw, ih, image->channels, image->pixelsize, image->rowstride); filter_performance("\n"); } #endif g_assert(RS_IS_IMAGE16(image) || (image == NULL)); last_elapsed += elapsed; count--; if (count == -1) { last_elapsed = 0.0; if (g_timer_elapsed(gt,NULL) > CHAIN_PERF_ELAPSED_MIN) filter_performance("Complete 16 bit chain took: \033[32m%.0f\033[0mms\n\n", g_timer_elapsed(gt, NULL)*1000.0); rs_filter_param_set_float(RS_FILTER_PARAM(response), "16-bit-time", g_timer_elapsed(gt, NULL)); g_timer_destroy(gt); } if (image) g_object_unref(image); return response; } /** * Get 8 bit output image from a RSFilter * @param filter A RSFilter * @param param A RSFilterRequest defining parameters for a image request * @return A RS_IMAGE16, this must be unref'ed */ RSFilterResponse * rs_filter_get_image8(RSFilter *filter, const RSFilterRequest *request) { g_return_val_if_fail(RS_IS_FILTER(filter), NULL); g_return_val_if_fail(RS_IS_FILTER_REQUEST(request), NULL); RS_DEBUG(FILTERS, "rs_filter_get_image8(%s [%p])", RS_FILTER_NAME(filter), filter); /* This timer-hack will break badly when multithreaded! */ static gfloat last_elapsed = 0.0; static gint count = -1; gfloat elapsed, temp; static GTimer *gt = NULL; RSFilterResponse *response = NULL; GdkPixbuf *image = NULL; GdkRectangle* roi = NULL; RSFilterRequest *r = NULL; g_return_val_if_fail(RS_IS_FILTER(filter), NULL); g_return_val_if_fail(RS_IS_FILTER_REQUEST(request), NULL); if (count == -1) gt = g_timer_new(); count++; if (filter->enabled && (roi = rs_filter_request_get_roi(request))) { roi = clamp_roi(roi, filter, request); if (roi) { r = rs_filter_request_clone(request); rs_filter_request_set_roi(r, roi); request = r; } } if (RS_FILTER_GET_CLASS(filter)->get_image8 && filter->enabled) response = RS_FILTER_GET_CLASS(filter)->get_image8(filter, request); else if (filter->previous) response = rs_filter_get_image8(filter->previous, request); g_assert(RS_IS_FILTER_RESPONSE(response)); image = rs_filter_response_get_image8(response); elapsed = g_timer_elapsed(gt, NULL) - last_elapsed; /* Subtract 16 bit time */ if (rs_filter_param_get_float(RS_FILTER_PARAM(response), "16-bit-time", &temp)) elapsed -= temp; if (roi) g_free(roi); if (r) g_object_unref(r); #ifdef FILTER_SHOW_PERFORMANCE if ((elapsed > FILTER_PERF_ELAPSED_MIN) && (image != NULL)) { gint iw = gdk_pixbuf_get_width(image); gint ih = gdk_pixbuf_get_height(image); if (rs_filter_response_get_roi(response)) { GdkRectangle *roi = rs_filter_response_get_roi(response); iw = roi->width; ih = roi->height; } filter_performance("%s took: \033[32m%.0f\033[0mms", RS_FILTER_NAME(filter), elapsed * 1000); filter_performance(" [\033[33m%.01f\033[0mMpix/s]", ((gfloat)(iw * ih)) / elapsed / 1000000.0); filter_performance("\n"); } #endif last_elapsed += elapsed; g_assert(GDK_IS_PIXBUF(image) || (image == NULL)); count--; if (count == -1) { last_elapsed = 0.0; rs_filter_param_get_float(RS_FILTER_PARAM(response), "16-bit-time", &last_elapsed); last_elapsed = g_timer_elapsed(gt, NULL)-last_elapsed; if (last_elapsed > CHAIN_PERF_ELAPSED_MIN) filter_performance("Complete 8 bit chain took: \033[32m%.0f\033[0mms\n\n", last_elapsed*1000.0); g_timer_destroy(gt); last_elapsed = 0.0; } if (image) g_object_unref(image); return response; } /** * Get predicted size of a RSFilter * @param filter A RSFilter * @param request A RSFilterRequest defining parameters for the request */ RSFilterResponse * rs_filter_get_size(RSFilter *filter, const RSFilterRequest *request) { RSFilterResponse *response = NULL; g_return_val_if_fail(RS_IS_FILTER(filter), NULL); g_return_val_if_fail(RS_IS_FILTER_REQUEST(request), NULL); if (RS_FILTER_GET_CLASS(filter)->get_size && filter->enabled) response = RS_FILTER_GET_CLASS(filter)->get_size(filter, request); else if (filter->previous) response = rs_filter_get_size(filter->previous, request); return response; } /** * Get predicted size of a RSFilter * @param filter A RSFilter * @param request A RSFilterRequest defining parameters for the request * @param width A pointer to a gint where the width will be written or NULL * @param height A pointer to a gint where the height will be written or NULL * @return TRUE if width/height is known, FALSE otherwise */ gboolean rs_filter_get_size_simple(RSFilter *filter, const RSFilterRequest *request, gint *width, gint *height) { gint w, h; RSFilterResponse *response; g_return_val_if_fail(RS_IS_FILTER(filter), FALSE); g_return_val_if_fail(RS_IS_FILTER_REQUEST(request), FALSE); response = rs_filter_get_size(filter, request); if (!RS_IS_FILTER_RESPONSE(response)) return FALSE; w = rs_filter_response_get_width(response); h = rs_filter_response_get_height(response); if (width) *width = w; if (height) *height = h; g_object_unref(response); return ((w>0) && (h>0)); } /** * Set a GObject property on zero or more filters above #filter recursively * @param filter A RSFilter * @param ... Pairs of property names and values followed by NULL */ void rs_filter_set_recursive(RSFilter *filter, ...) { va_list ap; gchar *property_name; RSFilter *current_filter; GParamSpec *spec; RSFilter *first_seen_here = NULL; GTypeValueTable *table = NULL; GType type = 0; union CValue { gint v_int; glong v_long; gint64 v_int64; gdouble v_double; gpointer v_pointer; } value; g_return_if_fail(RS_IS_FILTER(filter)); va_start(ap, filter); /* Loop through all properties */ while ((property_name = va_arg(ap, gchar *))) { /* We set table to NULL for every property to indicate that we (again) * have an "unknown" type */ table = NULL; current_filter = filter; /* Iterate through all filters previous to filter */ do { if ((spec = g_object_class_find_property(G_OBJECT_GET_CLASS(current_filter), property_name))) if (spec->flags & G_PARAM_WRITABLE) { /* If we got no GTypeValueTable at this point, we aquire * one. We rely on all filters using the same type for all * properties equally named */ if (!table) { first_seen_here = current_filter; type = spec->value_type; table = g_type_value_table_peek(type); /* If we have no valuetable, we're screwed, bail out */ if (!table) g_error("No GTypeValueTable found for '%s'", g_type_name(type)); switch (table->collect_format[0]) { case 'i': value.v_int = va_arg(ap, gint); break; case 'l': value.v_long = va_arg(ap, glong); break; case 'd': value.v_double = va_arg(ap, gdouble); break; case 'p': value.v_pointer = va_arg(ap, gpointer); break; default: g_error("Don't know how to collect for '%s'", g_type_name(type)); break; } } if (table) { /* We try to catch cases where different filters use * the same property name for different types */ if (type != spec->value_type) g_warning("Diverging types found for property '%s' (on filter '%s' and '%s')", property_name, RS_FILTER_NAME(first_seen_here), RS_FILTER_NAME(current_filter)); switch (table->collect_format[0]) { case 'i': g_object_set(current_filter, property_name, value.v_int, NULL); break; case 'l': g_object_set(current_filter, property_name, value.v_long, NULL); break; case 'd': g_object_set(current_filter, property_name, value.v_double, NULL); break; case 'p': g_object_set(current_filter, property_name, value.v_pointer, NULL); break; default: break; } } } } while (RS_IS_FILTER(current_filter = current_filter->previous)); if (!table) { // g_warning("Property: %s could not be found in filter chain. Skipping further properties", property_name); va_end(ap); return; } } va_end(ap); } /** * Get a GObject property from a RSFilter chain recursively * @param filter A RSFilter * @param ... Pairs of property names and a return pointers followed by NULL */ void rs_filter_get_recursive(RSFilter *filter, ...) { va_list ap; gchar *property_name; gpointer property_ret; RSFilter *current_filter; g_return_if_fail(RS_IS_FILTER(filter)); va_start(ap, filter); /* Loop through all properties */ while ((property_name = va_arg(ap, gchar *))) { property_ret = va_arg(ap, gpointer); g_assert(property_ret != NULL); current_filter = filter; /* Iterate through all filter previous to filter */ do { if (current_filter->enabled && g_object_class_find_property(G_OBJECT_GET_CLASS(current_filter), property_name)) { g_object_get(current_filter, property_name, property_ret, NULL); break; } } while (RS_IS_FILTER(current_filter = current_filter->previous)); } va_end(ap); } /** * Set enabled state of a RSFilter * @param filter A RSFilter * @param enabled TRUE to enable filter, FALSE to disable * @return Previous state */ gboolean rs_filter_set_enabled(RSFilter *filter, gboolean enabled) { gboolean previous_state; g_return_val_if_fail(RS_IS_FILTER(filter), FALSE); previous_state = filter->enabled; if (filter->enabled != enabled) { filter->enabled = enabled; rs_filter_changed(filter, RS_FILTER_CHANGED_PIXELDATA); } return previous_state; } /** * Get enabled state of a RSFilter * @param filter A RSFilter * @return TRUE if filter is enabled, FALSE if disabled */ gboolean rs_filter_get_enabled(RSFilter *filter) { g_return_val_if_fail(RS_IS_FILTER(filter), FALSE); return filter->enabled; } /** * Set a label for a RSFilter - only used for debugging * @param filter A RSFilter * @param label A new label for the RSFilter, this will NOT be copied */ extern void rs_filter_set_label(RSFilter *filter, const gchar *label) { g_return_if_fail(RS_IS_FILTER(filter)); filter->label = label; } /** * Get the label for a RSFilter * @param filter A RSFilter * @return The label for the RSFilter or NULL */ const gchar * rs_filter_get_label(RSFilter *filter) { g_return_val_if_fail(RS_IS_FILTER(filter), ""); return filter->label; } static void rs_filter_graph_helper(GString *str, RSFilter *filter) { g_assert(str != NULL); g_assert(RS_IS_FILTER(filter)); g_string_append_printf(str, "\"%p\" [\n\tshape=\"Mrecord\"\n", filter); if (!g_str_equal(RS_FILTER_NAME(filter), "RSCache")) g_string_append_printf(str, "\tcolor=grey\n\tstyle=filled\n"); if (filter->enabled) g_string_append_printf(str, "\tcolor=\"#66ba66\"\n"); else g_string_append_printf(str, "\tcolor=grey\n"); g_string_append_printf(str, "\tlabel=<<table cellborder=\"0\" border=\"0\">\n"); GObjectClass *klass = G_OBJECT_GET_CLASS(filter); GParamSpec **specs; gint i; guint n_specs = 0; /* Filter name (and label) */ g_string_append_printf(str, "\t\t<tr>\n\t\t\t<td colspan=\"2\" bgcolor=\"black\"><font color=\"white\">%s", RS_FILTER_NAME(filter)); if (filter->label) g_string_append_printf(str, " (%s)", filter->label); g_string_append_printf(str, "</font></td>\n\t\t</tr>\n"); /* Parameter and value list */ specs = g_object_class_list_properties(G_OBJECT_CLASS(klass), &n_specs); for(i=0; i<n_specs; i++) { gboolean boolean = FALSE; gint integer = 0; gfloat loat = 0.0; gchar *ostr = NULL; g_string_append_printf(str, "\t\t<tr>\n\t\t\t<td align=\"right\">%s:</td>\n\t\t\t<td align=\"left\">", specs[i]->name); /* We have to use if/else here, because RS_TYPE_* does not resolve to a constant */ if (G_PARAM_SPEC_VALUE_TYPE(specs[i]) == RS_TYPE_LENS) { RSLens *lens; gchar *identifier; g_object_get(filter, specs[i]->name, &lens, NULL); if (lens) { g_object_get(lens, "identifier", &identifier, NULL); g_object_unref(lens); g_string_append_printf(str, "%s", identifier); g_free(identifier); } else g_string_append_printf(str, "n/a"); } else if (G_PARAM_SPEC_VALUE_TYPE(specs[i]) == RS_TYPE_ICC_PROFILE) { RSIccProfile *profile; gchar *profile_filename; gchar *profile_basename; g_object_get(filter, specs[i]->name, &profile, NULL); g_object_get(profile, "filename", &profile_filename, NULL); g_object_unref(profile); profile_basename = g_path_get_basename (profile_filename); g_free(profile_filename); g_string_append_printf(str, "%s", profile_basename); g_free(profile_basename); } else switch (G_PARAM_SPEC_VALUE_TYPE(specs[i])) { case G_TYPE_BOOLEAN: g_object_get(filter, specs[i]->name, &boolean, NULL); g_string_append_printf(str, "%s", (boolean) ? "TRUE" : "FALSE"); break; case G_TYPE_INT: g_object_get(filter, specs[i]->name, &integer, NULL); g_string_append_printf(str, "%d", integer); break; case G_TYPE_FLOAT: g_object_get(filter, specs[i]->name, &loat, NULL); g_string_append_printf(str, "%.05f", loat); break; case G_TYPE_STRING: g_object_get(filter, specs[i]->name, &ostr, NULL); g_string_append_printf(str, "%s", ostr); break; default: g_string_append_printf(str, "n/a"); break; } g_string_append_printf(str, "</td>\n\t\t</tr>\n"); } g_string_append_printf(str, "\t\t</table>>\n\t];\n"); gint n_next = g_slist_length(filter->next_filters); for(i=0; i<n_next; i++) { RSFilter *next = RS_FILTER(g_slist_nth_data(filter->next_filters, i)); RSFilterResponse *response = rs_filter_get_size(filter, RS_FILTER_REQUEST_QUICK); /* Edge - print dimensions along */ g_string_append_printf(str, "\t\"%p\" -> \"%p\" [label=\" %dx%d\"];\n", filter, next, rs_filter_response_get_width(response), rs_filter_response_get_height(response)); g_object_unref(response); /* Recursively call ourself for every "next" filter */ rs_filter_graph_helper(str, next); } } /** * Draw a nice graph of the filter chain * note: Requires graphviz * @param filter The top-most filter to graph */ void rs_filter_graph(RSFilter *filter) { g_return_if_fail(RS_IS_FILTER(filter)); GString *str = g_string_new("digraph G {\n"); rs_filter_graph_helper(str, filter); g_string_append_printf(str, "}\n"); g_file_set_contents("/tmp/rs-filter-graph", str->str, str->len, NULL); if (0 != system("dot -Tpng >/tmp/rs-filter-graph.png </tmp/rs-filter-graph")) g_warning("Calling dot failed"); if (0 != system("gnome-open /tmp/rs-filter-graph.png")) g_warning("Calling gnome-open failed."); g_string_free(str, TRUE); }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_2235_0
crossvul-cpp_data_good_436_2
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: SMTP WRAPPER connect to a specified smtp server and send mail * using the smtp protocol according to the RFC 821. A non blocking * timeouted connection is used to handle smtp protocol. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <errno.h> #include <unistd.h> #include <time.h> #include "smtp.h" #include "memory.h" #include "layer4.h" #include "logger.h" #include "utils.h" #if !HAVE_DECL_SOCK_CLOEXEC #include "old_socket.h" #endif #ifdef _WITH_LVS_ #include "check_api.h" #endif #ifdef THREAD_DUMP #include "scheduler.h" #endif #ifdef _SMTP_ALERT_DEBUG_ bool do_smtp_alert_debug; #endif /* SMTP FSM definition */ static int connection_error(thread_t *); static int connection_in_progress(thread_t *); static int connection_timeout(thread_t *); static int connection_success(thread_t *); static int helo_cmd(thread_t *); static int mail_cmd(thread_t *); static int rcpt_cmd(thread_t *); static int data_cmd(thread_t *); static int body_cmd(thread_t *); static int quit_cmd(thread_t *); static int connection_code(thread_t *, int); static int helo_code(thread_t *, int); static int mail_code(thread_t *, int); static int rcpt_code(thread_t *, int); static int data_code(thread_t *, int); static int body_code(thread_t *, int); static int quit_code(thread_t *, int); static int smtp_read_thread(thread_t *); static int smtp_send_thread(thread_t *); struct { int (*send) (thread_t *); int (*read) (thread_t *, int); } SMTP_FSM[SMTP_MAX_FSM_STATE] = { /* Stream Write Handlers | Stream Read handlers * *-------------------------------+--------------------------*/ {connection_error, NULL}, /* connect_error */ {connection_in_progress, NULL}, /* connect_in_progress */ {connection_timeout, NULL}, /* connect_timeout */ {connection_success, connection_code}, /* connect_success */ {helo_cmd, helo_code}, /* HELO */ {mail_cmd, mail_code}, /* MAIL */ {rcpt_cmd, rcpt_code}, /* RCPT */ {data_cmd, data_code}, /* DATA */ {body_cmd, body_code}, /* BODY */ {quit_cmd, quit_code} /* QUIT */ }; static void free_smtp_all(smtp_t * smtp) { FREE(smtp->buffer); FREE(smtp->subject); FREE(smtp->body); FREE(smtp->email_to); FREE(smtp); } static char * fetch_next_email(smtp_t * smtp) { return list_element(global_data->email, smtp->email_it); } /* layer4 connection handlers */ static int connection_error(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); log_message(LOG_INFO, "SMTP connection ERROR to %s." , FMT_SMTP_HOST()); free_smtp_all(smtp); return 0; } static int connection_timeout(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); log_message(LOG_INFO, "Timeout connecting SMTP server %s." , FMT_SMTP_HOST()); free_smtp_all(smtp); return 0; } static int connection_in_progress(thread_t * thread) { int status; DBG("SMTP connection to %s now IN_PROGRESS.", FMT_SMTP_HOST()); /* * Here we use the propriety of a union structure, * each element of the structure have the same value. */ status = tcp_socket_state(thread, connection_in_progress); if (status != connect_in_progress) SMTP_FSM_SEND(status, thread); return 0; } static int connection_success(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); log_message(LOG_INFO, "Remote SMTP server %s connected." , FMT_SMTP_HOST()); smtp->stage = connect_success; thread_add_read(thread->master, smtp_read_thread, smtp, smtp->fd, global_data->smtp_connection_to); return 0; } /* SMTP protocol handlers */ static int smtp_read_thread(thread_t * thread) { smtp_t *smtp; char *buffer; char *reply; ssize_t rcv_buffer_size; int status = -1; smtp = THREAD_ARG(thread); if (thread->type == THREAD_READ_TIMEOUT) { log_message(LOG_INFO, "Timeout reading data to remote SMTP server %s." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); return -1; } buffer = smtp->buffer; rcv_buffer_size = read(thread->u.fd, buffer + smtp->buflen, SMTP_BUFFER_LENGTH - smtp->buflen); if (rcv_buffer_size == -1) { if (errno == EAGAIN) goto end; log_message(LOG_INFO, "Error reading data from remote SMTP server %s." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); return 0; } else if (rcv_buffer_size == 0) { log_message(LOG_INFO, "Remote SMTP server %s has closed the connection." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); return 0; } /* received data overflow buffer size ? */ if (smtp->buflen >= SMTP_BUFFER_MAX) { log_message(LOG_INFO, "Received buffer from remote SMTP server %s" " overflow our get read buffer length." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); return 0; } else { smtp->buflen += (size_t)rcv_buffer_size; buffer[smtp->buflen] = 0; /* NULL terminate */ } end: /* parse the buffer, finding the last line of the response for the code */ reply = buffer; while (reply < buffer + smtp->buflen) { char *p; p = strstr(reply, "\r\n"); if (!p) { memmove(buffer, reply, smtp->buflen - (size_t)(reply - buffer)); smtp->buflen -= (size_t)(reply - buffer); buffer[smtp->buflen] = 0; thread_add_read(thread->master, smtp_read_thread, smtp, thread->u.fd, global_data->smtp_connection_to); return 0; } if (reply[3] == '-') { /* Skip over the \r\n */ reply = p + 2; continue; } status = ((reply[0] - '0') * 100) + ((reply[1] - '0') * 10) + (reply[2] - '0'); reply = p + 2; break; } memmove(buffer, reply, smtp->buflen - (size_t)(reply - buffer)); smtp->buflen -= (size_t)(reply - buffer); buffer[smtp->buflen] = 0; if (status == -1) { thread_add_read(thread->master, smtp_read_thread, smtp, thread->u.fd, global_data->smtp_connection_to); return 0; } SMTP_FSM_READ(smtp->stage, thread, status); /* Registering next smtp command processing thread */ if (smtp->stage != ERROR) { thread_add_write(thread->master, smtp_send_thread, smtp, smtp->fd, global_data->smtp_connection_to); } else { log_message(LOG_INFO, "Can not read data from remote SMTP server %s." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); } return 0; } static int smtp_send_thread(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); if (thread->type == THREAD_WRITE_TIMEOUT) { log_message(LOG_INFO, "Timeout sending data to remote SMTP server %s." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); return 0; } SMTP_FSM_SEND(smtp->stage, thread); /* Handle END command */ if (smtp->stage == END) { SMTP_FSM_READ(QUIT, thread, 0); return 0; } /* Registering next smtp command processing thread */ if (smtp->stage != ERROR) { thread_add_read(thread->master, smtp_read_thread, smtp, thread->u.fd, global_data->smtp_connection_to); thread_del_write(thread); } else { log_message(LOG_INFO, "Can not send data to remote SMTP server %s." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); } return 0; } static int connection_code(thread_t * thread, int status) { smtp_t *smtp = THREAD_ARG(thread); if (status == 220) { smtp->stage++; } else { log_message(LOG_INFO, "Error connecting SMTP server %s." " SMTP status code = %d" , FMT_SMTP_HOST() , status); smtp->stage = ERROR; } return 0; } /* HELO command processing */ static int helo_cmd(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); char *buffer; buffer = (char *) MALLOC(SMTP_BUFFER_MAX); snprintf(buffer, SMTP_BUFFER_MAX, SMTP_HELO_CMD, (global_data->smtp_helo_name) ? global_data->smtp_helo_name : "localhost"); if (send(thread->u.fd, buffer, strlen(buffer), 0) == -1) smtp->stage = ERROR; FREE(buffer); return 0; } static int helo_code(thread_t * thread, int status) { smtp_t *smtp = THREAD_ARG(thread); if (status == 250) { smtp->stage++; } else { log_message(LOG_INFO, "Error processing HELO cmd on SMTP server %s." " SMTP status code = %d" , FMT_SMTP_HOST() , status); smtp->stage = ERROR; } return 0; } /* MAIL command processing */ static int mail_cmd(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); char *buffer; buffer = (char *) MALLOC(SMTP_BUFFER_MAX); snprintf(buffer, SMTP_BUFFER_MAX, SMTP_MAIL_CMD, global_data->email_from); if (send(thread->u.fd, buffer, strlen(buffer), 0) == -1) smtp->stage = ERROR; FREE(buffer); return 0; } static int mail_code(thread_t * thread, int status) { smtp_t *smtp = THREAD_ARG(thread); if (status == 250) { smtp->stage++; } else { log_message(LOG_INFO, "Error processing MAIL cmd on SMTP server %s." " SMTP status code = %d" , FMT_SMTP_HOST() , status); smtp->stage = ERROR; } return 0; } /* RCPT command processing */ static int rcpt_cmd(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); char *buffer; char *fetched_email; buffer = (char *) MALLOC(SMTP_BUFFER_MAX); /* We send RCPT TO command multiple time to add all our email receivers. * --rfc821.3.1 */ fetched_email = fetch_next_email(smtp); snprintf(buffer, SMTP_BUFFER_MAX, SMTP_RCPT_CMD, fetched_email); if (send(thread->u.fd, buffer, strlen(buffer), 0) == -1) smtp->stage = ERROR; FREE(buffer); return 0; } static int rcpt_code(thread_t * thread, int status) { smtp_t *smtp = THREAD_ARG(thread); char *fetched_email; if (status == 250) { smtp->email_it++; fetched_email = fetch_next_email(smtp); if (!fetched_email) smtp->stage++; } else { log_message(LOG_INFO, "Error processing RCPT cmd on SMTP server %s." " SMTP status code = %d" , FMT_SMTP_HOST() , status); smtp->stage = ERROR; } return 0; } /* DATA command processing */ static int data_cmd(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); if (send(thread->u.fd, SMTP_DATA_CMD, strlen(SMTP_DATA_CMD), 0) == -1) smtp->stage = ERROR; return 0; } static int data_code(thread_t * thread, int status) { smtp_t *smtp = THREAD_ARG(thread); if (status == 354) { smtp->stage++; } else { log_message(LOG_INFO, "Error processing DATA cmd on SMTP server %s." " SMTP status code = %d" , FMT_SMTP_HOST() , status); smtp->stage = ERROR; } return 0; } /* BODY command processing. * Do we need to use mutli-thread for multi-part body * handling ? Don t really think :) */ static int body_cmd(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); char *buffer; char rfc822[80]; time_t now; struct tm *t; buffer = (char *) MALLOC(SMTP_BUFFER_MAX); time(&now); t = localtime(&now); strftime(rfc822, sizeof(rfc822), "%a, %d %b %Y %H:%M:%S %z", t); snprintf(buffer, SMTP_BUFFER_MAX, SMTP_HEADERS_CMD, rfc822, global_data->email_from, smtp->subject, smtp->email_to); /* send the subject field */ if (send(thread->u.fd, buffer, strlen(buffer), 0) == -1) smtp->stage = ERROR; memset(buffer, 0, SMTP_BUFFER_MAX); snprintf(buffer, SMTP_BUFFER_MAX, SMTP_BODY_CMD, smtp->body); /* send the the body field */ if (send(thread->u.fd, buffer, strlen(buffer), 0) == -1) smtp->stage = ERROR; /* send the sending dot */ if (send(thread->u.fd, SMTP_SEND_CMD, strlen(SMTP_SEND_CMD), 0) == -1) smtp->stage = ERROR; FREE(buffer); return 0; } static int body_code(thread_t * thread, int status) { smtp_t *smtp = THREAD_ARG(thread); if (status == 250) { log_message(LOG_INFO, "SMTP alert successfully sent."); smtp->stage++; } else { log_message(LOG_INFO, "Error processing DOT cmd on SMTP server %s." " SMTP status code = %d" , FMT_SMTP_HOST() , status); smtp->stage = ERROR; } return 0; } /* QUIT command processing */ static int quit_cmd(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); if (send(thread->u.fd, SMTP_QUIT_CMD, strlen(SMTP_QUIT_CMD), 0) == -1) smtp->stage = ERROR; else smtp->stage++; return 0; } static int quit_code(thread_t * thread, __attribute__((unused)) int status) { smtp_t *smtp = THREAD_ARG(thread); /* final state, we are disconnected from the remote host */ free_smtp_all(smtp); thread_close_fd(thread); return 0; } /* connect remote SMTP server */ static void smtp_connect(smtp_t * smtp) { enum connect_result status; if ((smtp->fd = socket(global_data->smtp_server.ss_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, IPPROTO_TCP)) == -1) { DBG("SMTP connect fail to create socket."); free_smtp_all(smtp); return; } #if !HAVE_DECL_SOCK_NONBLOCK if (set_sock_flags(smtp->fd, F_SETFL, O_NONBLOCK)) log_message(LOG_INFO, "Unable to set NONBLOCK on smtp_connect socket - %s (%d)", strerror(errno), errno); #endif #if !HAVE_DECL_SOCK_CLOEXEC if (set_sock_flags(smtp->fd, F_SETFD, FD_CLOEXEC)) log_message(LOG_INFO, "Unable to set CLOEXEC on smtp_connect socket - %s (%d)", strerror(errno), errno); #endif status = tcp_connect(smtp->fd, &global_data->smtp_server); /* Handle connection status code */ thread_add_event(master, SMTP_FSM[status].send, smtp, smtp->fd); } #ifdef _SMTP_ALERT_DEBUG_ static void smtp_log_to_file(smtp_t *smtp) { FILE *fp = fopen_safe("/tmp/smtp-alert.log", "a"); time_t now; struct tm tm; char time_buf[25]; int time_buf_len; time(&now); localtime_r(&now, &tm); time_buf_len = strftime(time_buf, sizeof time_buf, "%a %b %e %X %Y", &tm); fprintf(fp, "%s: %s -> %s\n" "%*sSubject: %s\n" "%*sBody: %s\n\n", time_buf, global_data->email_from, smtp->email_to, time_buf_len - 7, "", smtp->subject, time_buf_len - 7, "", smtp->body); fclose(fp); free_smtp_all(smtp); } #endif /* * Build a comma separated string of smtp recipient email addresses * for the email message To-header. */ static void build_to_header_rcpt_addrs(smtp_t *smtp) { char *fetched_email; char *email_to_addrs; size_t bytes_available = SMTP_BUFFER_MAX - 1; size_t bytes_to_write; if (smtp == NULL) return; email_to_addrs = smtp->email_to; smtp->email_it = 0; while (1) { fetched_email = fetch_next_email(smtp); if (fetched_email == NULL) break; bytes_to_write = strlen(fetched_email); if (!smtp->email_it) { if (bytes_available < bytes_to_write) break; } else { if (bytes_available < 2 + bytes_to_write) break; /* Prepend with a comma and space to all non-first email addresses */ *email_to_addrs++ = ','; *email_to_addrs++ = ' '; bytes_available -= 2; } if (snprintf(email_to_addrs, bytes_to_write + 1, "%s", fetched_email) != (int)bytes_to_write) { /* Inconsistent state, no choice but to break here and do nothing */ break; } email_to_addrs += bytes_to_write; bytes_available -= bytes_to_write; smtp->email_it++; } smtp->email_it = 0; } /* Main entry point */ void smtp_alert(smtp_msg_t msg_type, void* data, const char *subject, const char *body) { smtp_t *smtp; #ifdef _WITH_VRRP_ vrrp_t *vrrp; vrrp_sgroup_t *vgroup; #endif #ifdef _WITH_LVS_ checker_t *checker; virtual_server_t *vs; smtp_rs *rs_info; #endif /* Only send mail if email specified */ if (LIST_ISEMPTY(global_data->email) || !global_data->smtp_server.ss_family) return; /* allocate & initialize smtp argument data structure */ smtp = (smtp_t *) MALLOC(sizeof(smtp_t)); smtp->subject = (char *) MALLOC(MAX_HEADERS_LENGTH); smtp->body = (char *) MALLOC(MAX_BODY_LENGTH); smtp->buffer = (char *) MALLOC(SMTP_BUFFER_MAX); smtp->email_to = (char *) MALLOC(SMTP_BUFFER_MAX); /* format subject if rserver is specified */ #ifdef _WITH_LVS_ if (msg_type == SMTP_MSG_RS) { checker = (checker_t *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] Realserver %s of virtual server %s - %s", global_data->router_id, FMT_RS(checker->rs, checker->vs), FMT_VS(checker->vs), checker->rs->alive ? "UP" : "DOWN"); } else if (msg_type == SMTP_MSG_VS) { vs = (virtual_server_t *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] Virtualserver %s - %s", global_data->router_id, FMT_VS(vs), subject); } else if (msg_type == SMTP_MSG_RS_SHUT) { rs_info = (smtp_rs *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] Realserver %s of virtual server %s - %s", global_data->router_id, FMT_RS(rs_info->rs, rs_info->vs), FMT_VS(rs_info->vs), subject); } else #endif #ifdef _WITH_VRRP_ if (msg_type == SMTP_MSG_VRRP) { vrrp = (vrrp_t *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] VRRP Instance %s - %s", global_data->router_id, vrrp->iname, subject); } else if (msg_type == SMTP_MSG_VGROUP) { vgroup = (vrrp_sgroup_t *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] VRRP Group %s - %s", global_data->router_id, vgroup->gname, subject); } else #endif if (global_data->router_id) snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] %s" , global_data->router_id , subject); else snprintf(smtp->subject, MAX_HEADERS_LENGTH, "%s", subject); strncpy(smtp->body, body, MAX_BODY_LENGTH - 1); smtp->body[MAX_BODY_LENGTH - 1]= '\0'; build_to_header_rcpt_addrs(smtp); #ifdef _SMTP_ALERT_DEBUG_ if (do_smtp_alert_debug) smtp_log_to_file(smtp); else #endif smtp_connect(smtp); } #ifdef THREAD_DUMP void register_smtp_addresses(void) { register_thread_address("body_cmd", body_cmd); register_thread_address("connection_error", connection_error); register_thread_address("connection_in_progress", connection_in_progress); register_thread_address("connection_success", connection_success); register_thread_address("connection_timeout", connection_timeout); register_thread_address("data_cmd", data_cmd); register_thread_address("helo_cmd", helo_cmd); register_thread_address("mail_cmd", mail_cmd); register_thread_address("quit_cmd", quit_cmd); register_thread_address("rcpt_cmd", rcpt_cmd); register_thread_address("smtp_read_thread", smtp_read_thread); register_thread_address("smtp_send_thread", smtp_send_thread); } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_2
crossvul-cpp_data_bad_1593_0
/* abrt-hook-ccpp.cpp - the hook for C/C++ crashing program Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com) Copyright (C) 2009 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/utsname.h> #include "libabrt.h" #define DUMP_SUID_UNSAFE 1 #define DUMP_SUID_SAFE 2 /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) static char* malloc_readlink(const char *linkname) { char buf[PATH_MAX + 1]; int len; len = readlink(linkname, buf, sizeof(buf)-1); if (len >= 0) { buf[len] = '\0'; return xstrdup(buf); } return NULL; } /* Custom version of copyfd_xyz, * one which is able to write into two descriptors at once. */ #define CONFIG_FEATURE_COPYBUF_KB 4 static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; //TODO: truncate to 0 or even delete the second file //(currently we delete the file later) } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } /* Global data */ static char *user_pwd; static char *proc_pid_status; static struct dump_dir *dd; static int user_core_fd = -1; /* * %s - signal number * %c - ulimit -c value * %p - pid * %u - uid * %g - gid * %t - UNIX time of dump * %e - executable filename * %h - hostname * %% - output one "%" */ /* Hook must be installed with exactly the same sequence of %c specifiers. * Last one, %h, may be omitted (we can find it out). */ static const char percent_specifiers[] = "%scpugteh"; static char *core_basename = (char*) "core"; /* * Used for error messages only. * It is either the same as core_basename if it is absolute, * or $PWD/core_basename. */ static char *full_core_basename; static char* get_executable(pid_t pid, int *fd_p) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); if (fd_p) *fd_p = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ char *executable = malloc_readlink(buf); if (!executable) return NULL; /* find and cut off " (deleted)" from the path */ char *deleted = executable + strlen(executable) - strlen(" (deleted)"); if (deleted > executable && strcmp(deleted, " (deleted)") == 0) { *deleted = '\0'; log("File '%s' seems to be deleted", executable); } /* find and cut off prelink suffixes from the path */ char *prelink = executable + strlen(executable) - strlen(".#prelink#.XXXXXX"); if (prelink > executable && strncmp(prelink, ".#prelink#.", strlen(".#prelink#.")) == 0) { log("File '%s' seems to be a prelink temporary file", executable); *prelink = '\0'; } return executable; } static char* get_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); return malloc_readlink(buf); } static char* get_rootdir(pid_t pid) { char buf[sizeof("/proc/%lu/root") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/root", (long)pid); return malloc_readlink(buf); } static int get_fsuid(void) { int real, euid, saved; /* if we fail to parse the uid, then make it root only readable to be safe */ int fs_uid = 0; char *line = proc_pid_status; /* never NULL */ for (;;) { if (strncmp(line, "Uid", 3) == 0) { int n = sscanf(line, "Uid:\t%d\t%d\t%d\t%d\n", &real, &euid, &saved, &fs_uid); if (n != 4) { perror_msg_and_die("Can't parse Uid: line"); } break; } line = strchr(line, '\n'); if (!line) break; line++; } return fs_uid; } static int dump_suid_policy() { /* - values are: 0 - don't dump suided programs - in this case the hook is not called by kernel 1 - create coredump readable by fs_uid 2 - create coredump readable by root only */ int c; int suid_dump_policy = 0; const char *filename = "/proc/sys/fs/suid_dumpable"; FILE *f = fopen(filename, "r"); if (!f) { log("Can't open %s", filename); return suid_dump_policy; } c = fgetc(f); fclose(f); if (c != EOF) suid_dump_policy = c - '0'; //log("suid dump policy is: %i", suid_dump_policy); return suid_dump_policy; } static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values) { errno = 0; if (user_pwd == NULL || chdir(user_pwd) != 0 ) { perror_msg("Can't cd to '%s'", user_pwd); return -1; } struct passwd* pw = getpwuid(uid); gid_t gid = pw ? pw->pw_gid : uid; //log("setting uid: %i gid: %i", uid, gid); xsetegid(gid); xseteuid(fsuid); if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } full_core_basename = core_basename; if (core_basename[0] != '/') core_basename = concat_path_file(user_pwd, core_basename); /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ struct stat sb; errno = 0; /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ int user_core_fd = open(core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW, 0600); /* kernel makes 0600 too */ xsetegid(0); xseteuid(0); if (user_core_fd < 0 || fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 /* kernel internal dumper checks this too: if (inode->i_uid != current->fsuid) <fail>, need to mimic? */ ) { if (user_core_fd < 0) perror_msg("Can't open '%s'", full_core_basename); else perror_msg("'%s' is not a regular file with link count 1", full_core_basename); return -1; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' to size 0", full_core_basename); unlink(core_basename); return -1; } return user_core_fd; } static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; } /* Like xopen, but on error, unlocks and deletes dd and user core */ static int create_or_die(const char *filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, DEFAULT_DUMP_DIR_MODE); if (fd >= 0) { IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid)); return fd; } int sv_errno = errno; if (dd) dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } errno = sv_errno; perror_msg_and_die("Can't open '%s'", filename); } int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } #endif /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s'", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size); } return 0; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1593_0
crossvul-cpp_data_bad_436_10
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Forked system call to launch an extra script. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <grp.h> #include <string.h> #include <sys/stat.h> #include <pwd.h> #include <sys/resource.h> #include <limits.h> #include <sys/prctl.h> #include "notify.h" #include "signals.h" #include "logger.h" #include "utils.h" #include "process.h" #include "parser.h" #include "keepalived_magic.h" #include "scheduler.h" /* Default user/group for script execution */ uid_t default_script_uid; gid_t default_script_gid; /* Have we got a default user OK? */ static bool default_script_uid_set = false; static bool default_user_fail = false; /* Set if failed to set default user, unless it defaults to root */ /* Script security enabled */ bool script_security = false; /* Buffer length needed for getpwnam_r/getgrname_r */ static size_t getpwnam_buf_len; static char *path; static bool path_is_malloced; /* The priority this process is running at */ static int cur_prio = INT_MAX; /* Buffer for expanding notify script commands */ static char cmd_str_buf[MAXBUF]; static bool set_privileges(uid_t uid, gid_t gid) { int retval; /* Ensure we receive SIGTERM if our parent process dies */ prctl(PR_SET_PDEATHSIG, SIGTERM); /* If we have increased our priority, set it to default for the script */ if (cur_prio != INT_MAX) cur_prio = getpriority(PRIO_PROCESS, 0); if (cur_prio < 0) setpriority(PRIO_PROCESS, 0, 0); /* Drop our privileges if configured */ if (gid) { retval = setgid(gid); if (retval < 0) { log_message(LOG_ALERT, "Couldn't setgid: %d (%m)", gid); return true; } /* Clear any extra supplementary groups */ retval = setgroups(1, &gid); if (retval < 0) { log_message(LOG_ALERT, "Couldn't setgroups: %d (%m)", gid); return true; } } if (uid) { retval = setuid(uid); if (retval < 0) { log_message(LOG_ALERT, "Couldn't setuid: %d (%m)", uid); return true; } } /* Prepare for invoking process/script */ signal_handler_script(); set_std_fd(false); return false; } char * cmd_str_r(const notify_script_t *script, char *buf, size_t len) { char *str_p; int i; size_t str_len; str_p = buf; for (i = 0; i < script->num_args; i++) { /* Check there is enough room for the next word */ str_len = strlen(script->args[i]); if (str_p + str_len + 2 + (i ? 1 : 0) >= buf + len) return NULL; if (i) *str_p++ = ' '; *str_p++ = '\''; strcpy(str_p, script->args[i]); str_p += str_len; *str_p++ = '\''; } *str_p = '\0'; return buf; } char * cmd_str(const notify_script_t *script) { size_t len; int i; for (i = 0, len = 0; i < script->num_args; i++) len += strlen(script->args[i]) + 3; /* Add two ', and trailing space (or null for last arg) */ if (len > sizeof cmd_str_buf) return NULL; return cmd_str_r(script, cmd_str_buf, sizeof cmd_str_buf); } /* Execute external script/program to process FIFO */ static pid_t notify_fifo_exec(thread_master_t *m, int (*func) (thread_t *), void *arg, notify_script_t *script) { pid_t pid; int retval; char *scr; pid = local_fork(); /* In case of fork is error. */ if (pid < 0) { log_message(LOG_INFO, "Failed fork process"); return -1; } /* In case of this is parent process */ if (pid) { thread_add_child(m, func, arg, pid, TIMER_NEVER); return 0; } #ifdef _MEM_CHECK_ skip_mem_dump(); #endif setpgid(0, 0); set_privileges(script->uid, script->gid); if (script->flags | SC_EXECABLE) { /* If keepalived dies, we want the script to die */ prctl(PR_SET_PDEATHSIG, SIGTERM); execve(script->args[0], script->args, environ); if (errno == EACCES) log_message(LOG_INFO, "FIFO notify script %s is not executable", script->args[0]); else log_message(LOG_INFO, "Unable to execute FIFO notify script %s - errno %d - %m", script->args[0], errno); } else { retval = system(scr = cmd_str(script)); if (retval == 127) { /* couldn't exec command */ log_message(LOG_ALERT, "Couldn't exec FIFO command: %s", scr); } else if (retval == -1) log_message(LOG_ALERT, "Error exec-ing FIFO command: %s", scr); exit(0); } /* unreached unless error */ exit(0); } static void fifo_open(notify_fifo_t* fifo, int (*script_exit)(thread_t *), const char *type) { int ret; int sav_errno; if (fifo->name) { sav_errno = 0; if (!(ret = mkfifo(fifo->name, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) fifo->created_fifo = true; else { sav_errno = errno; if (sav_errno != EEXIST) log_message(LOG_INFO, "Unable to create %snotify fifo %s", type, fifo->name); } if (!sav_errno || sav_errno == EEXIST) { /* Run the notify script if there is one */ if (fifo->script) notify_fifo_exec(master, script_exit, fifo, fifo->script); /* Now open the fifo */ if ((fifo->fd = open(fifo->name, O_RDWR | O_CLOEXEC | O_NONBLOCK)) == -1) { log_message(LOG_INFO, "Unable to open %snotify fifo %s - errno %d", type, fifo->name, errno); if (fifo->created_fifo) { unlink(fifo->name); fifo->created_fifo = false; } } } if (fifo->fd == -1) { FREE(fifo->name); fifo->name = NULL; } } } void notify_fifo_open(notify_fifo_t* global_fifo, notify_fifo_t* fifo, int (*script_exit)(thread_t *), const char *type) { /* Open the global FIFO if specified */ if (global_fifo->name) fifo_open(global_fifo, script_exit, ""); /* Now the specific FIFO */ if (fifo->name) fifo_open(fifo, script_exit, type); } static void fifo_close(notify_fifo_t* fifo) { if (fifo->fd != -1) { close(fifo->fd); fifo->fd = -1; } if (fifo->created_fifo) unlink(fifo->name); } void notify_fifo_close(notify_fifo_t* global_fifo, notify_fifo_t* fifo) { if (global_fifo->fd != -1) fifo_close(global_fifo); fifo_close(fifo); } /* perform a system call */ static void system_call(const notify_script_t *) __attribute__ ((noreturn)); static void system_call(const notify_script_t* script) { char *command_line = NULL; char *str; int retval; if (set_privileges(script->uid, script->gid)) exit(0); /* Move us into our own process group, so if the script needs to be killed * all its child processes will also be killed. */ setpgid(0, 0); if (script->flags & SC_EXECABLE) { /* If keepalived dies, we want the script to die */ prctl(PR_SET_PDEATHSIG, SIGTERM); execve(script->args[0], script->args, environ); /* error */ log_message(LOG_ALERT, "Error exec-ing command '%s', error %d: %m", script->args[0], errno); } else { retval = system(str = cmd_str(script)); if (retval == -1) log_message(LOG_ALERT, "Error exec-ing command: %s", str); else if (WIFEXITED(retval)) { if (WEXITSTATUS(retval) == 127) { /* couldn't find command */ log_message(LOG_ALERT, "Couldn't find command: %s", str); } else if (WEXITSTATUS(retval) == 126) { /* couldn't find command */ log_message(LOG_ALERT, "Couldn't execute command: %s", str); } } if (command_line) FREE(command_line); if (retval == -1 || (WIFEXITED(retval) && (WEXITSTATUS(retval) == 126 || WEXITSTATUS(retval) == 127))) exit(0); if (WIFEXITED(retval)) exit(WEXITSTATUS(retval)); if (WIFSIGNALED(retval)) kill(getpid(), WTERMSIG(retval)); exit(0); } exit(0); } /* Execute external script/program */ int notify_exec(const notify_script_t *script) { pid_t pid; if (log_file_name) flush_log_file(); pid = local_fork(); if (pid < 0) { /* fork error */ log_message(LOG_INFO, "Failed fork process"); return -1; } if (pid) { /* parent process */ return 0; } #ifdef _MEM_CHECK_ skip_mem_dump(); #endif system_call(script); /* We should never get here */ exit(0); } int system_call_script(thread_master_t *m, int (*func) (thread_t *), void * arg, unsigned long timer, notify_script_t* script) { pid_t pid; /* Daemonization to not degrade our scheduling timer */ if (log_file_name) flush_log_file(); pid = local_fork(); if (pid < 0) { /* fork error */ log_message(LOG_INFO, "Failed fork process"); return -1; } if (pid) { /* parent process */ thread_add_child(m, func, arg, pid, timer); return 0; } /* Child process */ #ifdef _MEM_CHECK_ skip_mem_dump(); #endif system_call(script); exit(0); /* Script errors aren't server errors */ } int child_killed_thread(thread_t *thread) { thread_master_t *m = thread->master; /* If the child didn't die, then force it */ if (thread->type == THREAD_CHILD_TIMEOUT) kill(-getpgid(thread->u.c.pid), SIGKILL); /* If all children have died, we can now complete the * termination process */ if (!&m->child.rb_root.rb_node && !m->shutdown_timer_running) thread_add_terminate_event(m); return 0; } void script_killall(thread_master_t *m, int signo, bool requeue) { thread_t *thread; pid_t p_pgid, c_pgid; #ifndef HAVE_SIGNALFD sigset_t old_set, child_wait; sigmask_func(0, NULL, &old_set); if (!sigismember(&old_set, SIGCHLD)) { sigemptyset(&child_wait); sigaddset(&child_wait, SIGCHLD); sigmask_func(SIG_BLOCK, &child_wait, NULL); } #endif p_pgid = getpgid(0); rb_for_each_entry_cached(thread, &m->child, n) { c_pgid = getpgid(thread->u.c.pid); if (c_pgid != p_pgid) kill(-c_pgid, signo); else { log_message(LOG_INFO, "Child process %d in our process group %d", c_pgid, p_pgid); kill(thread->u.c.pid, signo); } } /* We want to timeout the killed children in 1 second */ if (requeue && signo != SIGKILL) thread_children_reschedule(m, child_killed_thread, TIMER_HZ); #ifndef HAVE_SIGNALFD if (!sigismember(&old_set, SIGCHLD)) sigmask_func(SIG_UNBLOCK, &child_wait, NULL); #endif } static bool is_executable(struct stat *buf, uid_t uid, gid_t gid) { return (uid == 0 && buf->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) || (uid == buf->st_uid && buf->st_mode & S_IXUSR) || (uid != buf->st_uid && ((gid == buf->st_gid && buf->st_mode & S_IXGRP) || (gid != buf->st_gid && buf->st_mode & S_IXOTH))); } static void replace_cmd_name(notify_script_t *script, char *new_path) { size_t len; char **wp = &script->args[1]; size_t num_words = 1; char **params; char **word_ptrs; char *words; len = strlen(new_path) + 1; while (*wp) len += strlen(*wp++) + 1; num_words = ((char **)script->args[0] - &script->args[0]) - 1; params = word_ptrs = MALLOC((num_words + 1) * sizeof(char *) + len); words = (char *)&params[num_words + 1]; strcpy(words, new_path); *(word_ptrs++) = words; words += strlen(words) + 1; wp = &script->args[1]; while (*wp) { strcpy(words, *wp); *(word_ptrs++) = words; words += strlen(*wp) + 1; wp++; } *word_ptrs = NULL; FREE(script->args); script->args = params; } /* The following function is essentially __execve() from glibc */ static int find_path(notify_script_t *script) { size_t filename_len; size_t file_len; size_t path_len; char *file = script->args[0]; struct stat buf; int ret; int ret_val = ENOENT; int sgid_num; gid_t *sgid_list = NULL; const char *subp; bool got_eacces = false; const char *p; /* We check the simple case first. */ if (*file == '\0') return ENOENT; filename_len = strlen(file); if (filename_len >= PATH_MAX) { ret_val = ENAMETOOLONG; goto exit1; } /* Don't search when it contains a slash. */ if (strchr (file, '/') != NULL) { ret_val = 0; goto exit1; } /* Get the path if we haven't already done so, and if that doesn't * exist, use CS_PATH */ if (!path) { path = getenv ("PATH"); if (!path) { size_t cs_path_len; path = MALLOC(cs_path_len = confstr(_CS_PATH, NULL, 0)); confstr(_CS_PATH, path, cs_path_len); path_is_malloced = true; } } /* Although GLIBC does not enforce NAME_MAX, we set it as the maximum size to avoid unbounded stack allocation. Same applies for PATH_MAX. */ file_len = strnlen (file, NAME_MAX + 1); path_len = strnlen (path, PATH_MAX - 1) + 1; if (file_len > NAME_MAX) { ret_val = ENAMETOOLONG; goto exit1; } /* Set file access to the relevant uid/gid */ if (script->gid) { if (setegid(script->gid)) { log_message(LOG_INFO, "Unable to set egid to %d (%m)", script->gid); ret_val = EACCES; goto exit1; } /* Get our supplementary groups */ sgid_num = getgroups(0, NULL); sgid_list = MALLOC(((size_t)sgid_num + 1) * sizeof(gid_t)); sgid_num = getgroups(sgid_num, sgid_list); sgid_list[sgid_num++] = 0; /* Clear the supplementary group list */ if (setgroups(1, &script->gid)) { log_message(LOG_INFO, "Unable to set supplementary gids (%m)"); ret_val = EACCES; goto exit; } } if (script->uid && seteuid(script->uid)) { log_message(LOG_INFO, "Unable to set euid to %d (%m)", script->uid); ret_val = EACCES; goto exit; } for (p = path; ; p = subp) { char buffer[path_len + file_len + 1]; subp = strchrnul (p, ':'); /* PATH is larger than PATH_MAX and thus potentially larger than the stack allocation. */ if (subp >= p + path_len) { /* There are no more paths, bail out. */ if (*subp == '\0') { ret_val = ENOENT; goto exit; } /* Otherwise skip to next one. */ continue; } /* Use the current path entry, plus a '/' if nonempty, plus the file to execute. */ char *pend = mempcpy (buffer, p, (size_t)(subp - p)); *pend = '/'; memcpy (pend + (p < subp), file, file_len + 1); ret = stat (buffer, &buf); if (!ret) { if (!S_ISREG(buf.st_mode)) errno = EACCES; else if (!is_executable(&buf, script->uid, script->gid)) { errno = EACCES; } else { /* Success */ log_message(LOG_INFO, "WARNING - script `%s` resolved by path search to `%s`. Please specify full path.", script->args[0], buffer); /* Copy the found file name, and any parameters */ replace_cmd_name(script, buffer); ret_val = 0; got_eacces = false; goto exit; } } switch (errno) { case ENOEXEC: case EACCES: /* Record that we got a 'Permission denied' error. If we end up finding no executable we can use, we want to diagnose that we did find one but were denied access. */ if (!ret) got_eacces = true; case ENOENT: case ESTALE: case ENOTDIR: /* Those errors indicate the file is missing or not executable by us, in which case we want to just try the next path directory. */ case ENODEV: case ETIMEDOUT: /* Some strange filesystems like AFS return even stranger error numbers. They cannot reasonably mean anything else so ignore those, too. */ break; default: /* Some other error means we found an executable file, but something went wrong accessing it; return the error to our caller. */ ret_val = -1; goto exit; } if (*subp++ == '\0') break; } exit: /* Restore root euid/egid */ if (script->uid && seteuid(0)) log_message(LOG_INFO, "Unable to restore euid after script search (%m)"); if (script->gid) { if (setegid(0)) log_message(LOG_INFO, "Unable to restore egid after script search (%m)"); /* restore supplementary groups */ if (sgid_list) { if (setgroups((size_t)sgid_num, sgid_list)) log_message(LOG_INFO, "Unable to restore supplementary groups after script search (%m)"); FREE(sgid_list); } } exit1: /* We tried every element and none of them worked. */ if (got_eacces) { /* At least one failure was due to permissions, so report that error. */ return EACCES; } return ret_val; } static int check_security(char *filename, bool script_security) { char *next; char *slash; char sav; int ret; struct stat buf; int flags = 0; next = filename; while (next) { slash = strchrnul(next, '/'); if (*slash) next = slash + 1; else { slash = NULL; next = NULL; } if (slash) { /* We want to check '/' for first time around */ if (slash == filename) slash++; sav = *slash; *slash = 0; } ret = fstatat(0, filename, &buf, AT_SYMLINK_NOFOLLOW); /* Restore the full path name */ if (slash) *slash = sav; if (ret) { if (errno == EACCES || errno == ELOOP || errno == ENOENT || errno == ENOTDIR) log_message(LOG_INFO, "check_script_secure could not find script '%s' - disabling", filename); else log_message(LOG_INFO, "check_script_secure('%s') returned errno %d - %s - disabling", filename, errno, strerror(errno)); return flags | SC_NOTFOUND; } /* If it is not the last item, it must be a directory. If it is the last item * it must be a file or a symbolic link. */ if ((slash && !S_ISDIR(buf.st_mode)) || (!slash && !S_ISREG(buf.st_mode) && !S_ISLNK(buf.st_mode))) { log_message(LOG_INFO, "Wrong file type found in script path '%s'.", filename); return flags | SC_INHIBIT; } if (buf.st_uid || /* Owner is not root */ (((S_ISDIR(buf.st_mode) && /* A directory without the sticky bit set */ !(buf.st_mode & S_ISVTX)) || S_ISREG(buf.st_mode)) && /* This is a file */ ((buf.st_gid && buf.st_mode & S_IWGRP) || /* Group is not root and group write permission */ buf.st_mode & S_IWOTH))) { /* World has write permission */ log_message(LOG_INFO, "Unsafe permissions found for script '%s'%s.", filename, script_security ? " - disabling" : ""); flags |= SC_INSECURE; return flags | (script_security ? SC_INHIBIT : 0); } } return flags; } int check_script_secure(notify_script_t *script, #ifndef _HAVE_LIBMAGIC_ __attribute__((unused)) #endif magic_t magic) { int flags; int ret, ret_real, ret_new; struct stat file_buf, real_buf; bool need_script_protection = false; uid_t old_uid = 0; gid_t old_gid = 0; char *new_path; int sav_errno; char *real_file_path; char *orig_file_part, *new_file_part; if (!script) return 0; /* If the script starts "</" (possibly with white space between * the '<' and '/'), it is checking for a file being openable, * so it won't be executed */ if (script->args[0][0] == '<' && script->args[0][strspn(script->args[0] + 1, " \t") + 1] == '/') return SC_SYSTEM; if (!strchr(script->args[0], '/')) { /* It is a bare file name, so do a path search */ if ((ret = find_path(script))) { if (ret == EACCES) log_message(LOG_INFO, "Permissions failure for script %s in path - disabling", script->args[0]); else log_message(LOG_INFO, "Cannot find script %s in path - disabling", script->args[0]); return SC_NOTFOUND; } } /* Check script accessible by the user running it */ if (script->uid) old_uid = geteuid(); if (script->gid) old_gid = getegid(); if ((script->gid && setegid(script->gid)) || (script->uid && seteuid(script->uid))) { log_message(LOG_INFO, "Unable to set uid:gid %d:%d for script %s - disabling", script->uid, script->gid, script->args[0]); if ((script->uid && seteuid(old_uid)) || (script->gid && setegid(old_gid))) log_message(LOG_INFO, "Unable to restore uid:gid %d:%d after script %s", script->uid, script->gid, script->args[0]); return SC_INHIBIT; } /* Remove /./, /../, multiple /'s, and resolve symbolic links */ new_path = realpath(script->args[0], NULL); sav_errno = errno; if ((script->gid && setegid(old_gid)) || (script->uid && seteuid(old_uid))) log_message(LOG_INFO, "Unable to restore uid:gid %d:%d after checking script %s", script->uid, script->gid, script->args[0]); if (!new_path) { log_message(LOG_INFO, "Script %s cannot be accessed - %s", script->args[0], strerror(sav_errno)); return SC_NOTFOUND; } real_file_path = NULL; orig_file_part = strrchr(script->args[0], '/'); new_file_part = strrchr(new_path, '/'); if (strcmp(script->args[0], new_path)) { /* The path name is different */ /* If the file name parts don't match, we need to be careful to * ensure that we preserve the file name part since some executables * alter their behaviour based on what they are called */ if (strcmp(orig_file_part + 1, new_file_part + 1)) { real_file_path = new_path; new_path = MALLOC(new_file_part - real_file_path + 1 + strlen(orig_file_part + 1) + 1); strncpy(new_path, real_file_path, new_file_part + 1 - real_file_path); strcpy(new_path + (new_file_part + 1 - real_file_path), orig_file_part + 1); /* Now check this is the same file */ ret_real = stat(real_file_path, &real_buf); ret_new = stat(new_path, &file_buf); if (!ret_real && (ret_new || real_buf.st_dev != file_buf.st_dev || real_buf.st_ino != file_buf.st_ino)) { /* It doesn't resolve to the same file */ FREE(new_path); new_path = real_file_path; real_file_path = NULL; } } if (strcmp(script->args[0], new_path)) { /* We need to set up all the args again */ replace_cmd_name(script, new_path); } } if (!real_file_path) free(new_path); else FREE(new_path); /* Get the permissions for the file itself */ if (stat(real_file_path ? real_file_path : script->args[0], &file_buf)) { log_message(LOG_INFO, "Unable to access script `%s` - disabling", script->args[0]); return SC_NOTFOUND; } flags = SC_ISSCRIPT; /* We have the final file. Check if root is executing it, or it is set uid/gid root. */ if (is_executable(&file_buf, script->uid, script->gid)) { flags |= SC_EXECUTABLE; if (script->uid == 0 || script->gid == 0 || (file_buf.st_uid == 0 && (file_buf.st_mode & S_IXUSR) && (file_buf.st_mode & S_ISUID)) || (file_buf.st_gid == 0 && (file_buf.st_mode & S_IXGRP) && (file_buf.st_mode & S_ISGID))) need_script_protection = true; } else log_message(LOG_INFO, "WARNING - script '%s' is not executable for uid:gid %d:%d - disabling.", script->args[0], script->uid, script->gid); /* Default to execable */ script->flags |= SC_EXECABLE; #ifdef _HAVE_LIBMAGIC_ if (magic && flags & SC_EXECUTABLE) { const char *magic_desc = magic_file(magic, real_file_path ? real_file_path : script->args[0]); if (!strstr(magic_desc, " executable") && !strstr(magic_desc, " shared object")) { log_message(LOG_INFO, "Please add a #! shebang to script %s", script->args[0]); script->flags &= ~SC_EXECABLE; } } #endif if (!need_script_protection) { if (real_file_path) free(real_file_path); return flags; } /* Make sure that all parts of the path are not non-root writable */ flags |= check_security(script->args[0], script_security); if (real_file_path) { flags |= check_security(real_file_path, script_security); free(real_file_path); } return flags; } int check_notify_script_secure(notify_script_t **script_p, magic_t magic) { int flags; notify_script_t *script = *script_p; if (!script) return 0; flags = check_script_secure(script, magic); /* Mark not to run if needs inhibiting */ if ((flags & (SC_INHIBIT | SC_NOTFOUND)) || !(flags & SC_EXECUTABLE)) free_notify_script(script_p); return flags; } static void set_pwnam_buf_len(void) { long buf_len; /* Get buffer length needed for getpwnam_r/getgrnam_r */ if ((buf_len = sysconf(_SC_GETPW_R_SIZE_MAX)) == -1) getpwnam_buf_len = 1024; /* A safe default if no value is returned */ else getpwnam_buf_len = (size_t)buf_len; if ((buf_len = sysconf(_SC_GETGR_R_SIZE_MAX)) != -1 && (size_t)buf_len > getpwnam_buf_len) getpwnam_buf_len = (size_t)buf_len; } bool set_uid_gid(const char *username, const char *groupname, uid_t *uid_p, gid_t *gid_p, bool default_user) { uid_t uid; gid_t gid; struct passwd pwd; struct passwd *pwd_p; struct group grp; struct group *grp_p; int ret; bool using_default_default_user = false; if (!getpwnam_buf_len) set_pwnam_buf_len(); { char buf[getpwnam_buf_len]; if (default_user && !username) { using_default_default_user = true; username = "keepalived_script"; } if ((ret = getpwnam_r(username, &pwd, buf, sizeof(buf), &pwd_p))) { log_message(LOG_INFO, "Unable to resolve %sscript username '%s' - ignoring", default_user ? "default " : "", username); return true; } if (!pwd_p) { if (using_default_default_user) log_message(LOG_INFO, "WARNING - default user '%s' for script execution does not exist - please create.", username); else log_message(LOG_INFO, "%script user '%s' does not exist", default_user ? "Default s" : "S", username); return true; } uid = pwd.pw_uid; gid = pwd.pw_gid; if (groupname) { if ((ret = getgrnam_r(groupname, &grp, buf, sizeof(buf), &grp_p))) { log_message(LOG_INFO, "Unable to resolve %sscript group name '%s' - ignoring", default_user ? "default " : "", groupname); return true; } if (!grp_p) { log_message(LOG_INFO, "%script group '%s' does not exist", default_user ? "Default s" : "S", groupname); return true; } gid = grp.gr_gid; } *uid_p = uid; *gid_p = gid; } return false; } /* The default script user/group is keepalived_script if it exists, or root otherwise */ bool set_default_script_user(const char *username, const char *groupname) { if (!default_script_uid_set || username) { /* Even if we fail to set it, there is no point in trying again */ default_script_uid_set = true; if (set_uid_gid(username, groupname, &default_script_uid, &default_script_gid, true)) { if (username || script_security) default_user_fail = true; } else default_user_fail = false; } return default_user_fail; } bool set_script_uid_gid(vector_t *strvec, unsigned keyword_offset, uid_t *uid_p, gid_t *gid_p) { char *username; char *groupname; username = strvec_slot(strvec, keyword_offset); if (vector_size(strvec) > keyword_offset + 1) groupname = strvec_slot(strvec, keyword_offset + 1); else groupname = NULL; return set_uid_gid(username, groupname, uid_p, gid_p, false); } void set_script_params_array(vector_t *strvec, notify_script_t *script, unsigned extra_params) { unsigned num_words = 0; size_t len = 0; char **word_ptrs; char *words; vector_t *strvec_qe = NULL; unsigned i; /* Count the number of words, and total string length */ if (vector_size(strvec) >= 2) strvec_qe = alloc_strvec_quoted_escaped(strvec_slot(strvec, 1)); if (!strvec_qe) return; num_words = vector_size(strvec_qe); for (i = 0; i < num_words; i++) len += strlen(strvec_slot(strvec_qe, i)) + 1; /* Allocate memory for pointers to words and words themselves */ script->args = word_ptrs = MALLOC((num_words + extra_params + 1) * sizeof(char *) + len); words = (char *)word_ptrs + (num_words + extra_params + 1) * sizeof(char *); /* Set up pointers to words, and copy the words */ for (i = 0; i < num_words; i++) { strcpy(words, strvec_slot(strvec_qe, i)); *(word_ptrs++) = words; words += strlen(words) + 1; } *word_ptrs = NULL; script->num_args = num_words; free_strvec(strvec_qe); } notify_script_t* notify_script_init(int extra_params, const char *type) { notify_script_t *script = MALLOC(sizeof(notify_script_t)); vector_t *strvec_qe; /* We need to reparse the command line, allowing for quoted and escaped strings */ strvec_qe = alloc_strvec_quoted_escaped(NULL); if (!strvec_qe) { log_message(LOG_INFO, "Unable to parse notify script"); FREE(script); return NULL; } set_script_params_array(strvec_qe, script, extra_params); if (!script->args) { log_message(LOG_INFO, "Unable to parse script '%s' - ignoring", FMT_STR_VSLOT(strvec_qe, 1)); FREE(script); free_strvec(strvec_qe); return NULL; } script->flags = 0; if (vector_size(strvec_qe) > 2) { if (set_script_uid_gid(strvec_qe, 2, &script->uid, &script->gid)) { log_message(LOG_INFO, "Invalid user/group for %s script %s - ignoring", type, script->args[0]); FREE(script->args); FREE(script); free_strvec(strvec_qe); return NULL; } } else { if (set_default_script_user(NULL, NULL)) { log_message(LOG_INFO, "Failed to set default user for %s script %s - ignoring", type, script->args[0]); FREE(script->args); FREE(script); free_strvec(strvec_qe); return NULL; } script->uid = default_script_uid; script->gid = default_script_gid; } free_strvec(strvec_qe); return script; } void add_script_param(notify_script_t *script, char *param) { /* We store the args as an array of pointers to the args, terminated * by a NULL pointer, followed by the null terminated strings themselves */ if (script->args[script->num_args + 1]) { log_message(LOG_INFO, "notify_fifo_script %s no room to add parameter %s", script->args[0], param); return; } /* Add the extra parameter in the pre-reserved slot at the end */ script->args[script->num_args++] = param; } void notify_resource_release(void) { if (path_is_malloced) { FREE(path); path_is_malloced = false; path = NULL; } } bool notify_script_compare(notify_script_t *a, notify_script_t *b) { int i; if (a->num_args != b->num_args) return false; for (i = 0; i < a->num_args; i++) { if (strcmp(a->args[i], b->args[i])) return false; } return true; } #ifdef THREAD_DUMP void register_notify_addresses(void) { register_thread_address("child_killed_thread", child_killed_thread); } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_10
crossvul-cpp_data_bad_436_7
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Sheduling framework for vrrp code. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <errno.h> #include <netinet/ip.h> #include <signal.h> #if defined _WITH_VRRP_AUTH_ #include <netinet/in.h> #endif #include <stdint.h> #include <stdio.h> #include "vrrp_scheduler.h" #include "vrrp_track.h" #ifdef _HAVE_VRRP_VMAC_ #include "vrrp_vmac.h" #endif #include "vrrp_sync.h" #include "vrrp_notify.h" #include "vrrp_data.h" #include "vrrp_arp.h" #include "vrrp_ndisc.h" #include "vrrp_if.h" #include "global_data.h" #include "memory.h" #include "list.h" #include "logger.h" #include "main.h" #include "signals.h" #include "utils.h" #include "bitops.h" #include "vrrp_sock.h" #ifdef _WITH_SNMP_RFCV3_ #include "vrrp_snmp.h" #endif #ifdef _WITH_BFD_ #include "bfd_event.h" #include "bfd_daemon.h" #endif #ifdef THREAD_DUMP #include "scheduler.h" #endif /* global vars */ timeval_t garp_next_time; thread_t *garp_thread; bool vrrp_initialised; #ifdef _TSM_DEBUG_ bool do_tsm_debug; #endif /* local variables */ #ifdef _WITH_BFD_ static thread_t *bfd_thread; /* BFD control pipe read thread */ #endif /* VRRP FSM (Finite State Machine) design. * * The state transition diagram implemented is : * * +---------------+ * +----------------| |----------------+ * | | Fault | | * | +------------>| |<------------+ | * | | +---------------+ | | * | | | | | * | | V | | * | | +---------------+ | | * | | +--------->| |<---------+ | | * | | | | Initialize | | | | * | | | +-------| |-------+ | | | * | | | | +---------------+ | | | | * | | | | | | | | * V | | V V | | V * +---------------+ +---------------+ * | |---------------------->| | * | Master | | Backup | * | |<----------------------| | * +---------------+ +---------------+ */ static int vrrp_script_child_thread(thread_t *); static int vrrp_script_thread(thread_t *); #ifdef _WITH_BFD_ static int vrrp_bfd_thread(thread_t *); #endif static int vrrp_read_dispatcher_thread(thread_t *); /* VRRP TSM (Transition State Matrix) design. * * Introducing the Synchronization extension to VRRP * protocol, introduce the need for a transition machinery. * This mechanism can be designed using a diagonal matrix. * We call this matrix the VRRP TSM: * * \ E | B | M | F | * S \ | | | | * ------+-----+-----+-----+ Legend: * B | x 1 2 | B: VRRP BACKUP state * ------+ | M: VRRP MASTER state * M | 3 x 4 | F: VRRP FAULT state * ------+ | S: VRRP start state (before transition) * F | 5 6 x | E: VRRP end state (after transition) * ------+-----------------+ [1..6]: Handler functions. * * So we have have to implement n(n-1) handlers in order to deal with * all transitions possible. This matrix defines the maximum handlers * to implement for having the most time optimized transition machine. * For example: * . The handler (1) will sync all the BACKUP VRRP instances of a * group to MASTER state => we will call it vrrp_sync_master. * .... and so on for all other state .... * * This matrix is the strict implementation way. For readability and * performance we have implemented some handlers directly into the VRRP * FSM or they are handled when the trigger events to/from FAULT state occur. * For instance the handlers (2), (4), (5) & (6) are handled when it is * detected that a script or an interface has failed or recovered since * it will speed up convergence to init state. * Additionaly, we have implemented some other handlers into the matrix * in order to speed up group synchronization takeover. For instance * transition: * o B->B: To catch wantstate MASTER transition to force sync group * to this transition state too. * o F->F: To speed up FAULT state transition if group is not already * synced to FAULT state. */ static struct { void (*handler) (vrrp_t *); } VRRP_TSM[VRRP_MAX_TSM_STATE + 1][VRRP_MAX_TSM_STATE + 1] = { /* From: To: > BACKUP MASTER FAULT */ /* v */ { {NULL}, {NULL}, {NULL}, {NULL} }, /* BACKUP */ { {NULL}, {NULL}, {vrrp_sync_master}, {NULL} }, /* MASTER */ { {NULL}, {vrrp_sync_backup}, {vrrp_sync_master}, {NULL} }, /* FAULT */ { {NULL}, {NULL}, {vrrp_sync_master}, {NULL} } }; /* * Initialize state handling * --rfc2338.6.4.1 */ static void vrrp_init_state(list l) { vrrp_t *vrrp; vrrp_sgroup_t *vgroup; element e; bool is_up; int new_state; /* We can send SMTP messages from this point, so set the time */ set_time_now(); /* Do notifications for any sync groups in fault state */ for (e = LIST_HEAD(vrrp_data->vrrp_sync_group); e; ELEMENT_NEXT(e)) { /* Init group if needed */ vgroup = ELEMENT_DATA(e); if (vgroup->state == VRRP_STATE_FAULT) send_group_notifies(vgroup); } for (e = LIST_HEAD(l); e; ELEMENT_NEXT(e)) { vrrp = ELEMENT_DATA(e); /* wantstate is the state we would be in disregarding any sync group */ if (vrrp->state == VRRP_STATE_FAULT) vrrp->wantstate = VRRP_STATE_FAULT; new_state = vrrp->sync ? vrrp->sync->state : vrrp->wantstate; is_up = VRRP_ISUP(vrrp); if (is_up && new_state == VRRP_STATE_MAST && !vrrp->num_script_init && (!vrrp->sync || !vrrp->sync->num_member_init) && (vrrp->base_priority == VRRP_PRIO_OWNER || vrrp->reload_master) && vrrp->wantstate == VRRP_STATE_MAST) { #ifdef _WITH_LVS_ /* Check if sync daemon handling is needed */ if (global_data->lvs_syncd.ifname && global_data->lvs_syncd.vrrp == vrrp) ipvs_syncd_cmd(IPVS_STARTDAEMON, &global_data->lvs_syncd, vrrp->state == VRRP_STATE_MAST ? IPVS_MASTER : IPVS_BACKUP, false, false); #endif if (!vrrp->reload_master) { #ifdef _WITH_SNMP_RFCV3_ vrrp->stats->next_master_reason = VRRPV3_MASTER_REASON_PREEMPTED; #endif /* The simplest way to become master is to timeout from the backup state * very quickly (1usec) */ vrrp->state = VRRP_STATE_BACK; vrrp->ms_down_timer = 1; } // TODO Do we need -> vrrp_restore_interface(vrrp, false, false); // It removes everything, so probably if !reload } else { if (new_state == VRRP_STATE_BACK && vrrp->wantstate == VRRP_STATE_MAST) vrrp->ms_down_timer = vrrp->master_adver_int + VRRP_TIMER_SKEW_MIN(vrrp); else vrrp->ms_down_timer = 3 * vrrp->master_adver_int + VRRP_TIMER_SKEW(vrrp); #ifdef _WITH_SNMP_RFCV3_ vrrp->stats->next_master_reason = VRRPV3_MASTER_REASON_MASTER_NO_RESPONSE; #endif #ifdef _WITH_LVS_ /* Check if sync daemon handling is needed */ if (global_data->lvs_syncd.ifname && global_data->lvs_syncd.vrrp == vrrp) ipvs_syncd_cmd(IPVS_STARTDAEMON, &global_data->lvs_syncd, IPVS_BACKUP, false, false); #endif /* Set interface state */ vrrp_restore_interface(vrrp, false, false); if (is_up && new_state != VRRP_STATE_FAULT && !vrrp->num_script_init && (!vrrp->sync || !vrrp->sync->num_member_init)) { if (is_up) { vrrp->state = VRRP_STATE_BACK; log_message(LOG_INFO, "(%s) Entering BACKUP STATE (init)", vrrp->iname); } else { vrrp->state = VRRP_STATE_FAULT; log_message(LOG_INFO, "(%s) Entering FAULT STATE (init)", vrrp->iname); } send_instance_notifies(vrrp); } vrrp->last_transition = timer_now(); } #ifdef _WITH_SNMP_RFC_ vrrp->stats->uptime = timer_now(); #endif } } /* Declare vrrp_timer_cmp() rbtree compare function */ RB_TIMER_CMP(vrrp); /* Compute the new instance sands */ void vrrp_init_instance_sands(vrrp_t * vrrp) { set_time_now(); if (vrrp->state == VRRP_STATE_MAST) { if (vrrp->reload_master) vrrp->sands = time_now; else vrrp->sands = timer_add_long(time_now, vrrp->adver_int); } else if (vrrp->state == VRRP_STATE_BACK) { /* * When in the BACKUP state the expiry timer should be updated to * time_now plus the Master Down Timer, when a non-preemptable packet is * received. */ vrrp->sands = timer_add_long(time_now, vrrp->ms_down_timer); } else if (vrrp->state == VRRP_STATE_FAULT || vrrp->state == VRRP_STATE_INIT) vrrp->sands.tv_sec = TIMER_DISABLED; rb_move_cached(&vrrp->sockets->rb_sands, vrrp, rb_sands, vrrp_timer_cmp); } static void vrrp_init_sands(list l) { vrrp_t *vrrp; element e; LIST_FOREACH(l, vrrp, e) { vrrp->sands.tv_sec = TIMER_DISABLED; rb_insert_sort_cached(&vrrp->sockets->rb_sands, vrrp, rb_sands, vrrp_timer_cmp); vrrp_init_instance_sands(vrrp); vrrp->reload_master = false; } } static void vrrp_init_script(list l) { vrrp_script_t *vscript; element e; LIST_FOREACH(l, vscript, e) { if (vscript->init_state == SCRIPT_INIT_STATE_INIT) vscript->result = vscript->rise - 1; /* one success is enough */ else if (vscript->init_state == SCRIPT_INIT_STATE_FAILED) vscript->result = 0; /* assume failed by config */ thread_add_event(master, vrrp_script_thread, vscript, (int)vscript->interval); } } /* Timer functions */ static timeval_t * vrrp_compute_timer(const sock_t *sock) { vrrp_t *vrrp; static timeval_t timer = { .tv_sec = TIMER_DISABLED }; /* The sock won't exist if there isn't a vrrp instance on it, * so rb_first will always exist. */ vrrp = rb_entry(rb_first_cached(&sock->rb_sands), vrrp_t, rb_sands); if (vrrp) return &vrrp->sands; return &timer; } void vrrp_thread_requeue_read(vrrp_t *vrrp) { thread_requeue_read(master, vrrp->sockets->fd_in, vrrp_compute_timer(vrrp->sockets)); } /* Thread functions */ static void vrrp_register_workers(list l) { sock_t *sock; timeval_t timer; element e; /* Init compute timer */ memset(&timer, 0, sizeof(timer)); /* Init the VRRP instances state */ vrrp_init_state(vrrp_data->vrrp); /* Init VRRP instances sands */ vrrp_init_sands(vrrp_data->vrrp); /* Init VRRP tracking scripts */ if (!LIST_ISEMPTY(vrrp_data->vrrp_script)) vrrp_init_script(vrrp_data->vrrp_script); #ifdef _WITH_BFD_ if (!LIST_ISEMPTY(vrrp_data->vrrp)) { // TODO - should we only do this if we have track_bfd? Probably not /* Init BFD tracking thread */ bfd_thread = thread_add_read(master, vrrp_bfd_thread, NULL, bfd_vrrp_event_pipe[0], TIMER_NEVER); } #endif /* Register VRRP workers threads */ LIST_FOREACH(l, sock, e) { /* Register a timer thread if interface exists */ if (sock->fd_in != -1) sock->thread = thread_add_read_sands(master, vrrp_read_dispatcher_thread, sock, sock->fd_in, vrrp_compute_timer(sock)); } } void vrrp_thread_add_read(vrrp_t *vrrp) { vrrp->sockets->thread = thread_add_read_sands(master, vrrp_read_dispatcher_thread, vrrp->sockets, vrrp->sockets->fd_in, vrrp_compute_timer(vrrp->sockets)); } /* VRRP dispatcher functions */ static sock_t * already_exist_sock(list l, sa_family_t family, int proto, ifindex_t ifindex, bool unicast) { sock_t *sock; element e; LIST_FOREACH(l, sock, e) { if ((sock->family == family) && (sock->proto == proto) && (sock->ifindex == ifindex) && (sock->unicast == unicast)) return sock; } return NULL; } static sock_t * alloc_sock(sa_family_t family, list l, int proto, ifindex_t ifindex, bool unicast) { sock_t *new; new = (sock_t *)MALLOC(sizeof (sock_t)); new->family = family; new->proto = proto; new->ifindex = ifindex; new->unicast = unicast; new->rb_vrid = RB_ROOT; new->rb_sands = RB_ROOT_CACHED; list_add(l, new); return new; } static inline int vrrp_vrid_cmp(const vrrp_t *v1, const vrrp_t *v2) { return v1->vrid - v2->vrid; } static void vrrp_create_sockpool(list l) { vrrp_t *vrrp; element e; ifindex_t ifindex; int proto; bool unicast; sock_t *sock; LIST_FOREACH(vrrp_data->vrrp, vrrp, e) { ifindex = #ifdef _HAVE_VRRP_VMAC_ (__test_bit(VRRP_VMAC_XMITBASE_BIT, &vrrp->vmac_flags)) ? IF_BASE_INDEX(vrrp->ifp) : #endif IF_INDEX(vrrp->ifp); unicast = !LIST_ISEMPTY(vrrp->unicast_peer); #if defined _WITH_VRRP_AUTH_ if (vrrp->auth_type == VRRP_AUTH_AH) proto = IPPROTO_AH; else #endif proto = IPPROTO_VRRP; /* add the vrrp element if not exist */ if (!(sock = already_exist_sock(l, vrrp->family, proto, ifindex, unicast))) sock = alloc_sock(vrrp->family, l, proto, ifindex, unicast); /* Add the vrrp_t indexed by vrid to the socket */ rb_insert_sort(&sock->rb_vrid, vrrp, rb_vrid, vrrp_vrid_cmp); if (vrrp->kernel_rx_buf_size) sock->rx_buf_size += vrrp->kernel_rx_buf_size; else if (global_data->vrrp_rx_bufs_policy & RX_BUFS_SIZE) sock->rx_buf_size += global_data->vrrp_rx_bufs_size; else if (global_data->vrrp_rx_bufs_policy & RX_BUFS_POLICY_ADVERT) sock->rx_buf_size += global_data->vrrp_rx_bufs_multiples * vrrp_adv_len(vrrp); else if (global_data->vrrp_rx_bufs_policy & RX_BUFS_POLICY_MTU) sock->rx_buf_size += global_data->vrrp_rx_bufs_multiples * vrrp->ifp->mtu; } } static void vrrp_open_sockpool(list l) { sock_t *sock; element e; interface_t *ifp; LIST_FOREACH(l, sock, e) { if (!sock->ifindex) { sock->fd_in = sock->fd_out = -1; continue; } ifp = if_get_by_ifindex(sock->ifindex); sock->fd_in = open_vrrp_read_socket(sock->family, sock->proto, ifp, sock->unicast, sock->rx_buf_size); if (sock->fd_in == -1) sock->fd_out = -1; else sock->fd_out = open_vrrp_send_socket(sock->family, sock->proto, ifp, sock->unicast); } } static void vrrp_set_fds(list l) { sock_t *sock; vrrp_t *vrrp; element e; LIST_FOREACH(l, sock, e) { rb_for_each_entry(vrrp, &sock->rb_vrid, rb_vrid) vrrp->sockets = sock; } } /* * We create & allocate a socket pool here. The soft design * can be sum up by the following sketch : * * fd1 fd2 fd3 fd4 fdi fdi+1 * -----\__/--------\__/---........---\__/--- * | ETH0 | | ETH1 | | ETHn | * +------+ +------+ +------+ * * TODO TODO - this description is way out of date * Here we have n physical NIC. Each NIC own a maximum of 2 fds. * (one for VRRP the other for IPSEC_AH). All our VRRP instances * are multiplexed through this fds. So our design can handle 2*n * multiplexing points. */ int vrrp_dispatcher_init(__attribute__((unused)) thread_t * thread) { vrrp_create_sockpool(vrrp_data->vrrp_socket_pool); /* open the VRRP socket pool */ vrrp_open_sockpool(vrrp_data->vrrp_socket_pool); /* set VRRP instance fds to sockpool */ vrrp_set_fds(vrrp_data->vrrp_socket_pool); /* create the VRRP socket pool list */ /* register read dispatcher worker thread */ vrrp_register_workers(vrrp_data->vrrp_socket_pool); /* Dump socket pool */ if (__test_bit(LOG_DETAIL_BIT, &debug)) dump_list(NULL, vrrp_data->vrrp_socket_pool); vrrp_initialised = true; return 1; } void vrrp_dispatcher_release(vrrp_data_t *data) { free_list(&data->vrrp_socket_pool); #ifdef _WITH_BFD_ thread_cancel(bfd_thread); bfd_thread = NULL; #endif } static void vrrp_goto_master(vrrp_t * vrrp) { /* handle master state transition */ vrrp->wantstate = VRRP_STATE_MAST; vrrp_state_goto_master(vrrp); } /* Delayed gratuitous ARP thread */ int vrrp_gratuitous_arp_thread(thread_t * thread) { vrrp_t *vrrp = THREAD_ARG(thread); /* Simply broadcast the gratuitous ARP */ vrrp_send_link_update(vrrp, vrrp->garp_rep); return 0; } /* Delayed gratuitous ARP thread after receiving a lower priority advert */ int vrrp_lower_prio_gratuitous_arp_thread(thread_t * thread) { vrrp_t *vrrp = THREAD_ARG(thread); /* Simply broadcast the gratuitous ARP */ vrrp_send_link_update(vrrp, vrrp->garp_lower_prio_rep); return 0; } static void vrrp_master(vrrp_t * vrrp) { /* Send the VRRP advert */ vrrp_state_master_tx(vrrp); } void try_up_instance(vrrp_t *vrrp, bool leaving_init) { int wantstate; if (leaving_init) { if (vrrp->num_script_if_fault) return; } else if (--vrrp->num_script_if_fault || vrrp->num_script_init) return; if (vrrp->wantstate == VRRP_STATE_MAST && vrrp->base_priority == VRRP_PRIO_OWNER) { vrrp->wantstate = VRRP_STATE_MAST; #ifdef _WITH_SNMP_RFCV3_ vrrp->stats->next_master_reason = VRRPV3_MASTER_REASON_PREEMPTED; #endif } else { vrrp->wantstate = VRRP_STATE_BACK; #ifdef _WITH_SNMP_RFCV3_ vrrp->stats->next_master_reason = VRRPV3_MASTER_REASON_MASTER_NO_RESPONSE; #endif } vrrp->master_adver_int = vrrp->adver_int; if (vrrp->wantstate == VRRP_STATE_MAST && vrrp->base_priority == VRRP_PRIO_OWNER) vrrp->ms_down_timer = vrrp->master_adver_int + VRRP_TIMER_SKEW(vrrp); else vrrp->ms_down_timer = 3 * vrrp->master_adver_int + VRRP_TIMER_SKEW(vrrp); if (vrrp->sync) { if (leaving_init) { if (vrrp->sync->num_member_fault) return; } else if (--vrrp->sync->num_member_fault || vrrp->sync->num_member_init) return; } /* If the sync group can't go to master, we must go to backup state */ wantstate = vrrp->wantstate; if (vrrp->sync && vrrp->wantstate == VRRP_STATE_MAST && !vrrp_sync_can_goto_master(vrrp)) vrrp->wantstate = VRRP_STATE_BACK; /* We can come up */ vrrp_state_leave_fault(vrrp); vrrp_init_instance_sands(vrrp); vrrp_thread_requeue_read(vrrp); vrrp->wantstate = wantstate; if (vrrp->sync) { if (vrrp->state == VRRP_STATE_MAST) vrrp_sync_master(vrrp); else vrrp_sync_backup(vrrp); } } #ifdef _WITH_BFD_ static void vrrp_handle_bfd_event(bfd_event_t * evt) { vrrp_tracked_bfd_t *vbfd; tracking_vrrp_t *tbfd; vrrp_t * vrrp; element e, e1; struct timeval time_now; struct timeval timer_tmp; uint32_t delivery_time; if (__test_bit(LOG_DETAIL_BIT, &debug)) { time_now = timer_now(); timersub(&time_now, &evt->sent_time, &timer_tmp); delivery_time = timer_long(timer_tmp); log_message(LOG_INFO, "Received BFD event: instance %s is in" " state %s (delivered in %i usec)", evt->iname, BFD_STATE_STR(evt->state), delivery_time); } LIST_FOREACH(vrrp_data->vrrp_track_bfds, vbfd, e) { if (strcmp(vbfd->bname, evt->iname)) continue; if ((vbfd->bfd_up && evt->state == BFD_STATE_UP) || (!vbfd->bfd_up && evt->state == BFD_STATE_DOWN)) continue; vbfd->bfd_up = (evt->state == BFD_STATE_UP); LIST_FOREACH(vbfd->tracking_vrrp, tbfd, e1) { vrrp = tbfd->vrrp; log_message(LOG_INFO, "VRRP_Instance(%s) Tracked BFD" " instance %s is %s", vrrp->iname, evt->iname, vbfd->bfd_up ? "UP" : "DOWN"); if (tbfd->weight) { if (vbfd->bfd_up) vrrp->total_priority += abs(tbfd->weight); else vrrp->total_priority -= abs(tbfd->weight); vrrp_set_effective_priority(vrrp); continue; } if (vbfd->bfd_up) try_up_instance(vrrp, false); else down_instance(vrrp); } break; } } static int vrrp_bfd_thread(thread_t * thread) { bfd_event_t evt; bfd_thread = thread_add_read(master, vrrp_bfd_thread, NULL, thread->u.fd, TIMER_NEVER); if (thread->type != THREAD_READY_FD) return 0; while (read(thread->u.fd, &evt, sizeof(bfd_event_t)) != -1) vrrp_handle_bfd_event(&evt); return 0; } #endif /* Handle dispatcher read timeout */ static int vrrp_dispatcher_read_timeout(sock_t *sock) { vrrp_t *vrrp; int prev_state; set_time_now(); rb_for_each_entry_cached(vrrp, &sock->rb_sands, rb_sands) { if (vrrp->sands.tv_sec == TIMER_DISABLED || timercmp(&vrrp->sands, &time_now, >)) break; prev_state = vrrp->state; if (vrrp->state == VRRP_STATE_BACK) { if (__test_bit(LOG_DETAIL_BIT, &debug)) log_message(LOG_INFO, "(%s) Receive advertisement timeout", vrrp->iname); vrrp_goto_master(vrrp); } else if (vrrp->state == VRRP_STATE_MAST) vrrp_master(vrrp); /* handle instance synchronization */ #ifdef _TSM_DEBUG_ if (do_tsm_debug) log_message(LOG_INFO, "Send [%s] TSM transition : [%d,%d] Wantstate = [%d]", vrrp->iname, prev_state, vrrp->state, vrrp->wantstate); #endif VRRP_TSM_HANDLE(prev_state, vrrp); vrrp_init_instance_sands(vrrp); } return sock->fd_in; } /* Handle dispatcher read packet */ static int vrrp_dispatcher_read(sock_t * sock) { vrrp_t *vrrp; vrrphdr_t *hd; ssize_t len = 0; int prev_state = 0; unsigned proto = 0; struct sockaddr_storage src_addr; socklen_t src_addr_len = sizeof(src_addr); vrrp_t vrrp_lookup; /* Clean the read buffer */ memset(vrrp_buffer, 0, vrrp_buffer_len); /* read & affect received buffer */ len = recvfrom(sock->fd_in, vrrp_buffer, vrrp_buffer_len, 0, (struct sockaddr *) &src_addr, &src_addr_len); hd = vrrp_get_header(sock->family, vrrp_buffer, &proto); vrrp_lookup.vrid = hd->vrid; vrrp = rb_search(&sock->rb_vrid, &vrrp_lookup, rb_vrid, vrrp_vrid_cmp); /* If no instance found => ignore the advert */ if (!vrrp) return sock->fd_in; if (vrrp->state == VRRP_STATE_FAULT || vrrp->state == VRRP_STATE_INIT) { /* We just ignore a message received when we are in fault state or * not yet fully initialised */ return sock->fd_in; } vrrp->pkt_saddr = src_addr; prev_state = vrrp->state; if (vrrp->state == VRRP_STATE_BACK) vrrp_state_backup(vrrp, vrrp_buffer, len); else if (vrrp->state == VRRP_STATE_MAST) { if (vrrp_state_master_rx(vrrp, vrrp_buffer, len)) vrrp_state_leave_master(vrrp, false); } else log_message(LOG_INFO, "(%s) In dispatcher_read with state %d", vrrp->iname, vrrp->state); /* handle instance synchronization */ #ifdef _TSM_DEBUG_ if (do_tsm_debug) log_message(LOG_INFO, "Read [%s] TSM transition : [%d,%d] Wantstate = [%d]", vrrp->iname, prev_state, vrrp->state, vrrp->wantstate); #endif VRRP_TSM_HANDLE(prev_state, vrrp); /* If we have sent an advert, reset the timer */ if (vrrp->state != VRRP_STATE_MAST || !vrrp->lower_prio_no_advert) vrrp_init_instance_sands(vrrp); return sock->fd_in; } /* Our read packet dispatcher */ static int vrrp_read_dispatcher_thread(thread_t * thread) { sock_t *sock; int fd; /* Fetch thread arg */ sock = THREAD_ARG(thread); /* Dispatcher state handler */ if (thread->type == THREAD_READ_TIMEOUT || sock->fd_in == -1) fd = vrrp_dispatcher_read_timeout(sock); else fd = vrrp_dispatcher_read(sock); /* register next dispatcher thread */ if (fd != -1) sock->thread = thread_add_read_sands(thread->master, vrrp_read_dispatcher_thread, sock, fd, vrrp_compute_timer(sock)); return 0; } static int vrrp_script_thread(thread_t * thread) { vrrp_script_t *vscript = THREAD_ARG(thread); int ret; /* Register next timer tracker */ thread_add_timer(thread->master, vrrp_script_thread, vscript, vscript->interval); if (vscript->state != SCRIPT_STATE_IDLE) { /* We don't want the system to be overloaded with scripts that we are executing */ log_message(LOG_INFO, "Track script %s is %s, expect idle - skipping run", vscript->sname, vscript->state == SCRIPT_STATE_RUNNING ? "already running" : "being timed out"); return 0; } /* Execute the script in a child process. Parent returns, child doesn't */ ret = system_call_script(thread->master, vrrp_script_child_thread, vscript, (vscript->timeout) ? vscript->timeout : vscript->interval, &vscript->script); if (!ret) vscript->state = SCRIPT_STATE_RUNNING; return ret; } static int vrrp_script_child_thread(thread_t * thread) { int wait_status; pid_t pid; vrrp_script_t *vscript = THREAD_ARG(thread); int sig_num; unsigned timeout = 0; char *script_exit_type = NULL; bool script_success; char *reason = NULL; int reason_code; if (thread->type == THREAD_CHILD_TIMEOUT) { pid = THREAD_CHILD_PID(thread); if (vscript->state == SCRIPT_STATE_RUNNING) { vscript->state = SCRIPT_STATE_REQUESTING_TERMINATION; sig_num = SIGTERM; timeout = 2; } else if (vscript->state == SCRIPT_STATE_REQUESTING_TERMINATION) { vscript->state = SCRIPT_STATE_FORCING_TERMINATION; sig_num = SIGKILL; timeout = 2; } else if (vscript->state == SCRIPT_STATE_FORCING_TERMINATION) { log_message(LOG_INFO, "Child (PID %d) failed to terminate after kill", pid); sig_num = SIGKILL; timeout = 10; /* Give it longer to terminate */ } /* Kill it off. */ if (timeout) { /* If kill returns an error, we can't kill the process since either the process has terminated, * or we don't have permission. If we can't kill it, there is no point trying again. */ if (kill(-pid, sig_num)) { if (errno == ESRCH) { /* The process does not exist; presumably it * has just terminated. We should get * notification of it's termination, so allow * that to handle it. */ timeout = 1; } else { log_message(LOG_INFO, "kill -%d of process %s(%d) with new state %d failed with errno %d", sig_num, vscript->script.args[0], pid, vscript->state, errno); timeout = 1000; } } } else if (vscript->state != SCRIPT_STATE_IDLE) { log_message(LOG_INFO, "Child thread pid %d timeout with unknown script state %d", pid, vscript->state); timeout = 10; /* We need some timeout */ } if (timeout) thread_add_child(thread->master, vrrp_script_child_thread, vscript, pid, timeout * TIMER_HZ); return 0; } wait_status = THREAD_CHILD_STATUS(thread); if (WIFEXITED(wait_status)) { int status = WEXITSTATUS(wait_status); /* Report if status has changed */ if (status != vscript->last_status) log_message(LOG_INFO, "Script `%s` now returning %d", vscript->sname, status); if (status == 0) { /* success */ script_exit_type = "succeeded"; script_success = true; } else { /* failure */ script_exit_type = "failed"; script_success = false; reason = "exited with status"; reason_code = status; } vscript->last_status = status; } else if (WIFSIGNALED(wait_status)) { if (vscript->state == SCRIPT_STATE_REQUESTING_TERMINATION && WTERMSIG(wait_status) == SIGTERM) { /* The script terminated due to a SIGTERM, and we sent it a SIGTERM to * terminate the process. Now make sure any children it created have * died too. */ pid = THREAD_CHILD_PID(thread); kill(-pid, SIGKILL); } /* We treat forced termination as a failure */ if ((vscript->state == SCRIPT_STATE_REQUESTING_TERMINATION && WTERMSIG(wait_status) == SIGTERM) || (vscript->state == SCRIPT_STATE_FORCING_TERMINATION && (WTERMSIG(wait_status) == SIGKILL || WTERMSIG(wait_status) == SIGTERM))) script_exit_type = "timed_out"; else { script_exit_type = "failed"; reason = "due to signal"; reason_code = WTERMSIG(wait_status); } script_success = false; } if (script_exit_type) { if (script_success) { if (vscript->result < vscript->rise - 1) { vscript->result++; } else if (vscript->result != vscript->rise + vscript->fall - 1) { if (vscript->result < vscript->rise) { /* i.e. == vscript->rise - 1 */ log_message(LOG_INFO, "VRRP_Script(%s) %s", vscript->sname, script_exit_type); update_script_priorities(vscript, true); } vscript->result = vscript->rise + vscript->fall - 1; } } else { if (vscript->result > vscript->rise) { vscript->result--; } else { if (vscript->result == vscript->rise || vscript->init_state == SCRIPT_INIT_STATE_INIT) { if (reason) log_message(LOG_INFO, "VRRP_Script(%s) %s (%s %d)", vscript->sname, script_exit_type, reason, reason_code); else log_message(LOG_INFO, "VRRP_Script(%s) %s", vscript->sname, script_exit_type); update_script_priorities(vscript, false); } vscript->result = 0; } } } vscript->state = SCRIPT_STATE_IDLE; vscript->init_state = SCRIPT_INIT_STATE_DONE; return 0; } /* Delayed ARP/NA thread */ int vrrp_arp_thread(thread_t *thread) { element e, a; list l; ip_address_t *ipaddress; timeval_t next_time = { .tv_sec = INT_MAX /* We're never going to delay this long - I hope! */ }; interface_t *ifp; vrrp_t *vrrp; enum { VIP, EVIP } i; set_time_now(); for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { vrrp = ELEMENT_DATA(e); if (!vrrp->garp_pending && !vrrp->gna_pending) continue; vrrp->garp_pending = false; vrrp->gna_pending = false; if (vrrp->state != VRRP_STATE_MAST || !vrrp->vipset) continue; for (i = VIP; i <= EVIP; i++) { l = (i == VIP) ? vrrp->vip : vrrp->evip; if (!LIST_ISEMPTY(l)) { for (a = LIST_HEAD(l); a; ELEMENT_NEXT(a)) { ipaddress = ELEMENT_DATA(a); if (!ipaddress->garp_gna_pending) continue; if (!ipaddress->set) { ipaddress->garp_gna_pending = false; continue; } ifp = IF_BASE_IFP(ipaddress->ifp); /* This should never happen */ if (!ifp->garp_delay) { ipaddress->garp_gna_pending = false; continue; } if (!IP_IS6(ipaddress)) { if (timercmp(&time_now, &ifp->garp_delay->garp_next_time, >=)) { send_gratuitous_arp_immediate(ifp, ipaddress); ipaddress->garp_gna_pending = false; } else { vrrp->garp_pending = true; if (timercmp(&ifp->garp_delay->garp_next_time, &next_time, <)) next_time = ifp->garp_delay->garp_next_time; } } else { if (timercmp(&time_now, &ifp->garp_delay->gna_next_time, >=)) { ndisc_send_unsolicited_na_immediate(ifp, ipaddress); ipaddress->garp_gna_pending = false; } else { vrrp->gna_pending = true; if (timercmp(&ifp->garp_delay->gna_next_time, &next_time, <)) next_time = ifp->garp_delay->gna_next_time; } } } } } } if (next_time.tv_sec != INT_MAX) { /* Register next timer tracker */ garp_next_time = next_time; garp_thread = thread_add_timer(thread->master, vrrp_arp_thread, NULL, timer_long(timer_sub_now(next_time))); } else garp_thread = NULL; return 0; } #ifdef _WITH_DUMP_THREADS_ void dump_threads(void) { FILE *fp; char time_buf[26]; element e; vrrp_t *vrrp; char *file_name; file_name = make_file_name("/tmp/thread_dump.dat", "vrrp", #if HAVE_DECL_CLONE_NEWNET global_data->network_namespace, #else NULL, #endif global_data->instance_name); fp = fopen(file_name, "a"); FREE(file_name); set_time_now(); ctime_r(&time_now.tv_sec, time_buf); fprintf(fp, "\n%.19s.%6.6ld: Thread dump\n", time_buf, time_now.tv_usec); dump_thread_data(master, fp); fprintf(fp, "alloc = %lu\n", master->alloc); fprintf(fp, "\n"); LIST_FOREACH(vrrp_data->vrrp, vrrp, e) { ctime_r(&vrrp->sands.tv_sec, time_buf); fprintf(fp, "VRRP instance %s, sands %.19s.%6.6lu, status %s\n", vrrp->iname, time_buf, vrrp->sands.tv_usec, vrrp->state == VRRP_STATE_INIT ? "INIT" : vrrp->state == VRRP_STATE_BACK ? "BACKUP" : vrrp->state == VRRP_STATE_MAST ? "MASTER" : vrrp->state == VRRP_STATE_FAULT ? "FAULT" : vrrp->state == VRRP_STATE_STOP ? "STOP" : vrrp->state == VRRP_DISPATCHER ? "DISPATCHER" : "unknown"); } fclose(fp); } #endif #ifdef THREAD_DUMP void register_vrrp_scheduler_addresses(void) { register_thread_address("vrrp_arp_thread", vrrp_arp_thread); register_thread_address("vrrp_dispatcher_init", vrrp_dispatcher_init); register_thread_address("vrrp_gratuitous_arp_thread", vrrp_gratuitous_arp_thread); register_thread_address("vrrp_lower_prio_gratuitous_arp_thread", vrrp_lower_prio_gratuitous_arp_thread); register_thread_address("vrrp_script_child_thread", vrrp_script_child_thread); register_thread_address("vrrp_script_thread", vrrp_script_thread); register_thread_address("vrrp_read_dispatcher_thread", vrrp_read_dispatcher_thread); #ifdef _WITH_BFD_ register_thread_address("vrrp_bfd_thread", vrrp_bfd_thread); #endif } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_7
crossvul-cpp_data_bad_1468_0
/* liblxcapi * * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>. * Copyright © 2012 Canonical Ltd. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define _GNU_SOURCE #include "lxclock.h" #include <malloc.h> #include <stdio.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <pthread.h> #include <lxc/lxccontainer.h> #include "utils.h" #include "log.h" #ifdef MUTEX_DEBUGGING #include <execinfo.h> #endif #define MAX_STACKDEPTH 25 #define OFLAG (O_CREAT | O_RDWR) #define SEMMODE 0660 #define SEMVALUE 1 #define SEMVALUE_LOCKED 0 lxc_log_define(lxc_lock, lxc); #ifdef MUTEX_DEBUGGING static pthread_mutex_t thread_mutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP; static inline void dump_stacktrace(void) { void *array[MAX_STACKDEPTH]; size_t size; char **strings; size_t i; size = backtrace(array, MAX_STACKDEPTH); strings = backtrace_symbols(array, size); // Using fprintf here as our logging module is not thread safe fprintf(stderr, "\tObtained %zd stack frames.\n", size); for (i = 0; i < size; i++) fprintf(stderr, "\t\t%s\n", strings[i]); free (strings); } #else static pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALIZER; static inline void dump_stacktrace(void) {;} #endif static void lock_mutex(pthread_mutex_t *l) { int ret; if ((ret = pthread_mutex_lock(l)) != 0) { fprintf(stderr, "pthread_mutex_lock returned:%d %s\n", ret, strerror(ret)); dump_stacktrace(); exit(1); } } static void unlock_mutex(pthread_mutex_t *l) { int ret; if ((ret = pthread_mutex_unlock(l)) != 0) { fprintf(stderr, "pthread_mutex_unlock returned:%d %s\n", ret, strerror(ret)); dump_stacktrace(); exit(1); } } static char *lxclock_name(const char *p, const char *n) { int ret; int len; char *dest; char *rundir; /* lockfile will be: * "/run" + "/lock/lxc/$lxcpath/$lxcname + '\0' if root * or * $XDG_RUNTIME_DIR + "/lock/lxc/$lxcpath/$lxcname + '\0' if non-root */ /* length of "/lock/lxc/" + $lxcpath + "/" + "." + $lxcname + '\0' */ len = strlen("/lock/lxc/") + strlen(n) + strlen(p) + 3; rundir = get_rundir(); if (!rundir) return NULL; len += strlen(rundir); if ((dest = malloc(len)) == NULL) { free(rundir); return NULL; } ret = snprintf(dest, len, "%s/lock/lxc/%s", rundir, p); if (ret < 0 || ret >= len) { free(dest); free(rundir); return NULL; } ret = mkdir_p(dest, 0755); if (ret < 0) { /* fall back to "/tmp/" + $(id -u) + "/lxc" + $lxcpath + "/" + "." + $lxcname + '\0' * * maximum length of $(id -u) is 10 calculated by (log (2 ** (sizeof(uid_t) * 8) - 1) / log 10 + 1) * * lxcpath always starts with '/' */ int l2 = 22 + strlen(n) + strlen(p); if (l2 > len) { char *d; d = realloc(dest, l2); if (!d) { free(dest); free(rundir); return NULL; } len = l2; dest = d; } ret = snprintf(dest, len, "/tmp/%d/lxc%s", geteuid(), p); if (ret < 0 || ret >= len) { free(dest); free(rundir); return NULL; } ret = mkdir_p(dest, 0755); if (ret < 0) { free(dest); free(rundir); return NULL; } ret = snprintf(dest, len, "/tmp/%d/lxc%s/.%s", geteuid(), p, n); } else ret = snprintf(dest, len, "%s/lock/lxc/%s/.%s", rundir, p, n); free(rundir); if (ret < 0 || ret >= len) { free(dest); return NULL; } return dest; } static sem_t *lxc_new_unnamed_sem(void) { sem_t *s; int ret; s = malloc(sizeof(*s)); if (!s) return NULL; ret = sem_init(s, 0, 1); if (ret) { free(s); return NULL; } return s; } struct lxc_lock *lxc_newlock(const char *lxcpath, const char *name) { struct lxc_lock *l; l = malloc(sizeof(*l)); if (!l) goto out; if (!name) { l->type = LXC_LOCK_ANON_SEM; l->u.sem = lxc_new_unnamed_sem(); if (!l->u.sem) { free(l); l = NULL; } goto out; } l->type = LXC_LOCK_FLOCK; l->u.f.fname = lxclock_name(lxcpath, name); if (!l->u.f.fname) { free(l); l = NULL; goto out; } l->u.f.fd = -1; out: return l; } int lxclock(struct lxc_lock *l, int timeout) { int ret = -1, saved_errno = errno; struct flock lk; switch(l->type) { case LXC_LOCK_ANON_SEM: if (!timeout) { ret = sem_wait(l->u.sem); if (ret == -1) saved_errno = errno; } else { struct timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts) == -1) { ret = -2; goto out; } ts.tv_sec += timeout; ret = sem_timedwait(l->u.sem, &ts); if (ret == -1) saved_errno = errno; } break; case LXC_LOCK_FLOCK: ret = -2; if (timeout) { ERROR("Error: timeout not supported with flock"); ret = -2; goto out; } if (!l->u.f.fname) { ERROR("Error: filename not set for flock"); ret = -2; goto out; } if (l->u.f.fd == -1) { l->u.f.fd = open(l->u.f.fname, O_RDWR|O_CREAT, S_IWUSR | S_IRUSR); if (l->u.f.fd == -1) { ERROR("Error opening %s", l->u.f.fname); goto out; } } lk.l_type = F_WRLCK; lk.l_whence = SEEK_SET; lk.l_start = 0; lk.l_len = 0; ret = fcntl(l->u.f.fd, F_SETLKW, &lk); if (ret == -1) saved_errno = errno; break; } out: errno = saved_errno; return ret; } int lxcunlock(struct lxc_lock *l) { int ret = 0, saved_errno = errno; struct flock lk; switch(l->type) { case LXC_LOCK_ANON_SEM: if (!l->u.sem) ret = -2; else { ret = sem_post(l->u.sem); saved_errno = errno; } break; case LXC_LOCK_FLOCK: if (l->u.f.fd != -1) { lk.l_type = F_UNLCK; lk.l_whence = SEEK_SET; lk.l_start = 0; lk.l_len = 0; ret = fcntl(l->u.f.fd, F_SETLK, &lk); if (ret < 0) saved_errno = errno; close(l->u.f.fd); l->u.f.fd = -1; } else ret = -2; break; } errno = saved_errno; return ret; } /* * lxc_putlock() is only called when a container_new() fails, * or during container_put(), which is already guaranteed to * only be done by one task. * So the only exclusion we need to provide here is for regular * thread safety (i.e. file descriptor table changes). */ void lxc_putlock(struct lxc_lock *l) { if (!l) return; switch(l->type) { case LXC_LOCK_ANON_SEM: if (l->u.sem) { sem_destroy(l->u.sem); free(l->u.sem); l->u.sem = NULL; } break; case LXC_LOCK_FLOCK: if (l->u.f.fd != -1) { close(l->u.f.fd); l->u.f.fd = -1; } free(l->u.f.fname); l->u.f.fname = NULL; break; } free(l); } void process_lock(void) { lock_mutex(&thread_mutex); } void process_unlock(void) { unlock_mutex(&thread_mutex); } /* One thread can do fork() while another one is holding a mutex. * There is only one thread in child just after the fork(), so no one will ever release that mutex. * We setup a "child" fork handler to unlock the mutex just after the fork(). * For several mutex types, unlocking an unlocked mutex can lead to undefined behavior. * One way to deal with it is to setup "prepare" fork handler * to lock the mutex before fork() and both "parent" and "child" fork handlers * to unlock the mutex. * This forbids doing fork() while explicitly holding the lock. */ #ifdef HAVE_PTHREAD_ATFORK __attribute__((constructor)) static void process_lock_setup_atfork(void) { pthread_atfork(process_lock, process_unlock, process_unlock); } #endif int container_mem_lock(struct lxc_container *c) { return lxclock(c->privlock, 0); } void container_mem_unlock(struct lxc_container *c) { lxcunlock(c->privlock); } int container_disk_lock(struct lxc_container *c) { int ret; if ((ret = lxclock(c->privlock, 0))) return ret; if ((ret = lxclock(c->slock, 0))) { lxcunlock(c->privlock); return ret; } return 0; } void container_disk_unlock(struct lxc_container *c) { lxcunlock(c->slock); lxcunlock(c->privlock); }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1468_0
crossvul-cpp_data_good_3264_0
/* * ProFTPD - FTP server daemon * Copyright (c) 1997, 1998 Public Flood Software * Copyright (c) 1999, 2000 MacGyver aka Habeeb J. Dihu <macgyver@tos.net> * Copyright (c) 2001-2017 The ProFTPD Project team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. * * As a special exemption, Public Flood Software/MacGyver aka Habeeb J. Dihu * and other respective copyright holders give permission to link this program * with OpenSSL, and distribute the resulting executable, without including * the source code for OpenSSL in the source distribution. */ /* Authentication module for ProFTPD */ #include "conf.h" #include "privs.h" #ifdef HAVE_USERSEC_H # include <usersec.h> #endif #ifdef HAVE_SYS_AUDIT_H # include <sys/audit.h> #endif extern pid_t mpid; module auth_module; #ifdef PR_USE_LASTLOG static unsigned char lastlog = FALSE; #endif /* PR_USE_LASTLOG */ static unsigned char mkhome = FALSE; static unsigned char authenticated_without_pass = FALSE; static int TimeoutLogin = PR_TUNABLE_TIMEOUTLOGIN; static int logged_in = FALSE; static int auth_anon_allow_robots = FALSE; static int auth_anon_allow_robots_enabled = FALSE; static int auth_client_connected = FALSE; static unsigned int auth_tries = 0; static char *auth_pass_resp_code = R_230; static pr_fh_t *displaylogin_fh = NULL; static int TimeoutSession = 0; static int saw_first_user_cmd = FALSE; static const char *timing_channel = "timing"; static int auth_count_scoreboard(cmd_rec *, const char *); static int auth_scan_scoreboard(void); static int auth_sess_init(void); /* auth_cmd_chk_cb() is hooked into the main server's auth_hook function, * so that we can deny all commands until authentication is complete. * * Note: Once this function returns true (i.e. client has authenticated), * it will ALWAYS return true. At least until REIN is implemented. Thus * we have a flag for such a situation, to save on redundant lookups for * the "authenticated" record. */ static int auth_have_authenticated = FALSE; static int auth_cmd_chk_cb(cmd_rec *cmd) { if (auth_have_authenticated == FALSE) { unsigned char *authd; authd = get_param_ptr(cmd->server->conf, "authenticated", FALSE); if (authd == NULL || *authd == FALSE) { pr_response_send(R_530, _("Please login with USER and PASS")); return FALSE; } auth_have_authenticated = TRUE; } return TRUE; } static int auth_login_timeout_cb(CALLBACK_FRAME) { pr_response_send_async(R_421, _("Login timeout (%d %s): closing control connection"), TimeoutLogin, TimeoutLogin != 1 ? "seconds" : "second"); /* It's possible that any listeners of this event might terminate the * session process themselves (e.g. mod_ban). So write out that the * TimeoutLogin has been exceeded to the log here, in addition to the * scheduled session exit message. */ pr_log_pri(PR_LOG_INFO, "%s", "Login timeout exceeded, disconnected"); pr_event_generate("core.timeout-login", NULL); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT, "TimeoutLogin"); /* Do not restart the timer (should never be reached). */ return 0; } static int auth_session_timeout_cb(CALLBACK_FRAME) { pr_event_generate("core.timeout-session", NULL); pr_response_send_async(R_421, _("Session Timeout (%d seconds): closing control connection"), TimeoutSession); pr_log_pri(PR_LOG_INFO, "%s", "FTP session timed out, disconnected"); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT, "TimeoutSession"); /* no need to restart the timer -- session's over */ return 0; } /* Event listeners */ static void auth_exit_ev(const void *event_data, void *user_data) { pr_auth_cache_clear(); /* Close the scoreboard descriptor that we opened. */ (void) pr_close_scoreboard(FALSE); } static void auth_sess_reinit_ev(const void *event_data, void *user_data) { int res; /* A HOST command changed the main_server pointer, reinitialize ourselves. */ pr_event_unregister(&auth_module, "core.exit", auth_exit_ev); pr_event_unregister(&auth_module, "core.session-reinit", auth_sess_reinit_ev); pr_timer_remove(PR_TIMER_LOGIN, &auth_module); /* Reset the CreateHome setting. */ mkhome = FALSE; /* Reset any MaxPasswordSize setting. */ (void) pr_auth_set_max_password_len(session.pool, 0); #if defined(PR_USE_LASTLOG) lastlog = FALSE; #endif /* PR_USE_LASTLOG */ mkhome = FALSE; res = auth_sess_init(); if (res < 0) { pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_SESSION_INIT_FAILED, NULL); } } /* Initialization functions */ static int auth_init(void) { /* Add the commands handled by this module to the HELP list. */ pr_help_add(C_USER, _("<sp> username"), TRUE); pr_help_add(C_PASS, _("<sp> password"), TRUE); pr_help_add(C_ACCT, _("is not implemented"), FALSE); pr_help_add(C_REIN, _("is not implemented"), FALSE); /* By default, enable auth checking */ set_auth_check(auth_cmd_chk_cb); return 0; } static int auth_sess_init(void) { config_rec *c = NULL; unsigned char *tmp = NULL; pr_event_register(&auth_module, "core.session-reinit", auth_sess_reinit_ev, NULL); /* Check for any MaxPasswordSize. */ c = find_config(main_server->conf, CONF_PARAM, "MaxPasswordSize", FALSE); if (c != NULL) { size_t len; len = *((size_t *) c->argv[0]); (void) pr_auth_set_max_password_len(session.pool, len); } /* Check for a server-specific TimeoutLogin */ c = find_config(main_server->conf, CONF_PARAM, "TimeoutLogin", FALSE); if (c != NULL) { TimeoutLogin = *((int *) c->argv[0]); } /* Start the login timer */ if (TimeoutLogin) { pr_timer_remove(PR_TIMER_LOGIN, &auth_module); pr_timer_add(TimeoutLogin, PR_TIMER_LOGIN, &auth_module, auth_login_timeout_cb, "TimeoutLogin"); } if (auth_client_connected == FALSE) { int res = 0; PRIVS_ROOT res = pr_open_scoreboard(O_RDWR); PRIVS_RELINQUISH if (res < 0) { switch (res) { case PR_SCORE_ERR_BAD_MAGIC: pr_log_debug(DEBUG0, "error opening scoreboard: bad/corrupted file"); break; case PR_SCORE_ERR_OLDER_VERSION: pr_log_debug(DEBUG0, "error opening scoreboard: bad version (too old)"); break; case PR_SCORE_ERR_NEWER_VERSION: pr_log_debug(DEBUG0, "error opening scoreboard: bad version (too new)"); break; default: pr_log_debug(DEBUG0, "error opening scoreboard: %s", strerror(errno)); break; } } } pr_event_register(&auth_module, "core.exit", auth_exit_ev, NULL); if (auth_client_connected == FALSE) { /* Create an entry in the scoreboard for this session, if we don't already * have one. */ if (pr_scoreboard_entry_get(PR_SCORE_CLIENT_ADDR) == NULL) { if (pr_scoreboard_entry_add() < 0) { pr_log_pri(PR_LOG_NOTICE, "notice: unable to add scoreboard entry: %s", strerror(errno)); } pr_scoreboard_entry_update(session.pid, PR_SCORE_USER, "(none)", PR_SCORE_SERVER_PORT, main_server->ServerPort, PR_SCORE_SERVER_ADDR, session.c->local_addr, session.c->local_port, PR_SCORE_SERVER_LABEL, main_server->ServerName, PR_SCORE_CLIENT_ADDR, session.c->remote_addr, PR_SCORE_CLIENT_NAME, session.c->remote_name, PR_SCORE_CLASS, session.conn_class ? session.conn_class->cls_name : "", PR_SCORE_PROTOCOL, "ftp", PR_SCORE_BEGIN_SESSION, time(NULL), NULL); } } else { /* We're probably handling a HOST comand, and the server changed; just * update the SERVER_LABEL field. */ pr_scoreboard_entry_update(session.pid, PR_SCORE_SERVER_LABEL, main_server->ServerName, NULL); } /* Should we create the home for a user, if they don't have one? */ tmp = get_param_ptr(main_server->conf, "CreateHome", FALSE); if (tmp != NULL && *tmp == TRUE) { mkhome = TRUE; } else { mkhome = FALSE; } #ifdef PR_USE_LASTLOG /* Use the lastlog file, if supported and requested. */ tmp = get_param_ptr(main_server->conf, "UseLastlog", FALSE); if (tmp && *tmp == TRUE) { lastlog = TRUE; } else { lastlog = FALSE; } #endif /* PR_USE_LASTLOG */ /* Scan the scoreboard now, in order to tally up certain values for * substituting in any of the Display* file variables. This function * also performs the MaxConnectionsPerHost enforcement. */ auth_scan_scoreboard(); auth_client_connected = TRUE; return 0; } static int do_auth(pool *p, xaset_t *conf, const char *u, char *pw) { char *cpw = NULL; config_rec *c; if (conf != NULL) { c = find_config(conf, CONF_PARAM, "UserPassword", FALSE); while (c != NULL) { pr_signals_handle(); if (strcmp(c->argv[0], u) == 0) { cpw = (char *) c->argv[1]; break; } c = find_config_next(c, c->next, CONF_PARAM, "UserPassword", FALSE); } } if (cpw != NULL) { if (pr_auth_getpwnam(p, u) == NULL) { int xerrno = errno; if (xerrno == ENOENT) { pr_log_pri(PR_LOG_NOTICE, "no such user '%s'", u); } errno = xerrno; return PR_AUTH_NOPWD; } return pr_auth_check(p, cpw, u, pw); } return pr_auth_authenticate(p, u, pw); } /* Command handlers */ static void login_failed(pool *p, const char *user) { #ifdef HAVE_LOGINFAILED const char *host, *sess_ttyname; int res, xerrno; host = pr_netaddr_get_dnsstr(session.c->remote_addr); sess_ttyname = pr_session_get_ttyname(p); PRIVS_ROOT res = loginfailed((char *) user, (char *) host, (char *) sess_ttyname, AUDIT_FAIL); xerrno = errno; PRIVS_RELINQUISH if (res < 0) { pr_trace_msg("auth", 3, "AIX loginfailed() error for user '%s', " "host '%s', tty '%s', reason %d: %s", user, host, sess_ttyname, AUDIT_FAIL, strerror(errno)); } #endif /* HAVE_LOGINFAILED */ } MODRET auth_err_pass(cmd_rec *cmd) { const char *user; user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (user != NULL) { login_failed(cmd->tmp_pool, user); } /* Remove the stashed original USER name here in a LOG_CMD_ERR handler, so * that other modules, who may want to lookup the original USER parameter on * a failed login in an earlier command handler phase, have a chance to do * so. This removal of the USER parameter on failure was happening directly * in the CMD handler previously, thus preventing POST_CMD_ERR handlers from * using USER. */ pr_table_remove(session.notes, "mod_auth.orig-user", NULL); return PR_HANDLED(cmd); } MODRET auth_log_pass(cmd_rec *cmd) { /* Only log, to the syslog, that the login has succeeded here, where we * know that the login has definitely succeeded. */ pr_log_auth(PR_LOG_INFO, "%s %s: Login successful.", (session.anon_config != NULL) ? "ANON" : C_USER, session.user); if (cmd->arg != NULL) { size_t passwd_len; /* And scrub the memory holding the password sent by the client, for * safety/security. */ passwd_len = strlen(cmd->arg); pr_memscrub(cmd->arg, passwd_len); } return PR_DECLINED(cmd); } static void login_succeeded(pool *p, const char *user) { #ifdef HAVE_LOGINSUCCESS const char *host, *sess_ttyname; char *msg = NULL; int res, xerrno; host = pr_netaddr_get_dnsstr(session.c->remote_addr); sess_ttyname = pr_session_get_ttyname(p); PRIVS_ROOT res = loginsuccess((char *) user, (char *) host, (char *) sess_ttyname, &msg); xerrno = errno; PRIVS_RELINQUISH if (res == 0) { if (msg != NULL) { pr_trace_msg("auth", 14, "AIX loginsuccess() report: %s", msg); } } else { pr_trace_msg("auth", 3, "AIX loginsuccess() error for user '%s', " "host '%s', tty '%s': %s", user, host, sess_ttyname, strerror(errno)); } if (msg != NULL) { free(msg); } #endif /* HAVE_LOGINSUCCESS */ } MODRET auth_post_pass(cmd_rec *cmd) { config_rec *c = NULL; const char *grantmsg = NULL, *user; unsigned int ctxt_precedence = 0; unsigned char have_user_timeout, have_group_timeout, have_class_timeout, have_all_timeout, *root_revoke = NULL, *authenticated; struct stat st; /* Was there a precending USER command? Was the client successfully * authenticated? */ authenticated = get_param_ptr(cmd->server->conf, "authenticated", FALSE); /* Clear the list of auth-only modules. */ pr_auth_clear_auth_only_modules(); if (authenticated != NULL && *authenticated == TRUE) { /* At this point, we can look up the Protocols config if the client * has been authenticated, which may have been tweaked via mod_ifsession's * user/group/class-specific sections. */ c = find_config(main_server->conf, CONF_PARAM, "Protocols", FALSE); if (c != NULL) { register unsigned int i; array_header *protocols; char **elts; const char *protocol; protocols = c->argv[0]; elts = protocols->elts; protocol = pr_session_get_protocol(PR_SESS_PROTO_FL_LOGOUT); /* We only want to check for 'ftp' in the configured Protocols list * if a) a RFC2228 mechanism (e.g. SSL or GSS) is not in use, and * b) an SSH protocol is not in use. */ if (session.rfc2228_mech == NULL && strncmp(protocol, "SSH2", 5) != 0) { int allow_ftp = FALSE; for (i = 0; i < protocols->nelts; i++) { char *proto; proto = elts[i]; if (proto != NULL) { if (strncasecmp(proto, "ftp", 4) == 0) { allow_ftp = TRUE; break; } } } if (!allow_ftp) { pr_log_debug(DEBUG0, "%s", "ftp protocol denied by Protocols config"); pr_response_send(R_530, "%s", _("Login incorrect.")); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by Protocols setting"); } } } } user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); /* Count up various quantities in the scoreboard, checking them against * the Max* limits to see if the session should be barred from going * any further. */ auth_count_scoreboard(cmd, session.user); /* Check for dynamic configuration. This check needs to be after the * setting of any possible anon_config, as that context may be allowed * or denied .ftpaccess-parsing separately from the containing server. */ if (pr_fsio_stat(session.cwd, &st) != -1) build_dyn_config(cmd->tmp_pool, session.cwd, &st, TRUE); have_user_timeout = have_group_timeout = have_class_timeout = have_all_timeout = FALSE; c = find_config(TOPLEVEL_CONF, CONF_PARAM, "TimeoutSession", FALSE); while (c != NULL) { pr_signals_handle(); if (c->argc == 3) { if (strncmp(c->argv[1], "user", 5) == 0) { if (pr_expr_eval_user_or((char **) &c->argv[2]) == TRUE) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_group_timeout = have_class_timeout = have_all_timeout = FALSE; have_user_timeout = TRUE; } } } else if (strncmp(c->argv[1], "group", 6) == 0) { if (pr_expr_eval_group_and((char **) &c->argv[2]) == TRUE) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_class_timeout = have_all_timeout = FALSE; have_group_timeout = TRUE; } } } else if (strncmp(c->argv[1], "class", 6) == 0) { if (session.conn_class != NULL && strcmp(session.conn_class->cls_name, c->argv[2]) == 0) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_group_timeout = have_all_timeout = FALSE; have_class_timeout = TRUE; } } } } else { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_group_timeout = have_class_timeout = FALSE; have_all_timeout = TRUE; } } c = find_config_next(c, c->next, CONF_PARAM, "TimeoutSession", FALSE); } /* If configured, start a session timer. The timer ID value for * session timers will not be #defined, as I think that is a bad approach. * A better mechanism would be to use the random timer ID generation, and * store the returned ID in order to later remove the timer. */ if (have_user_timeout || have_group_timeout || have_class_timeout || have_all_timeout) { pr_log_debug(DEBUG4, "setting TimeoutSession of %d seconds for current %s", TimeoutSession, have_user_timeout ? "user" : have_group_timeout ? "group" : have_class_timeout ? "class" : "all"); pr_timer_add(TimeoutSession, PR_TIMER_SESSION, &auth_module, auth_session_timeout_cb, "TimeoutSession"); } /* Handle a DisplayLogin file. */ if (displaylogin_fh) { if (!(session.sf_flags & SF_ANON)) { if (pr_display_fh(displaylogin_fh, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin_fh->fh_path, strerror(errno)); } pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } else { /* We're an <Anonymous> login, but there was a previous DisplayLogin * configured which was picked up earlier. Close that filehandle, * and look for a new one. */ char *displaylogin; pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin) { if (pr_display_file(displaylogin, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } } } } else { char *displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin) { if (pr_display_file(displaylogin, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } } } grantmsg = get_param_ptr(TOPLEVEL_CONF, "AccessGrantMsg", FALSE); if (grantmsg == NULL) { /* Append the final greeting lines. */ if (session.sf_flags & SF_ANON) { pr_response_add(auth_pass_resp_code, "%s", _("Anonymous access granted, restrictions apply")); } else { pr_response_add(auth_pass_resp_code, _("User %s logged in"), user); } } else { /* Handle any AccessGrantMsg directive. */ grantmsg = sreplace(cmd->tmp_pool, grantmsg, "%u", user, NULL); pr_response_add(auth_pass_resp_code, "%s", grantmsg); } login_succeeded(cmd->tmp_pool, user); /* A RootRevoke value of 0 indicates 'false', 1 indicates 'true', and * 2 indicates 'NonCompliantActiveTransfer'. We will drop root privs for any * RootRevoke value greater than 0. */ root_revoke = get_param_ptr(TOPLEVEL_CONF, "RootRevoke", FALSE); if (root_revoke != NULL && *root_revoke > 0) { pr_signals_block(); PRIVS_ROOT PRIVS_REVOKE pr_signals_unblock(); /* Disable future attempts at UID/GID manipulation. */ session.disable_id_switching = TRUE; if (*root_revoke == 1) { /* If the server's listening port is less than 1024, block PORT * commands (effectively allowing only passive connections, which is * not necessarily a Bad Thing). Only log this here -- the blocking * will need to occur in mod_core's handling of the PORT/EPRT commands. */ if (session.c->local_port < 1024) { pr_log_debug(DEBUG0, "RootRevoke in effect, active data transfers may not succeed"); } } pr_log_debug(DEBUG0, "RootRevoke in effect, dropped root privs"); } c = find_config(TOPLEVEL_CONF, CONF_PARAM, "AnonAllowRobots", FALSE); if (c != NULL) { auth_anon_allow_robots = *((int *) c->argv[0]); } return PR_DECLINED(cmd); } /* Handle group based authentication, only checked if pw based fails. */ static config_rec *auth_group(pool *p, const char *user, char **group, char **ournamep, char **anonnamep, char *pass) { config_rec *c; char *ourname = NULL, *anonname = NULL; char **grmem; struct group *grp; ourname = get_param_ptr(main_server->conf, "UserName", FALSE); if (ournamep != NULL && ourname != NULL) { *ournamep = ourname; } c = find_config(main_server->conf, CONF_PARAM, "GroupPassword", TRUE); if (c) do { grp = pr_auth_getgrnam(p, c->argv[0]); if (grp == NULL) { continue; } for (grmem = grp->gr_mem; *grmem; grmem++) { if (strcmp(*grmem, user) == 0) { if (pr_auth_check(p, c->argv[1], user, pass) == 0) { break; } } } if (*grmem) { if (group != NULL) { *group = c->argv[0]; } if (c->parent != NULL) { c = c->parent; } if (c->config_type == CONF_ANON) { anonname = get_param_ptr(c->subset, "UserName", FALSE); } if (anonnamep != NULL) { *anonnamep = anonname; } if (anonnamep != NULL && !anonname && ourname != NULL) { *anonnamep = ourname; } break; } } while((c = find_config_next(c, c->next, CONF_PARAM, "GroupPassword", TRUE)) != NULL); return c; } /* Determine any applicable chdirs. */ static const char *get_default_chdir(pool *p, xaset_t *conf) { config_rec *c; const char *dir = NULL; c = find_config(conf, CONF_PARAM, "DefaultChdir", FALSE); while (c != NULL) { int res; pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultChdir", FALSE); } /* If the directory is relative, concatenate w/ session.cwd. */ if (dir != NULL && *dir != '/' && *dir != '~') { dir = pdircat(p, session.cwd, dir, NULL); } /* Check for any expandable variables. */ if (dir != NULL) { dir = path_subst_uservar(p, &dir); } return dir; } static int is_symlink_path(pool *p, const char *path, size_t pathlen) { int res, xerrno = 0; struct stat st; char *ptr; if (pathlen == 0) { return 0; } pr_fs_clear_cache2(path); res = pr_fsio_lstat(path, &st); if (res < 0) { xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path, strerror(xerrno)); errno = xerrno; return -1; } if (S_ISLNK(st.st_mode)) { errno = EPERM; return -1; } /* To handle the case where a component further up the path might be a * symlink (which lstat(2) will NOT handle), we walk the path backwards, * calling ourselves recursively. */ ptr = strrchr(path, '/'); if (ptr != NULL) { char *new_path; size_t new_pathlen; pr_signals_handle(); new_pathlen = ptr - path; new_path = pstrndup(p, path, new_pathlen); pr_log_debug(DEBUG10, "AllowChrootSymlink: path '%s' not a symlink, checking '%s'", path, new_path); res = is_symlink_path(p, new_path, new_pathlen); if (res < 0) { return -1; } } return 0; } /* Determine if the user (non-anon) needs a default root dir other than /. */ static int get_default_root(pool *p, int allow_symlinks, const char **root) { config_rec *c = NULL; const char *dir = NULL; int res; c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE); while (c != NULL) { pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE); } if (dir != NULL) { const char *new_dir; /* Check for any expandable variables. */ new_dir = path_subst_uservar(p, &dir); if (new_dir != NULL) { dir = new_dir; } if (strncmp(dir, "/", 2) == 0) { dir = NULL; } else { char *realdir; int xerrno = 0; if (allow_symlinks == FALSE) { char *path, target_path[PR_TUNABLE_PATH_MAX + 1]; size_t pathlen; /* First, deal with any possible interpolation. dir_realpath() will * do this for us, but dir_realpath() ALSO automatically follows * symlinks, which is what we do NOT want to do here. */ path = pstrdup(p, dir); if (*path != '/') { if (*path == '~') { if (pr_fs_interpolate(dir, target_path, sizeof(target_path)-1) < 0) { return -1; } path = target_path; } } /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ pathlen = strlen(path); if (pathlen > 1 && path[pathlen-1] == '/') { path[pathlen-1] = '\0'; } res = is_symlink_path(p, path, pathlen); if (res < 0) { if (errno == EPERM) { pr_log_pri(PR_LOG_WARNING, "error: DefaultRoot %s is a symlink " "(denied by AllowChrootSymlinks config)", path); } errno = EPERM; return -1; } } /* We need to be the final user here so that if the user has their home * directory with a mode the user proftpd is running (i.e. the User * directive) as can not traverse down, we can still have the default * root. */ pr_fs_clear_cache2(dir); PRIVS_USER realdir = dir_realpath(p, dir); xerrno = errno; PRIVS_RELINQUISH if (realdir) { dir = realdir; } else { /* Try to provide a more informative message. */ char interp_dir[PR_TUNABLE_PATH_MAX + 1]; memset(interp_dir, '\0', sizeof(interp_dir)); (void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1); pr_log_pri(PR_LOG_NOTICE, "notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s", dir, interp_dir, strerror(xerrno)); errno = xerrno; } } } *root = dir; return 0; } static struct passwd *passwd_dup(pool *p, struct passwd *pw) { struct passwd *npw; npw = pcalloc(p, sizeof(struct passwd)); npw->pw_name = pstrdup(p, pw->pw_name); npw->pw_passwd = pstrdup(p, pw->pw_passwd); npw->pw_uid = pw->pw_uid; npw->pw_gid = pw->pw_gid; npw->pw_gecos = pstrdup(p, pw->pw_gecos); npw->pw_dir = pstrdup(p, pw->pw_dir); npw->pw_shell = pstrdup(p, pw->pw_shell); return npw; } static void ensure_open_passwd(pool *p) { /* Make sure pass/group is open. */ pr_auth_setpwent(p); pr_auth_setgrent(p); /* On some unices the following is necessary to ensure the files * are open (BSDI 3.1) */ pr_auth_getpwent(p); pr_auth_getgrent(p); /* Per Debian bug report: * https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=717235 * we might want to do another set{pw,gr}ent(), to play better with * some NSS modules. */ pr_auth_setpwent(p); pr_auth_setgrent(p); } /* Next function (the biggie) handles all authentication, setting * up chroot() jail, etc. */ static int setup_env(pool *p, cmd_rec *cmd, const char *user, char *pass) { struct passwd *pw; config_rec *c, *tmpc; const char *defchdir = NULL, *defroot = NULL, *origuser, *sess_ttyname; char *ourname = NULL, *anonname = NULL, *anongroup = NULL, *ugroup = NULL; char *xferlog = NULL; int aclp, i, res = 0, allow_chroot_symlinks = TRUE, showsymlinks; unsigned char *wtmp_log = NULL, *anon_require_passwd = NULL; /********************* Authenticate the user here *********************/ session.hide_password = TRUE; origuser = user; c = pr_auth_get_anon_config(p, &user, &ourname, &anonname); if (c != NULL) { session.anon_config = c; } if (user == NULL) { pr_log_auth(PR_LOG_NOTICE, "USER %s: user is not a UserAlias from %s [%s] " "to %s:%i", origuser, session.c->remote_name, pr_netaddr_get_ipstr(session.c->remote_addr), pr_netaddr_get_ipstr(session.c->local_addr), session.c->local_port); goto auth_failure; } pw = pr_auth_getpwnam(p, user); if (pw == NULL && c != NULL && ourname != NULL) { /* If the client is authenticating using an alias (e.g. "AuthAliasOnly on"), * then we need to try checking using the real username, too (Bug#4255). */ pr_trace_msg("auth", 16, "no user entry found for <Anonymous> alias '%s', using '%s'", user, ourname); pw = pr_auth_getpwnam(p, ourname); } if (pw == NULL) { int auth_code = PR_AUTH_NOPWD; pr_log_auth(PR_LOG_NOTICE, "USER %s: no such user found from %s [%s] to %s:%i", user, session.c->remote_name, pr_netaddr_get_ipstr(session.c->remote_addr), pr_netaddr_get_ipstr(session.c->local_addr), session.c->local_port); pr_event_generate("mod_auth.authentication-code", &auth_code); goto auth_failure; } /* Security: other functions perform pw lookups, thus we need to make * a local copy of the user just looked up. */ pw = passwd_dup(p, pw); if (pw->pw_uid == PR_ROOT_UID) { unsigned char *root_allow = NULL; pr_event_generate("mod_auth.root-login", NULL); /* If RootLogin is set to true, we allow this... even though we * still log a warning. :) */ if ((root_allow = get_param_ptr(c ? c->subset : main_server->conf, "RootLogin", FALSE)) == NULL || *root_allow != TRUE) { if (pass) { pr_memscrub(pass, strlen(pass)); } pr_log_auth(PR_LOG_NOTICE, "SECURITY VIOLATION: Root login attempted"); return 0; } } session.user = pstrdup(p, pw->pw_name); session.group = pstrdup(p, pr_auth_gid2name(p, pw->pw_gid)); /* Set the login_uid and login_uid */ session.login_uid = pw->pw_uid; session.login_gid = pw->pw_gid; /* Check for any expandable variables in session.cwd. */ pw->pw_dir = (char *) path_subst_uservar(p, (const char **) &pw->pw_dir); /* Before we check for supplemental groups, check to see if the locally * resolved name of the user, returned via auth_getpwnam(), is different * from the USER argument sent by the client. The name can change, since * auth modules can play all sorts of neat tricks on us. * * If the names differ, assume that any cached data in the session.gids * and session.groups lists are stale, and clear them out. */ if (strcmp(pw->pw_name, user) != 0) { pr_trace_msg("auth", 10, "local user name '%s' differs from client-sent " "user name '%s', clearing cached group data", pw->pw_name, user); session.gids = NULL; session.groups = NULL; } if (!session.gids && !session.groups) { /* Get the supplemental groups. Note that we only look up the * supplemental group credentials if we have not cached the group * credentials before, in session.gids and session.groups. * * Those credentials may have already been retrieved, as part of the * pr_auth_get_anon_config() call. */ res = pr_auth_getgroups(p, pw->pw_name, &session.gids, &session.groups); if (res < 1) { pr_log_debug(DEBUG5, "no supplemental groups found for user '%s'", pw->pw_name); } } tmpc = find_config(main_server->conf, CONF_PARAM, "AllowChrootSymlinks", FALSE); if (tmpc != NULL) { allow_chroot_symlinks = *((int *) tmpc->argv[0]); } /* If c != NULL from this point on, we have an anonymous login */ aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); if (c != NULL) { anongroup = get_param_ptr(c->subset, "GroupName", FALSE); if (anongroup == NULL) { anongroup = get_param_ptr(main_server->conf, "GroupName",FALSE); } #ifdef PR_USE_REGEX /* Check for configured AnonRejectPasswords regex here, and fail the login * if the given password matches the regex. */ tmpc = find_config(c->subset, CONF_PARAM, "AnonRejectPasswords", FALSE); if (tmpc != NULL) { int re_notmatch; pr_regex_t *pw_regex; pw_regex = (pr_regex_t *) tmpc->argv[0]; re_notmatch = *((int *) tmpc->argv[1]); if (pw_regex != NULL && pass != NULL) { int re_res; re_res = pr_regexp_exec(pw_regex, pass, 0, NULL, 0, 0, 0); if (re_res == 0 || (re_res != 0 && re_notmatch == TRUE)) { char errstr[200] = {'\0'}; pr_regexp_error(re_res, pw_regex, errstr, sizeof(errstr)); pr_log_auth(PR_LOG_NOTICE, "ANON %s: AnonRejectPasswords denies login", origuser); pr_event_generate("mod_auth.anon-reject-passwords", session.c); goto auth_failure; } } } #endif if (!login_check_limits(c->subset, FALSE, TRUE, &i) || (!aclp && !i) ){ pr_log_auth(PR_LOG_NOTICE, "ANON %s (Login failed): Limit access denies " "login", origuser); goto auth_failure; } } if (c == NULL && aclp == 0) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Limit access denies login", origuser); goto auth_failure; } if (c != NULL) { anon_require_passwd = get_param_ptr(c->subset, "AnonRequirePassword", FALSE); } if (c == NULL || (anon_require_passwd != NULL && *anon_require_passwd == TRUE)) { int auth_code; const char *user_name = user; if (c != NULL && origuser != NULL && strcasecmp(user, origuser) != 0) { unsigned char *auth_using_alias; auth_using_alias = get_param_ptr(c->subset, "AuthUsingAlias", FALSE); /* If 'AuthUsingAlias' set and we're logging in under an alias, * then auth using that alias. */ if (auth_using_alias && *auth_using_alias == TRUE) { user_name = origuser; pr_log_auth(PR_LOG_INFO, "ANON AUTH: User %s, authenticating using alias %s", user, user_name); } } /* It is possible for the user to have already been authenticated during * the handling of the USER command, as by an RFC2228 mechanism. If * that had happened, we won't need to call do_auth() here. */ if (!authenticated_without_pass) { auth_code = do_auth(p, c ? c->subset : main_server->conf, user_name, pass); } else { auth_code = PR_AUTH_OK_NO_PASS; } pr_event_generate("mod_auth.authentication-code", &auth_code); if (auth_code < 0) { /* Normal authentication has failed, see if group authentication * passes */ c = auth_group(p, user, &anongroup, &ourname, &anonname, pass); if (c != NULL) { if (c->config_type != CONF_ANON) { c = NULL; ugroup = anongroup; anongroup = NULL; } auth_code = PR_AUTH_OK; } } if (pass) pr_memscrub(pass, strlen(pass)); if (session.auth_mech) pr_log_debug(DEBUG2, "user '%s' authenticated by %s", user, session.auth_mech); switch (auth_code) { case PR_AUTH_OK_NO_PASS: auth_pass_resp_code = R_232; break; case PR_AUTH_OK: auth_pass_resp_code = R_230; break; case PR_AUTH_NOPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): No such user found", user); goto auth_failure; case PR_AUTH_BADPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Incorrect password", origuser); goto auth_failure; case PR_AUTH_AGEPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Password expired", user); goto auth_failure; case PR_AUTH_DISABLEDPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Account disabled", user); goto auth_failure; case PR_AUTH_CRED_INSUFFICIENT: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Insufficient credentials", user); goto auth_failure; case PR_AUTH_CRED_UNAVAIL: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Unavailable credentials", user); goto auth_failure; case PR_AUTH_CRED_ERROR: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Failure setting credentials", user); goto auth_failure; case PR_AUTH_INFO_UNAVAIL: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Unavailable authentication service", user); goto auth_failure; case PR_AUTH_MAX_ATTEMPTS_EXCEEDED: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Max authentication service attempts reached", user); goto auth_failure; case PR_AUTH_INIT_ERROR: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Failed initializing authentication service", user); goto auth_failure; case PR_AUTH_NEW_TOKEN_REQUIRED: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): New authentication token required", user); goto auth_failure; default: break; }; /* Catch the case where we forgot to handle a bad auth code above. */ if (auth_code < 0) goto auth_failure; if (pw->pw_uid == PR_ROOT_UID) { pr_log_auth(PR_LOG_WARNING, "ROOT FTP login successful"); } } else if (c && (!anon_require_passwd || *anon_require_passwd == FALSE)) { session.hide_password = FALSE; } pr_auth_setgrent(p); res = pr_auth_is_valid_shell(c ? c->subset : main_server->conf, pw->pw_shell); if (res == FALSE) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Invalid shell: '%s'", user, pw->pw_shell); goto auth_failure; } res = pr_auth_banned_by_ftpusers(c ? c->subset : main_server->conf, pw->pw_name); if (res == TRUE) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): User in " PR_FTPUSERS_PATH, user); goto auth_failure; } if (c) { struct group *grp = NULL; unsigned char *add_userdir = NULL; const char *u; char *chroot_dir; u = pr_table_get(session.notes, "mod_auth.orig-user", NULL); add_userdir = get_param_ptr(c->subset, "UserDirRoot", FALSE); /* If resolving an <Anonymous> user, make sure that user's groups * are set properly for the check of the home directory path (which * depend on those supplemental group memberships). Additionally, * temporarily switch to the new user's uid. */ pr_signals_block(); PRIVS_ROOT res = set_groups(p, pw->pw_gid, session.gids); if (res < 0) { if (errno != ENOSYS) { pr_log_pri(PR_LOG_WARNING, "error: unable to set groups: %s", strerror(errno)); } } #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(pw->pw_uid, pw->pw_gid) if ((add_userdir && *add_userdir == TRUE) && strcmp(u, user) != 0) { chroot_dir = pdircat(p, c->name, u, NULL); } else { chroot_dir = c->name; } if (allow_chroot_symlinks == FALSE) { char *chroot_path, target_path[PR_TUNABLE_PATH_MAX+1]; struct stat st; chroot_path = chroot_dir; if (chroot_path[0] != '/') { if (chroot_path[0] == '~') { if (pr_fs_interpolate(chroot_path, target_path, sizeof(target_path)-1) == 0) { chroot_path = target_path; } else { chroot_path = NULL; } } } if (chroot_path != NULL) { size_t chroot_pathlen; /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ chroot_pathlen = strlen(chroot_path); if (chroot_pathlen > 1 && chroot_path[chroot_pathlen-1] == '/') { chroot_path[chroot_pathlen-1] = '\0'; } pr_fs_clear_cache2(chroot_path); res = pr_fsio_lstat(chroot_path, &st); if (res < 0) { int xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", chroot_path, strerror(xerrno)); errno = xerrno; chroot_path = NULL; } else { if (S_ISLNK(st.st_mode)) { pr_log_pri(PR_LOG_WARNING, "error: <Anonymous %s> is a symlink (denied by " "AllowChrootSymlinks config)", chroot_path); errno = EPERM; chroot_path = NULL; } } } if (chroot_path != NULL) { session.chroot_path = dir_realpath(p, chroot_dir); } else { session.chroot_path = NULL; } if (session.chroot_path == NULL) { pr_log_debug(DEBUG8, "error resolving '%s': %s", chroot_dir, strerror(errno)); } } else { session.chroot_path = dir_realpath(p, chroot_dir); if (session.chroot_path == NULL) { pr_log_debug(DEBUG8, "error resolving '%s': %s", chroot_dir, strerror(errno)); } } if (session.chroot_path && pr_fsio_access(session.chroot_path, X_OK, session.uid, session.gid, session.gids) != 0) { session.chroot_path = NULL; } else { session.chroot_path = pstrdup(session.pool, session.chroot_path); } /* Return all privileges back to that of the daemon, for now. */ PRIVS_ROOT res = set_groups(p, daemon_gid, daemon_gids); if (res < 0) { if (errno != ENOSYS) { pr_log_pri(PR_LOG_ERR, "error: unable to set groups: %s", strerror(errno)); } } #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(daemon_uid, daemon_gid) pr_signals_unblock(); /* Sanity check, make sure we have daemon_uid and daemon_gid back */ #ifdef HAVE_GETEUID if (getegid() != daemon_gid || geteuid() != daemon_uid) { PRIVS_RELINQUISH pr_log_pri(PR_LOG_WARNING, "switching IDs from user %s back to daemon uid/gid failed: %s", session.user, strerror(errno)); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL); } #endif /* HAVE_GETEUID */ if (anon_require_passwd && *anon_require_passwd == TRUE) { session.anon_user = pstrdup(session.pool, origuser); } else { session.anon_user = pstrdup(session.pool, pass); } if (!session.chroot_path) { pr_log_pri(PR_LOG_NOTICE, "%s: Directory %s is not accessible", session.user, c->name); pr_response_add_err(R_530, _("Unable to set anonymous privileges.")); goto auth_failure; } sstrncpy(session.cwd, "/", sizeof(session.cwd)); xferlog = get_param_ptr(c->subset, "TransferLog", FALSE); if (anongroup) { grp = pr_auth_getgrnam(p, anongroup); if (grp) { pw->pw_gid = grp->gr_gid; session.group = pstrdup(p, grp->gr_name); } } } else { struct group *grp; char *homedir; if (ugroup) { grp = pr_auth_getgrnam(p, ugroup); if (grp) { pw->pw_gid = grp->gr_gid; session.group = pstrdup(p, grp->gr_name); } } /* Attempt to resolve any possible symlinks. */ PRIVS_USER homedir = dir_realpath(p, pw->pw_dir); PRIVS_RELINQUISH if (homedir) sstrncpy(session.cwd, homedir, sizeof(session.cwd)); else sstrncpy(session.cwd, pw->pw_dir, sizeof(session.cwd)); } /* Create the home directory, if need be. */ if (!c && mkhome) { if (create_home(p, session.cwd, origuser, pw->pw_uid, pw->pw_gid) < 0) { /* NOTE: should this cause the login to fail? */ goto auth_failure; } } /* Get default chdir (if any) */ defchdir = get_default_chdir(p, (c ? c->subset : main_server->conf)); if (defchdir != NULL) { sstrncpy(session.cwd, defchdir, sizeof(session.cwd)); } /* Check limits again to make sure deny/allow directives still permit * access. */ if (!login_check_limits((c ? c->subset : main_server->conf), FALSE, TRUE, &i)) { pr_log_auth(PR_LOG_NOTICE, "%s %s: Limit access denies login", (c != NULL) ? "ANON" : C_USER, origuser); goto auth_failure; } /* Perform a directory fixup. */ resolve_deferred_dirs(main_server); fixup_dirs(main_server, CF_DEFER); /* If running under an anonymous context, resolve all <Directory> * blocks inside it. */ if (c && c->subset) resolve_anonymous_dirs(c->subset); /* Write the login to wtmp. This must be done here because we won't * have access after we give up root. This can result in falsified * wtmp entries if an error kicks the user out before we get * through with the login process. Oh well. */ sess_ttyname = pr_session_get_ttyname(p); /* Perform wtmp logging only if not turned off in <Anonymous> * or the current server */ if (c) wtmp_log = get_param_ptr(c->subset, "WtmpLog", FALSE); if (wtmp_log == NULL) wtmp_log = get_param_ptr(main_server->conf, "WtmpLog", FALSE); /* As per Bug#3482, we need to disable WtmpLog for FreeBSD 9.0, as * an interim measure. * * The issue is that some platforms update multiple files for a single * pututxline(3) call; proftpd tries to update those files manually, * do to chroots (after which a pututxline(3) call will fail). A proper * solution requires a separate process, running with the correct * privileges, which would handle wtmp logging. The proftpd session * processes would send messages to this logging daemon (via Unix domain * socket, or FIFO, or TCP socket). * * Also note that this hack to disable WtmpLog may need to be extended * to other platforms in the future. */ #if defined(HAVE_UTMPX_H) && \ defined(__FreeBSD_version) && __FreeBSD_version >= 900007 if (wtmp_log == NULL || *wtmp_log == TRUE) { wtmp_log = pcalloc(p, sizeof(unsigned char)); *wtmp_log = FALSE; pr_log_debug(DEBUG5, "WtpmLog automatically disabled; see Bug#3482 for details"); } #endif PRIVS_ROOT if (wtmp_log == NULL || *wtmp_log == TRUE) { log_wtmp(sess_ttyname, session.user, session.c->remote_name, session.c->remote_addr); session.wtmp_log = TRUE; } #ifdef PR_USE_LASTLOG if (lastlog) { log_lastlog(pw->pw_uid, session.user, sess_ttyname, session.c->remote_addr); } #endif /* PR_USE_LASTLOG */ /* Open any TransferLogs */ if (!xferlog) { if (c) xferlog = get_param_ptr(c->subset, "TransferLog", FALSE); if (!xferlog) xferlog = get_param_ptr(main_server->conf, "TransferLog", FALSE); if (!xferlog) xferlog = PR_XFERLOG_PATH; } if (strcasecmp(xferlog, "NONE") == 0) { xferlog_open(NULL); } else { xferlog_open(xferlog); } res = set_groups(p, pw->pw_gid, session.gids); if (res < 0) { if (errno != ENOSYS) { pr_log_pri(PR_LOG_ERR, "error: unable to set groups: %s", strerror(errno)); } } PRIVS_RELINQUISH /* Now check to see if the user has an applicable DefaultRoot */ if (c == NULL) { if (get_default_root(session.pool, allow_chroot_symlinks, &defroot) < 0) { pr_log_pri(PR_LOG_NOTICE, "error: unable to determine DefaultRoot directory"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } ensure_open_passwd(p); if (defroot != NULL) { if (pr_auth_chroot(defroot) == -1) { pr_log_pri(PR_LOG_NOTICE, "error: unable to set DefaultRoot directory"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } /* Re-calc the new cwd based on this root dir. If not applicable * place the user in / (of defroot) */ if (strncmp(session.cwd, defroot, strlen(defroot)) == 0) { char *newcwd = &session.cwd[strlen(defroot)]; if (*newcwd == '/') newcwd++; session.cwd[0] = '/'; sstrncpy(&session.cwd[1], newcwd, sizeof(session.cwd)); } } } if (c) ensure_open_passwd(p); if (c && pr_auth_chroot(session.chroot_path) == -1) { pr_log_pri(PR_LOG_NOTICE, "error: unable to set anonymous privileges"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } /* new in 1.1.x, I gave in and we don't give up root permanently.. * sigh. */ PRIVS_ROOT #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(pw->pw_uid, pw->pw_gid) #ifdef HAVE_GETEUID if (getegid() != pw->pw_gid || geteuid() != pw->pw_uid) { PRIVS_RELINQUISH pr_log_pri(PR_LOG_ERR, "error: %s setregid() or setreuid(): %s", session.user, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } #endif /* If the home directory is NULL or "", reject the login. */ if (pw->pw_dir == NULL || strncmp(pw->pw_dir, "", 1) == 0) { pr_log_pri(PR_LOG_WARNING, "error: user %s home directory is NULL or \"\"", session.user); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } { unsigned char *show_symlinks = get_param_ptr( c ? c->subset : main_server->conf, "ShowSymlinks", FALSE); if (!show_symlinks || *show_symlinks == TRUE) showsymlinks = TRUE; else showsymlinks = FALSE; } /* chdir to the proper directory, do this even if anonymous * to make sure we aren't outside our chrooted space. */ /* Attempt to change to the correct directory -- use session.cwd first. * This will contain the DefaultChdir directory, if configured... */ if (pr_fsio_chdir_canon(session.cwd, !showsymlinks) == -1) { /* if we've got DefaultRoot or anonymous login, ignore this error * and chdir to / */ if (session.chroot_path != NULL || defroot) { pr_log_debug(DEBUG2, "unable to chdir to %s (%s), defaulting to chroot " "directory %s", session.cwd, strerror(errno), (session.chroot_path ? session.chroot_path : defroot)); if (pr_fsio_chdir_canon("/", !showsymlinks) == -1) { pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"/\") failed: %s", session.user, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } else if (defchdir) { /* If we've got defchdir, failure is ok as well, simply switch to * user's homedir. */ pr_log_debug(DEBUG2, "unable to chdir to %s (%s), defaulting to home " "directory %s", session.cwd, strerror(errno), pw->pw_dir); if (pr_fsio_chdir_canon(pw->pw_dir, !showsymlinks) == -1) { pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"%s\") failed: %s", session.user, session.cwd, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } else { /* Unable to switch to user's real home directory, which is not * allowed. */ pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"%s\") failed: %s", session.user, session.cwd, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } sstrncpy(session.cwd, pr_fs_getcwd(), sizeof(session.cwd)); sstrncpy(session.vwd, pr_fs_getvwd(), sizeof(session.vwd)); /* Make sure directory config pointers are set correctly */ dir_check_full(p, cmd, G_NONE, session.cwd, NULL); if (c) { if (!session.hide_password) { session.proc_prefix = pstrcat(session.pool, session.c->remote_name, ": anonymous/", pass, NULL); } else { session.proc_prefix = pstrcat(session.pool, session.c->remote_name, ": anonymous", NULL); } session.sf_flags = SF_ANON; } else { session.proc_prefix = pstrdup(session.pool, session.c->remote_name); session.sf_flags = 0; } /* While closing the pointer to the password database would avoid any * potential attempt to hijack this information, it is unfortunately needed * in a chroot()ed environment. Otherwise, mappings from UIDs to names, * among other things, would fail. */ /* pr_auth_endpwent(p); */ /* Authentication complete, user logged in, now kill the login * timer. */ /* Update the scoreboard entry */ pr_scoreboard_entry_update(session.pid, PR_SCORE_USER, session.user, PR_SCORE_CWD, session.cwd, NULL); pr_session_set_idle(); pr_timer_remove(PR_TIMER_LOGIN, &auth_module); /* These copies are made from the session.pool, instead of the more * volatile pool used originally, in order that the copied data maintain * its integrity for the lifetime of the session. */ session.user = pstrdup(session.pool, session.user); if (session.group) session.group = pstrdup(session.pool, session.group); if (session.gids) session.gids = copy_array(session.pool, session.gids); /* session.groups is an array of strings, so we must copy the string data * as well as the pointers. */ session.groups = copy_array_str(session.pool, session.groups); /* Resolve any deferred-resolution paths in the FS layer */ pr_resolve_fs_map(); return 1; auth_failure: if (pass) pr_memscrub(pass, strlen(pass)); session.user = session.group = NULL; session.gids = session.groups = NULL; session.wtmp_log = FALSE; return 0; } /* This function counts the number of connected users. It only fills in the * Class-based counters and an estimate for the number of clients. The primary * purpose is to make it so that the %N/%y escapes work in a DisplayConnect * greeting. A secondary purpose is to enforce any configured * MaxConnectionsPerHost limit. */ static int auth_scan_scoreboard(void) { char *key; void *v; config_rec *c = NULL; pr_scoreboard_entry_t *score = NULL; unsigned int cur = 0, ccur = 0, hcur = 0; char curr_server_addr[80] = {'\0'}; const char *client_addr = pr_netaddr_get_ipstr(session.c->remote_addr); snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; /* Determine how many users are currently connected */ if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { pr_signals_handle(); /* Make sure it matches our current server */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { cur++; if (strcmp(score->sce_client_addr, client_addr) == 0) hcur++; /* Only count up authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) continue; /* Note: the class member of the scoreboard entry will never be * NULL. At most, it may be the empty string. */ if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Lookup any configured MaxConnectionsPerHost. */ c = find_config(main_server->conf, CONF_PARAM, "MaxConnectionsPerHost", FALSE); if (c) { unsigned int *max = c->argv[0]; if (*max && hcur > *max) { char maxstr[20]; char *msg = "Sorry, the maximum number of connections (%m) for your host " "are already connected."; pr_event_generate("mod_auth.max-connections-per-host", session.c); if (c->argc == 2) msg = c->argv[1]; memset(maxstr, '\0', sizeof(maxstr)); snprintf(maxstr, sizeof(maxstr), "%u", *max); maxstr[sizeof(maxstr)-1] = '\0'; pr_response_send(R_530, "%s", sreplace(session.pool, msg, "%m", maxstr, NULL)); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxConnectionsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxConnectionsPerHost"); } } return 0; } static int have_client_limits(cmd_rec *cmd) { if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerClass", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE) != NULL) { return TRUE; } return FALSE; } static int auth_count_scoreboard(cmd_rec *cmd, const char *user) { char *key; void *v; pr_scoreboard_entry_t *score = NULL; long cur = 0, hcur = 0, ccur = 0, hostsperuser = 1, usersessions = 0; config_rec *c = NULL, *maxc = NULL; /* First, check to see which Max* directives are configured. If none * are configured, then there is no need for us to needlessly scan the * ScoreboardFile. */ if (have_client_limits(cmd) == FALSE) { return 0; } /* Determine how many users are currently connected. */ /* We use this call to get the possibly-changed user name. */ c = pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Gather our statistics. */ if (user != NULL) { char curr_server_addr[80] = {'\0'}; snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { unsigned char same_host = FALSE; pr_signals_handle(); /* Make sure it matches our current server. */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { if ((c != NULL && c->config_type == CONF_ANON && !strcmp(score->sce_user, user)) || c == NULL) { /* This small hack makes sure that cur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c != NULL && c->config_type == CONF_ANON && cur == 0) { cur = 1; } /* Only count authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) { continue; } cur++; /* Count up sessions on a per-host basis. */ if (!strcmp(score->sce_client_addr, pr_netaddr_get_ipstr(session.c->remote_addr))) { same_host = TRUE; /* This small hack makes sure that hcur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c != NULL && c->config_type == CONF_ANON && hcur == 0) { hcur = 1; } hcur++; } /* Take a per-user count of connections. */ if (strcmp(score->sce_user, user) == 0) { usersessions++; /* Count up unique hosts. */ if (!same_host) { hostsperuser++; } } } if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); PRIVS_RELINQUISH } key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Try to determine what MaxClients/MaxHosts limits apply to this session * (if any) and count through the runtime file to see if this limit would * be exceeded. */ maxc = find_config(cmd->server->conf, CONF_PARAM, "MaxClientsPerClass", FALSE); while (session.conn_class != NULL && maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your class " "are already connected."; unsigned int *max = maxc->argv[1]; if (strcmp(maxc->argv[0], session.conn_class->cls_name) != 0) { maxc = find_config_next(maxc, maxc->next, CONF_PARAM, "MaxClientsPerClass", FALSE); continue; } if (maxc->argc > 2) { maxstr = maxc->argv[2]; } if (*max && ccur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-class", session.conn_class->cls_name); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerClass %s %u)", session.conn_class->cls_name, *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerClass"); } break; } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your host " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && hcur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-host", session.c); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerHost"); } } /* Check for any configured MaxClientsPerUser. */ maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) for this user " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && usersessions > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerUser %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerUser"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of allowed clients (%m) are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && cur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients", NULL); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClients %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClients"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of hosts (%m) for this user are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && hostsperuser > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-hosts-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxHostsPerUser %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxHostsPerUser"); } } return 0; } MODRET auth_pre_user(cmd_rec *cmd) { if (saw_first_user_cmd == FALSE) { if (pr_trace_get_level(timing_channel)) { unsigned long elapsed_ms; uint64_t finish_ms; pr_gettimeofday_millis(&finish_ms); elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms); pr_trace_msg(timing_channel, 4, "Time before first USER: %lu ms", elapsed_ms); } saw_first_user_cmd = TRUE; } if (logged_in) { return PR_DECLINED(cmd); } /* Close the passwd and group databases, because libc won't let us see new * entries to these files without this (only in PersistentPasswd mode). */ pr_auth_endpwent(cmd->tmp_pool); pr_auth_endgrent(cmd->tmp_pool); /* Check for a user name that exceeds PR_TUNABLE_LOGIN_MAX. */ if (strlen(cmd->arg) > PR_TUNABLE_LOGIN_MAX) { pr_log_pri(PR_LOG_NOTICE, "USER %s (Login failed): " "maximum USER length exceeded", cmd->arg); pr_response_add_err(R_501, _("Login incorrect.")); pr_cmd_set_errno(cmd, EPERM); errno = EPERM; return PR_ERROR(cmd); } return PR_DECLINED(cmd); } MODRET auth_user(cmd_rec *cmd) { int nopass = FALSE; config_rec *c; const char *denymsg = NULL, *user, *origuser; int failnopwprompt = 0, aclp, i; unsigned char *anon_require_passwd = NULL, *login_passwd_prompt = NULL; if (cmd->argc < 2) { return PR_ERROR_MSG(cmd, R_500, _("USER: command requires a parameter")); } if (logged_in) { /* If the client has already authenticated, BUT the given USER command * here is for the exact same user name, then allow the command to * succeed (Bug#4217). */ origuser = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (origuser != NULL && strcmp(origuser, cmd->arg) == 0) { pr_response_add(R_230, _("User %s logged in"), origuser); return PR_HANDLED(cmd); } pr_response_add_err(R_501, "%s", _("Reauthentication not supported")); return PR_ERROR(cmd); } user = cmd->arg; (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (pr_table_add_dup(session.notes, "mod_auth.orig-user", user, 0) < 0) { pr_log_debug(DEBUG3, "error stashing 'mod_auth.orig-user' in " "session.notes: %s", strerror(errno)); } origuser = user; c = pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Check for AccessDenyMsg */ denymsg = get_param_ptr((c ? c->subset : cmd->server->conf), "AccessDenyMsg", FALSE); if (denymsg != NULL) { if (strstr(denymsg, "%u") != NULL) { denymsg = sreplace(cmd->tmp_pool, denymsg, "%u", user, NULL); } } login_passwd_prompt = get_param_ptr( (c && c->config_type == CONF_ANON) ? c->subset : main_server->conf, "LoginPasswordPrompt", FALSE); if (login_passwd_prompt && *login_passwd_prompt == FALSE) { failnopwprompt = TRUE; } else { failnopwprompt = FALSE; } if (failnopwprompt) { if (!user) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_pri(PR_LOG_NOTICE, "USER %s (Login failed): Not a UserAlias", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, _("Login incorrect.")); } pr_session_end(0); } aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); if (c && c->config_type != CONF_ANON) { c = (config_rec *) pcalloc(session.pool, sizeof(config_rec)); c->config_type = CONF_ANON; c->name = ""; /* don't really need this yet */ c->subset = main_server->conf; } if (c) { if (!login_check_limits(c->subset, FALSE, TRUE, &i) || (!aclp && !i) ) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_auth(PR_LOG_NOTICE, "ANON %s: Limit access denies login", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, _("Login incorrect.")); } pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by <Limit LOGIN>"); } } if (c == NULL && aclp == 0) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_auth(PR_LOG_NOTICE, "USER %s: Limit access denies login", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, "%s", _("Login incorrect.")); } pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by <Limit LOGIN>"); } } if (c) anon_require_passwd = get_param_ptr(c->subset, "AnonRequirePassword", FALSE); if (c && user && (!anon_require_passwd || *anon_require_passwd == FALSE)) nopass = TRUE; session.gids = NULL; session.groups = NULL; session.user = NULL; session.group = NULL; if (nopass) { pr_response_add(R_331, _("Anonymous login ok, send your complete email " "address as your password")); } else if (pr_auth_requires_pass(cmd->tmp_pool, user) == FALSE) { /* Check to see if a password from the client is required. In the * vast majority of cases, a password will be required. */ /* Act as if we received a PASS command from the client. */ cmd_rec *fakecmd = pr_cmd_alloc(cmd->pool, 2, NULL); /* We use pstrdup() here, rather than assigning C_PASS directly, since * code elsewhere will attempt to modify this buffer, and C_PASS is * a string literal. */ fakecmd->argv[0] = pstrdup(fakecmd->pool, C_PASS); fakecmd->argv[1] = NULL; fakecmd->arg = NULL; c = add_config_param_set(&cmd->server->conf, "authenticated", 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = TRUE; authenticated_without_pass = TRUE; pr_log_auth(PR_LOG_NOTICE, "USER %s: Authenticated without password", user); pr_cmd_dispatch(fakecmd); } else { pr_response_add(R_331, _("Password required for %s"), (char *) cmd->argv[1]); } return PR_HANDLED(cmd); } /* Close the passwd and group databases, similar to auth_pre_user(). */ MODRET auth_pre_pass(cmd_rec *cmd) { const char *user; char *displaylogin; pr_auth_endpwent(cmd->tmp_pool); pr_auth_endgrent(cmd->tmp_pool); /* Handle cases where PASS might be sent before USER. */ user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (user != NULL) { config_rec *c; c = find_config(main_server->conf, CONF_PARAM, "AllowEmptyPasswords", FALSE); if (c == NULL) { const char *anon_user; config_rec *anon_config; /* Since we have not authenticated yet, we cannot use the TOPLEVEL_CONF * macro to handle <Anonymous> sections. So we do it manually. */ anon_user = pstrdup(cmd->tmp_pool, user); anon_config = pr_auth_get_anon_config(cmd->tmp_pool, &anon_user, NULL, NULL); if (anon_config != NULL) { c = find_config(anon_config->subset, CONF_PARAM, "AllowEmptyPasswords", FALSE); } } if (c != NULL) { int allow_empty_passwords; allow_empty_passwords = *((int *) c->argv[0]); if (allow_empty_passwords == FALSE) { size_t passwd_len = 0; if (cmd->argc > 1) { if (cmd->arg != NULL) { passwd_len = strlen(cmd->arg); } } /* Make sure to NOT enforce 'AllowEmptyPasswords off' if e.g. * the AllowDotLogin TLSOption is in effect. */ if (cmd->argc == 1 || passwd_len == 0) { if (session.auth_mech == NULL || strcmp(session.auth_mech, "mod_tls.c") != 0) { pr_log_debug(DEBUG5, "Refusing empty password from user '%s' (AllowEmptyPasswords " "false)", user); pr_log_auth(PR_LOG_NOTICE, "Refusing empty password from user '%s'", user); pr_event_generate("mod_auth.empty-password", user); pr_response_add_err(R_501, _("Login incorrect.")); return PR_ERROR(cmd); } pr_log_debug(DEBUG9, "%s", "'AllowEmptyPasswords off' in effect, " "BUT client authenticated via the AllowDotLogin TLSOption"); } } } } /* Look for a DisplayLogin file which has an absolute path. If we find one, * open a filehandle, such that that file can be displayed even if the * session is chrooted. DisplayLogin files with relative paths will be * handled after chroot, preserving the old behavior. */ displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin && *displaylogin == '/') { struct stat st; displaylogin_fh = pr_fsio_open(displaylogin, O_RDONLY); if (displaylogin_fh == NULL) { pr_log_debug(DEBUG6, "unable to open DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } else { if (pr_fsio_fstat(displaylogin_fh, &st) < 0) { pr_log_debug(DEBUG6, "unable to stat DisplayLogin file '%s': %s", displaylogin, strerror(errno)); pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } else { if (S_ISDIR(st.st_mode)) { errno = EISDIR; pr_log_debug(DEBUG6, "unable to use DisplayLogin file '%s': %s", displaylogin, strerror(errno)); pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } } } } return PR_DECLINED(cmd); } MODRET auth_pass(cmd_rec *cmd) { const char *user = NULL; int res = 0; if (logged_in) { return PR_ERROR_MSG(cmd, R_503, _("You are already logged in")); } user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (user == NULL) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); return PR_ERROR_MSG(cmd, R_503, _("Login with USER first")); } /* Clear any potentially cached directory config */ session.anon_config = NULL; session.dir_config = NULL; res = setup_env(cmd->tmp_pool, cmd, user, cmd->arg); if (res == 1) { config_rec *c = NULL; c = add_config_param_set(&cmd->server->conf, "authenticated", 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = TRUE; set_auth_check(NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (session.sf_flags & SF_ANON) { if (pr_table_add_dup(session.notes, "mod_auth.anon-passwd", pr_fs_decode_path(cmd->server->pool, cmd->arg), 0) < 0) { pr_log_debug(DEBUG3, "error stashing anonymous password in session.notes: %s", strerror(errno)); } } logged_in = TRUE; if (pr_trace_get_level(timing_channel)) { unsigned long elapsed_ms; uint64_t finish_ms; pr_gettimeofday_millis(&finish_ms); elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms); pr_trace_msg(timing_channel, 4, "Time before successful login (via '%s'): %lu ms", session.auth_mech, elapsed_ms); } return PR_HANDLED(cmd); } (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (res == 0) { unsigned int max_logins, *max = NULL; const char *denymsg = NULL; /* check for AccessDenyMsg */ if ((denymsg = get_param_ptr((session.anon_config ? session.anon_config->subset : cmd->server->conf), "AccessDenyMsg", FALSE)) != NULL) { if (strstr(denymsg, "%u") != NULL) { denymsg = sreplace(cmd->tmp_pool, denymsg, "%u", user, NULL); } } max = get_param_ptr(main_server->conf, "MaxLoginAttempts", FALSE); if (max != NULL) { max_logins = *max; } else { max_logins = 3; } if (max_logins > 0 && ++auth_tries >= max_logins) { if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, "%s", _("Login incorrect.")); } pr_log_auth(PR_LOG_NOTICE, "Maximum login attempts (%u) exceeded, connection refused", max_logins); /* Generate an event about this limit being exceeded. */ pr_event_generate("mod_auth.max-login-attempts", session.c); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxLoginAttempts"); } return PR_ERROR_MSG(cmd, R_530, denymsg ? denymsg : _("Login incorrect.")); } return PR_HANDLED(cmd); } MODRET auth_acct(cmd_rec *cmd) { pr_response_add(R_502, _("ACCT command not implemented")); return PR_HANDLED(cmd); } MODRET auth_rein(cmd_rec *cmd) { pr_response_add(R_502, _("REIN command not implemented")); return PR_HANDLED(cmd); } /* FSIO callbacks for providing a fake robots.txt file, for the AnonAllowRobots * functionality. */ #define AUTH_ROBOTS_TXT "User-agent: *\nDisallow: /\n" #define AUTH_ROBOTS_TXT_FD 6742 static int robots_fsio_stat(pr_fs_t *fs, const char *path, struct stat *st) { st->st_dev = (dev_t) 0; st->st_ino = (ino_t) 0; st->st_mode = (S_IFREG|S_IRUSR|S_IRGRP|S_IROTH); st->st_nlink = 0; st->st_uid = (uid_t) 0; st->st_gid = (gid_t) 0; st->st_atime = 0; st->st_mtime = 0; st->st_ctime = 0; st->st_size = strlen(AUTH_ROBOTS_TXT); st->st_blksize = 1024; st->st_blocks = 1; return 0; } static int robots_fsio_fstat(pr_fh_t *fh, int fd, struct stat *st) { if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } return robots_fsio_stat(NULL, NULL, st); } static int robots_fsio_lstat(pr_fs_t *fs, const char *path, struct stat *st) { return robots_fsio_stat(fs, path, st); } static int robots_fsio_unlink(pr_fs_t *fs, const char *path) { return 0; } static int robots_fsio_open(pr_fh_t *fh, const char *path, int flags) { if (flags != O_RDONLY) { errno = EINVAL; return -1; } return AUTH_ROBOTS_TXT_FD; } static int robots_fsio_close(pr_fh_t *fh, int fd) { if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } return 0; } static int robots_fsio_read(pr_fh_t *fh, int fd, char *buf, size_t bufsz) { size_t robots_len; if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } robots_len = strlen(AUTH_ROBOTS_TXT); if (bufsz < robots_len) { errno = EINVAL; return -1; } memcpy(buf, AUTH_ROBOTS_TXT, robots_len); return (int) robots_len; } static int robots_fsio_write(pr_fh_t *fh, int fd, const char *buf, size_t bufsz) { if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } return (int) bufsz; } static int robots_fsio_access(pr_fs_t *fs, const char *path, int mode, uid_t uid, gid_t gid, array_header *suppl_gids) { if (mode != R_OK) { errno = EACCES; return -1; } return 0; } static int robots_fsio_faccess(pr_fh_t *fh, int mode, uid_t uid, gid_t gid, array_header *suppl_gids) { if (fh->fh_fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } if (mode != R_OK) { errno = EACCES; return -1; } return 0; } MODRET auth_pre_retr(cmd_rec *cmd) { const char *path; pr_fs_t *curr_fs = NULL; struct stat st; /* Only apply this for <Anonymous> logins. */ if (session.anon_config == NULL) { return PR_DECLINED(cmd); } if (auth_anon_allow_robots == TRUE) { return PR_DECLINED(cmd); } auth_anon_allow_robots_enabled = FALSE; path = dir_canonical_path(cmd->tmp_pool, cmd->arg); if (strcasecmp(path, "/robots.txt") != 0) { return PR_DECLINED(cmd); } /* If a previous REST command, with a non-zero value, has been sent, then * do nothing. Ugh. */ if (session.restart_pos > 0) { pr_log_debug(DEBUG10, "'AnonAllowRobots off' in effect, but cannot " "support resumed download (REST %" PR_LU " previously sent by client)", (pr_off_t) session.restart_pos); return PR_DECLINED(cmd); } pr_fs_clear_cache2(path); if (pr_fsio_lstat(path, &st) == 0) { /* There's an existing REAL "robots.txt" file on disk; use that, and * preserve the principle of least surprise. */ pr_log_debug(DEBUG10, "'AnonAllowRobots off' in effect, but have " "real 'robots.txt' file on disk; using that"); return PR_DECLINED(cmd); } curr_fs = pr_get_fs(path, NULL); if (curr_fs != NULL) { pr_fs_t *robots_fs; robots_fs = pr_register_fs(cmd->pool, "robots", path); if (robots_fs == NULL) { pr_log_debug(DEBUG8, "'AnonAllowRobots off' in effect, but failed to " "register FS: %s", strerror(errno)); return PR_DECLINED(cmd); } /* Use enough of our own custom FSIO callbacks to be able to provide * a fake "robots.txt" file. */ robots_fs->stat = robots_fsio_stat; robots_fs->fstat = robots_fsio_fstat; robots_fs->lstat = robots_fsio_lstat; robots_fs->unlink = robots_fsio_unlink; robots_fs->open = robots_fsio_open; robots_fs->close = robots_fsio_close; robots_fs->read = robots_fsio_read; robots_fs->write = robots_fsio_write; robots_fs->access = robots_fsio_access; robots_fs->faccess = robots_fsio_faccess; /* For all other FSIO callbacks, use the underlying FS. */ robots_fs->rename = curr_fs->rename; robots_fs->lseek = curr_fs->lseek; robots_fs->link = curr_fs->link; robots_fs->readlink = curr_fs->readlink; robots_fs->symlink = curr_fs->symlink; robots_fs->ftruncate = curr_fs->ftruncate; robots_fs->truncate = curr_fs->truncate; robots_fs->chmod = curr_fs->chmod; robots_fs->fchmod = curr_fs->fchmod; robots_fs->chown = curr_fs->chown; robots_fs->fchown = curr_fs->fchown; robots_fs->lchown = curr_fs->lchown; robots_fs->utimes = curr_fs->utimes; robots_fs->futimes = curr_fs->futimes; robots_fs->fsync = curr_fs->fsync; pr_fs_clear_cache2(path); auth_anon_allow_robots_enabled = TRUE; } return PR_DECLINED(cmd); } MODRET auth_post_retr(cmd_rec *cmd) { if (auth_anon_allow_robots == TRUE) { return PR_DECLINED(cmd); } if (auth_anon_allow_robots_enabled == TRUE) { int res; res = pr_unregister_fs("/robots.txt"); if (res < 0) { pr_log_debug(DEBUG9, "error removing 'robots' FS for '/robots.txt': %s", strerror(errno)); } auth_anon_allow_robots_enabled = FALSE; } return PR_DECLINED(cmd); } /* Configuration handlers */ MODRET set_accessdenymsg(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_accessgrantmsg(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: AllowChrootSymlinks on|off */ MODRET set_allowchrootsymlinks(cmd_rec *cmd) { int allow_chroot_symlinks = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); allow_chroot_symlinks = get_boolean(cmd, 1); if (allow_chroot_symlinks == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = allow_chroot_symlinks; return PR_HANDLED(cmd); } /* usage: AllowEmptyPasswords on|off */ MODRET set_allowemptypasswords(cmd_rec *cmd) { int allow_empty_passwords = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); allow_empty_passwords = get_boolean(cmd, 1); if (allow_empty_passwords == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = allow_empty_passwords; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: AnonAllowRobots on|off */ MODRET set_anonallowrobots(cmd_rec *cmd) { int allow_robots = -1; config_rec *c; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); allow_robots = get_boolean(cmd, 1); if (allow_robots == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = palloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = allow_robots; return PR_HANDLED(cmd); } MODRET set_anonrequirepassword(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } /* usage: AnonRejectPasswords pattern [flags] */ MODRET set_anonrejectpasswords(cmd_rec *cmd) { #ifdef PR_USE_REGEX config_rec *c; pr_regex_t *pre = NULL; int notmatch = FALSE, regex_flags = REG_EXTENDED|REG_NOSUB, res = 0; char *pattern = NULL; if (cmd->argc-1 < 1 || cmd->argc-1 > 2) { CONF_ERROR(cmd, "bad number of parameters"); } CHECK_CONF(cmd, CONF_ANON); /* Make sure that, if present, the flags parameter is correctly formatted. */ if (cmd->argc-1 == 2) { int flags = 0; /* We need to parse the flags parameter here, to see if any flags which * affect the compilation of the regex (e.g. NC) are present. */ flags = pr_filter_parse_flags(cmd->tmp_pool, cmd->argv[2]); if (flags < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": badly formatted flags parameter: '", cmd->argv[2], "'", NULL)); } if (flags == 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown flags '", cmd->argv[2], "'", NULL)); } regex_flags |= flags; } pre = pr_regexp_alloc(&auth_module); pattern = cmd->argv[1]; if (*pattern == '!') { notmatch = TRUE; pattern++; } res = pr_regexp_compile(pre, pattern, regex_flags); if (res != 0) { char errstr[200] = {'\0'}; pr_regexp_error(res, pre, errstr, 200); pr_regexp_free(NULL, pre); CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "Unable to compile regex '", cmd->argv[1], "': ", errstr, NULL)); } c = add_config_param(cmd->argv[0], 2, pre, NULL); c->argv[1] = palloc(c->pool, sizeof(int)); *((int *) c->argv[1]) = notmatch; return PR_HANDLED(cmd); #else CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0], " directive " "cannot be used on this system, as you do not have POSIX compliant " "regex support", NULL)); #endif } MODRET set_authaliasonly(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_authusingalias(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_createhome(cmd_rec *cmd) { int bool = -1, start = 2; mode_t mode = (mode_t) 0700, dirmode = (mode_t) 0711; char *skel_path = NULL; config_rec *c = NULL; uid_t cuid = 0; gid_t cgid = 0, hgid = -1; unsigned long flags = 0UL; if (cmd->argc-1 < 1) { CONF_ERROR(cmd, "wrong number of parameters"); } CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } /* No need to process the rest if bool is FALSE. */ if (bool == FALSE) { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } /* Check the mode parameter, if present */ if (cmd->argc-1 >= 2 && strcasecmp(cmd->argv[2], "dirmode") != 0 && strcasecmp(cmd->argv[2], "skel") != 0) { char *tmp = NULL; mode = strtol(cmd->argv[2], &tmp, 8); if (tmp && *tmp) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": bad mode parameter: '", cmd->argv[2], "'", NULL)); start = 3; } if (cmd->argc-1 > 2) { register unsigned int i; /* Cycle through the rest of the parameters */ for (i = start; i < cmd->argc;) { if (strcasecmp(cmd->argv[i], "skel") == 0) { struct stat st; /* Check that the skel directory, if configured, meets the * requirements. */ skel_path = cmd->argv[++i]; if (*skel_path != '/') { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "skel path '", skel_path, "' is not a full path", NULL)); } if (pr_fsio_stat(skel_path, &st) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to stat '", skel_path, "': ", strerror(errno), NULL)); } if (!S_ISDIR(st.st_mode)) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", skel_path, "' is not a directory", NULL)); } /* Must not be world-writable. */ if (st.st_mode & S_IWOTH) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", skel_path, "' is world-writable", NULL)); } /* Move the index past the skel parameter */ i++; } else if (strcasecmp(cmd->argv[i], "dirmode") == 0) { char *tmp = NULL; dirmode = strtol(cmd->argv[++i], &tmp, 8); if (tmp && *tmp) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad mode parameter: '", cmd->argv[i], "'", NULL)); /* Move the index past the dirmode parameter */ i++; } else if (strcasecmp(cmd->argv[i], "uid") == 0) { /* Check for a "~" parameter. */ if (strncmp(cmd->argv[i+1], "~", 2) != 0) { uid_t uid; if (pr_str2uid(cmd->argv[++i], &uid) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad UID parameter: '", cmd->argv[i], "'", NULL)); } cuid = uid; } else { cuid = (uid_t) -1; i++; } /* Move the index past the uid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "gid") == 0) { /* Check for a "~" parameter. */ if (strncmp(cmd->argv[i+1], "~", 2) != 0) { gid_t gid; if (pr_str2gid(cmd->argv[++i], &gid) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad GID parameter: '", cmd->argv[i], "'", NULL)); } cgid = gid; } else { cgid = (gid_t) -1; i++; } /* Move the index past the gid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "homegid") == 0) { char *tmp = NULL; gid_t gid; gid = strtol(cmd->argv[++i], &tmp, 10); if (tmp && *tmp) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad GID parameter: '", cmd->argv[i], "'", NULL)); } hgid = gid; /* Move the index past the homegid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "NoRootPrivs") == 0) { flags |= PR_MKHOME_FL_USE_USER_PRIVS; i++; } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown parameter: '", cmd->argv[i], "'", NULL)); } } } c = add_config_param(cmd->argv[0], 8, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->argv[1] = pcalloc(c->pool, sizeof(mode_t)); *((mode_t *) c->argv[1]) = mode; c->argv[2] = pcalloc(c->pool, sizeof(mode_t)); *((mode_t *) c->argv[2]) = dirmode; if (skel_path) { c->argv[3] = pstrdup(c->pool, skel_path); } c->argv[4] = pcalloc(c->pool, sizeof(uid_t)); *((uid_t *) c->argv[4]) = cuid; c->argv[5] = pcalloc(c->pool, sizeof(gid_t)); *((gid_t *) c->argv[5]) = cgid; c->argv[6] = pcalloc(c->pool, sizeof(gid_t)); *((gid_t *) c->argv[6]) = hgid; c->argv[7] = pcalloc(c->pool, sizeof(unsigned long)); *((unsigned long *) c->argv[7]) = flags; return PR_HANDLED(cmd); } MODRET add_defaultroot(cmd_rec *cmd) { config_rec *c; char *dir; unsigned int argc; void **argv; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (cmd->argc < 2) { CONF_ERROR(cmd, "syntax: DefaultRoot <directory> [<group-expression>]"); } argc = cmd->argc - 2; argv = cmd->argv; dir = *++argv; /* dir must be / or ~. */ if (*dir != '/' && *dir != '~') { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") absolute pathname " "required", NULL)); } if (strchr(dir, '*')) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); } if (*(dir + strlen(dir) - 1) != '/') { dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); } acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(void *)); argv = c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } *argv = NULL; return PR_HANDLED(cmd); } MODRET add_defaultchdir(cmd_rec *cmd) { config_rec *c; char *dir; unsigned int argc; void **argv; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2) { CONF_ERROR(cmd, "syntax: DefaultChdir <directory> [<group-expression>]"); } argc = cmd->argc - 2; argv = cmd->argv; dir = *++argv; if (strchr(dir, '*')) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); } if (*(dir + strlen(dir) - 1) != '/') { dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); } acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(void *)); argv = c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) { while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } } *argv = NULL; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_displaylogin(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_grouppassword(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_loginpasswordprompt(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerClass class max|"none" ["message"] */ MODRET set_maxclientsclass(cmd_rec *cmd) { int max; config_rec *c; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[2], "none") == 0) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[2], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "max must be 'none' or a number greater than 0"); } if (cmd->argc == 4) { c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL); c->argv[0] = pstrdup(c->pool, cmd->argv[1]); c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = max; c->argv[2] = pstrdup(c->pool, cmd->argv[3]); } else { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pstrdup(c->pool, cmd->argv[1]); c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = max; } return PR_HANDLED(cmd); } /* usage: MaxClients max|"none" ["message"] */ MODRET set_maxclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerHost max|"none" ["message"] */ MODRET set_maxhostclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerUser max|"none" ["message"] */ MODRET set_maxuserclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxConnectionsPerHost max|"none" ["message"] */ MODRET set_maxconnectsperhost(cmd_rec *cmd) { int max; config_rec *c; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[1], "none") == 0) max = 0; else { char *tmp = NULL; max = (int) strtol(cmd->argv[1], &tmp, 10); if ((tmp && *tmp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; return PR_HANDLED(cmd); } /* usage: MaxHostsPerUser max|"none" ["message"] */ MODRET set_maxhostsperuser(cmd_rec *cmd) { int max; config_rec *c = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_maxloginattempts(cmd_rec *cmd) { int max; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[1], "none") == 0) { max = 0; } else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; return PR_HANDLED(cmd); } /* usage: MaxPasswordSize len */ MODRET set_maxpasswordsize(cmd_rec *cmd) { config_rec *c; size_t password_len; char *len, *ptr = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); len = cmd->argv[1]; if (*len == '-') { CONF_ERROR(cmd, "badly formatted parameter"); } password_len = strtoul(len, &ptr, 10); if (ptr && *ptr) { CONF_ERROR(cmd, "badly formatted parameter"); } /* XXX Applies to the following modules, which use crypt(3): * * mod_ldap (ldap_auth_check; "check" authtab) * ldap_auth_auth ("auth" authtab) calls pr_auth_check() * mod_sql (sql_auth_crypt, via SQLAuthTypes; cmd_check "check" authtab dispatches here) * cmd_auth ("auth" authtab) calls pr_auth_check() * mod_auth_file (authfile_chkpass, "check" authtab) * authfile_auth ("auth" authtab) calls pr_auth_check() * mod_auth_unix (pw_check, "check" authtab) * pw_auth ("auth" authtab) calls pr_auth_check() * * mod_sftp uses pr_auth_authenticate(), which will dispatch into above * * mod_radius does NOT use either -- up to RADIUS server policy? * * Is there a common code path that all of the above go through? */ c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = palloc(c->pool, sizeof(size_t)); *((size_t *) c->argv[0]) = password_len; return PR_HANDLED(cmd); } MODRET set_requirevalidshell(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: RewriteHome on|off */ MODRET set_rewritehome(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_rootlogin(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd,1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = (unsigned char) bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: RootRevoke on|off|UseNonCompliantActiveTransfer */ MODRET set_rootrevoke(cmd_rec *cmd) { int root_revoke = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* A RootRevoke value of 0 indicates 'false', 1 indicates 'true', and * 2 indicates 'NonCompliantActiveTransfer'. */ root_revoke = get_boolean(cmd, 1); if (root_revoke == -1) { if (strcasecmp(cmd->argv[1], "UseNonCompliantActiveTransfer") != 0 && strcasecmp(cmd->argv[1], "UseNonCompliantActiveTransfers") != 0) { CONF_ERROR(cmd, "expected Boolean parameter"); } root_revoke = 2; } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = (unsigned char) root_revoke; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_timeoutlogin(cmd_rec *cmd) { int timeout = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; return PR_HANDLED(cmd); } MODRET set_timeoutsession(cmd_rec *cmd) { int timeout = 0, precedence = 0; config_rec *c = NULL; int ctxt = (cmd->config && cmd->config->config_type != CONF_PARAM ? cmd->config->config_type : cmd->server->config_type ? cmd->server->config_type : CONF_ROOT); /* this directive must have either 1 or 3 arguments */ if (cmd->argc-1 != 1 && cmd->argc-1 != 3) { CONF_ERROR(cmd, "missing parameters"); } CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Set the precedence for this config_rec based on its configuration * context. */ if (ctxt & CONF_GLOBAL) { precedence = 1; /* These will never appear simultaneously */ } else if ((ctxt & CONF_ROOT) || (ctxt & CONF_VIRTUAL)) { precedence = 2; } else if (ctxt & CONF_ANON) { precedence = 3; } if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } if (timeout == 0) { /* do nothing */ return PR_HANDLED(cmd); } if (cmd->argc-1 == 3) { if (strncmp(cmd->argv[2], "user", 5) == 0 || strncmp(cmd->argv[2], "group", 6) == 0 || strncmp(cmd->argv[2], "class", 6) == 0) { /* no op */ } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[0], ": unknown classifier used: '", cmd->argv[2], "'", NULL)); } } if (cmd->argc-1 == 1) { c = add_config_param(cmd->argv[0], 2, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = precedence; } else if (cmd->argc-1 == 3) { array_header *acl = NULL; unsigned int argc; void **argv; argc = cmd->argc - 3; argv = cmd->argv + 2; acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 2; /* Add 3 to argc for the argv of the config_rec: one for the * seconds value, one for the precedence, one for the classifier, * and one for the terminating NULL. */ c->argv = pcalloc(c->pool, ((argc + 4) * sizeof(void *))); /* Capture the config_rec's argv pointer for doing the by-hand * population. */ argv = c->argv; /* Copy in the seconds. */ *argv = pcalloc(c->pool, sizeof(int)); *((int *) *argv++) = timeout; /* Copy in the precedence. */ *argv = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) *argv++) = precedence; /* Copy in the classifier. */ *argv++ = pstrdup(c->pool, cmd->argv[2]); /* now, copy in the expression arguments */ if (argc && acl) { while (argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } } /* don't forget the terminating NULL */ *argv = NULL; } else { /* Should never reach here. */ CONF_ERROR(cmd, "wrong number of parameters"); } c->flags |= CF_MERGEDOWN_MULTI; return PR_HANDLED(cmd); } MODRET set_useftpusers(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: UseLastlog on|off */ MODRET set_uselastlog(cmd_rec *cmd) { #ifdef PR_USE_LASTLOG int bool; config_rec *c; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); #else CONF_ERROR(cmd, "requires lastlog support (--with-lastlog)"); #endif /* PR_USE_LASTLOG */ } /* usage: UserAlias alias real-user */ MODRET set_useralias(cmd_rec *cmd) { config_rec *c = NULL; char *alias, *real_user; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Make sure that the given names differ. */ alias = cmd->argv[1]; real_user = cmd->argv[2]; if (strcmp(alias, real_user) == 0) { CONF_ERROR(cmd, "alias and real user names must differ"); } c = add_config_param_str(cmd->argv[0], 2, alias, real_user); /* Note: only merge this directive down if it is not appearing in an * <Anonymous> context. */ if (!check_context(cmd, CONF_ANON)) { c->flags |= CF_MERGEDOWN_MULTI; } return PR_HANDLED(cmd); } MODRET set_userdirroot(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_userpassword(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: WtmpLog on|off */ MODRET set_wtmplog(cmd_rec *cmd) { int use_wtmp = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (strcasecmp(cmd->argv[1], "NONE") == 0) { use_wtmp = FALSE; } else { use_wtmp = get_boolean(cmd, 1); if (use_wtmp == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = use_wtmp; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* Module API tables */ static conftable auth_conftab[] = { { "AccessDenyMsg", set_accessdenymsg, NULL }, { "AccessGrantMsg", set_accessgrantmsg, NULL }, { "AllowChrootSymlinks", set_allowchrootsymlinks, NULL }, { "AllowEmptyPasswords", set_allowemptypasswords, NULL }, { "AnonAllowRobots", set_anonallowrobots, NULL }, { "AnonRequirePassword", set_anonrequirepassword, NULL }, { "AnonRejectPasswords", set_anonrejectpasswords, NULL }, { "AuthAliasOnly", set_authaliasonly, NULL }, { "AuthUsingAlias", set_authusingalias, NULL }, { "CreateHome", set_createhome, NULL }, { "DefaultChdir", add_defaultchdir, NULL }, { "DefaultRoot", add_defaultroot, NULL }, { "DisplayLogin", set_displaylogin, NULL }, { "GroupPassword", set_grouppassword, NULL }, { "LoginPasswordPrompt", set_loginpasswordprompt, NULL }, { "MaxClients", set_maxclients, NULL }, { "MaxClientsPerClass", set_maxclientsclass, NULL }, { "MaxClientsPerHost", set_maxhostclients, NULL }, { "MaxClientsPerUser", set_maxuserclients, NULL }, { "MaxConnectionsPerHost", set_maxconnectsperhost, NULL }, { "MaxHostsPerUser", set_maxhostsperuser, NULL }, { "MaxLoginAttempts", set_maxloginattempts, NULL }, { "MaxPasswordSize", set_maxpasswordsize, NULL }, { "RequireValidShell", set_requirevalidshell, NULL }, { "RewriteHome", set_rewritehome, NULL }, { "RootLogin", set_rootlogin, NULL }, { "RootRevoke", set_rootrevoke, NULL }, { "TimeoutLogin", set_timeoutlogin, NULL }, { "TimeoutSession", set_timeoutsession, NULL }, { "UseFtpUsers", set_useftpusers, NULL }, { "UseLastlog", set_uselastlog, NULL }, { "UserAlias", set_useralias, NULL }, { "UserDirRoot", set_userdirroot, NULL }, { "UserPassword", set_userpassword, NULL }, { "WtmpLog", set_wtmplog, NULL }, { NULL, NULL, NULL } }; static cmdtable auth_cmdtab[] = { { PRE_CMD, C_USER, G_NONE, auth_pre_user, FALSE, FALSE, CL_AUTH }, { CMD, C_USER, G_NONE, auth_user, FALSE, FALSE, CL_AUTH }, { PRE_CMD, C_PASS, G_NONE, auth_pre_pass, FALSE, FALSE, CL_AUTH }, { CMD, C_PASS, G_NONE, auth_pass, FALSE, FALSE, CL_AUTH }, { POST_CMD, C_PASS, G_NONE, auth_post_pass, FALSE, FALSE, CL_AUTH }, { LOG_CMD, C_PASS, G_NONE, auth_log_pass, FALSE, FALSE }, { LOG_CMD_ERR,C_PASS, G_NONE, auth_err_pass, FALSE, FALSE }, { CMD, C_ACCT, G_NONE, auth_acct, FALSE, FALSE, CL_AUTH }, { CMD, C_REIN, G_NONE, auth_rein, FALSE, FALSE, CL_AUTH }, /* For the automatic robots.txt handling */ { PRE_CMD, C_RETR, G_NONE, auth_pre_retr, FALSE, FALSE }, { POST_CMD, C_RETR, G_NONE, auth_post_retr, FALSE, FALSE }, { POST_CMD_ERR,C_RETR,G_NONE, auth_post_retr, FALSE, FALSE }, { 0, NULL } }; /* Module interface */ module auth_module = { NULL, NULL, /* Module API version */ 0x20, /* Module name */ "auth", /* Module configuration directive table */ auth_conftab, /* Module command handler table */ auth_cmdtab, /* Module authentication handler table */ NULL, /* Module initialization function */ auth_init, /* Session initialization function */ auth_sess_init };
./CrossVul/dataset_final_sorted/CWE-59/c/good_3264_0
crossvul-cpp_data_good_436_5
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Configuration file parser/reader. Place into the dynamic * data structure representation the conf file representing * the loadbalanced server pool. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <unistd.h> #include <string.h> #include <stdint.h> #include <net/if_arp.h> #include <sys/types.h> #include <sys/stat.h> //#include <unistd.h> #include <stdio.h> #include <ctype.h> #include <net/if.h> #include "vrrp_parser.h" #include "logger.h" #include "parser.h" #include "bitops.h" #include "utils.h" #include "main.h" #include "global_data.h" #include "global_parser.h" #include "vrrp_data.h" #include "vrrp_ipaddress.h" #include "vrrp_sync.h" #include "vrrp_track.h" #ifdef _HAVE_VRRP_VMAC_ #include "vrrp_vmac.h" #endif #include "vrrp_static_track.h" #ifdef _WITH_LVS_ #include "check_parser.h" #endif #ifdef _WITH_BFD_ #include "bfd_parser.h" #endif /* Used for initialising track files */ static enum { TRACK_FILE_NO_INIT, TRACK_FILE_CREATE, TRACK_FILE_INIT, } track_file_init; static int track_file_init_value; static bool script_user_set; static bool remove_script; /* track groups for static items */ static void static_track_group_handler(vector_t *strvec) { element e; static_track_group_t *tg; char* gname; if (!strvec) return; if (vector_count(strvec) != 2) { report_config_error(CONFIG_GENERAL_ERROR, "track_group must have a name - skipping"); skip_block(true); return; } gname = strvec_slot(strvec, 1); /* check group doesn't already exist */ LIST_FOREACH(vrrp_data->static_track_groups, tg, e) { if (!strcmp(gname,tg->gname)) { report_config_error(CONFIG_GENERAL_ERROR, "track_group %s already defined", gname); skip_block(true); return; } } alloc_static_track_group(gname); } static void static_track_group_group_handler(vector_t *strvec) { static_track_group_t *tgroup = LIST_TAIL_DATA(vrrp_data->static_track_groups); if (tgroup->iname) { report_config_error(CONFIG_GENERAL_ERROR, "Group list already specified for sync group %s", tgroup->gname); skip_block(true); return; } tgroup->iname = read_value_block(strvec); if (!tgroup->iname) report_config_error(CONFIG_GENERAL_ERROR, "Warning - track group %s has empty group block", tgroup->gname); } /* Static addresses handler */ static void static_addresses_handler(vector_t *strvec) { global_data->have_vrrp_config = true; if (!strvec) return; alloc_value_block(alloc_saddress, vector_slot(strvec, 0)); } #ifdef _HAVE_FIB_ROUTING_ /* Static routes handler */ static void static_routes_handler(vector_t *strvec) { global_data->have_vrrp_config = true; if (!strvec) return; alloc_value_block(alloc_sroute, vector_slot(strvec, 0)); } /* Static rules handler */ static void static_rules_handler(vector_t *strvec) { global_data->have_vrrp_config = true; if (!strvec) return; alloc_value_block(alloc_srule, vector_slot(strvec, 0)); } #endif /* VRRP handlers */ static void vrrp_sync_group_handler(vector_t *strvec) { list l; element e; vrrp_sgroup_t *sg; char* gname; if (!strvec) return; if (vector_count(strvec) != 2) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_sync_group must have a name - skipping"); skip_block(true); return; } gname = strvec_slot(strvec, 1); /* check group doesn't already exist */ if (!LIST_ISEMPTY(vrrp_data->vrrp_sync_group)) { l = vrrp_data->vrrp_sync_group; for (e = LIST_HEAD(l); e; ELEMENT_NEXT(e)) { sg = ELEMENT_DATA(e); if (!strcmp(gname,sg->gname)) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp sync group %s already defined", gname); skip_block(true); return; } } } alloc_vrrp_sync_group(gname); } static void vrrp_group_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->iname) { report_config_error(CONFIG_GENERAL_ERROR, "Group list already specified for sync group %s", vgroup->gname); skip_block(true); return; } vgroup->iname = read_value_block(strvec); if (!vgroup->iname) report_config_error(CONFIG_GENERAL_ERROR, "Warning - sync group %s has empty group block", vgroup->gname); } static void vrrp_group_track_if_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_group_track_if, vector_slot(strvec, 0)); } static void vrrp_group_track_scr_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_group_track_script, vector_slot(strvec, 0)); } static void vrrp_group_track_file_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_group_track_file, vector_slot(strvec, 0)); } #if defined _WITH_BFD_ static void vrrp_group_track_bfd_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_group_track_bfd, vector_slot(strvec, 0)); } #endif static inline notify_script_t* set_vrrp_notify_script(__attribute__((unused)) vector_t *strvec, int extra_params) { return notify_script_init(extra_params, "notify"); } static void vrrp_gnotify_backup_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->script_backup) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp group %s: notify_backup script already specified - ignoring %s", vgroup->gname, FMT_STR_VSLOT(strvec,1)); return; } vgroup->script_backup = set_vrrp_notify_script(strvec, 0); vgroup->notify_exec = true; } static void vrrp_gnotify_master_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->script_master) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp group %s: notify_master script already specified - ignoring %s", vgroup->gname, FMT_STR_VSLOT(strvec,1)); return; } vgroup->script_master = set_vrrp_notify_script(strvec, 0); vgroup->notify_exec = true; } static void vrrp_gnotify_fault_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->script_fault) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp group %s: notify_fault script already specified - ignoring %s", vgroup->gname, FMT_STR_VSLOT(strvec,1)); return; } vgroup->script_fault = set_vrrp_notify_script(strvec, 0); vgroup->notify_exec = true; } static void vrrp_gnotify_stop_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->script_stop) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp group %s: notify_stop script already specified - ignoring %s", vgroup->gname, FMT_STR_VSLOT(strvec,1)); return; } vgroup->script_stop = set_vrrp_notify_script(strvec, 0); vgroup->notify_exec = true; } static void vrrp_gnotify_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->script) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp group %s: notify script already specified - ignoring %s", vgroup->gname, FMT_STR_VSLOT(strvec,1)); return; } vgroup->script = set_vrrp_notify_script(strvec, 4); vgroup->notify_exec = true; } static void vrrp_gsmtp_handler(__attribute__((unused)) vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec, 1)); if (res == -1) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_group smtp_alert parameter %s", FMT_STR_VSLOT(strvec, 1)); return; } } vgroup->smtp_alert = res; } static void vrrp_gglobal_tracking_handler(__attribute__((unused)) vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); report_config_error(CONFIG_GENERAL_ERROR, "(%s) global_tracking is deprecated. Use track_interface/script/file on the sync group", vgroup->gname); vgroup->sgroup_tracking_weight = true; } static void vrrp_sg_tracking_weight_handler(__attribute__((unused)) vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); vgroup->sgroup_tracking_weight = true; } static void vrrp_handler(vector_t *strvec) { list l; element e; vrrp_t *vrrp; char *iname; global_data->have_vrrp_config = true; if (!strvec) return; if (vector_count(strvec) != 2) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_instance must have a name"); skip_block(true); return; } iname = strvec_slot(strvec,1); /* Make sure the vrrp instance doesn't already exist */ if (!LIST_ISEMPTY(vrrp_data->vrrp)) { l = vrrp_data->vrrp; for (e = LIST_HEAD(l); e; ELEMENT_NEXT(e)) { vrrp = ELEMENT_DATA(e); if (!strcmp(iname,vrrp->iname)) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp instance %s already defined", iname ); skip_block(true); return; } } } alloc_vrrp(iname); } #ifdef _HAVE_VRRP_VMAC_ static void vrrp_vmac_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); interface_t *ifp; __set_bit(VRRP_VMAC_BIT, &vrrp->vmac_flags); if (vector_size(strvec) >= 2) { if (strlen(strvec_slot(strvec, 1)) >= IFNAMSIZ) { report_config_error(CONFIG_GENERAL_ERROR, "VMAC interface name '%s' too long - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } strcpy(vrrp->vmac_ifname, strvec_slot(strvec, 1)); /* Check if the interface exists and is a macvlan we can use */ if ((ifp = if_get_by_ifname(vrrp->vmac_ifname, IF_NO_CREATE)) && ifp->vmac_type != MACVLAN_MODE_PRIVATE) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) interface %s already exists and is not a private macvlan; ignoring vmac if_name", vrrp->iname, vrrp->vmac_ifname); vrrp->vmac_ifname[0] = '\0'; } } } static void vrrp_vmac_xmit_base_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); __set_bit(VRRP_VMAC_XMITBASE_BIT, &vrrp->vmac_flags); } #endif static void vrrp_unicast_peer_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_unicast_peer, vector_slot(strvec, 0)); } #ifdef _WITH_UNICAST_CHKSUM_COMPAT_ static void vrrp_unicast_chksum_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vector_size(strvec) >= 2) { if (!strcmp(strvec_slot(strvec, 1), "never")) vrrp->unicast_chksum_compat = CHKSUM_COMPATIBILITY_NEVER; else report_config_error(CONFIG_GENERAL_ERROR, "(%s) Unknown old_unicast_chksum mode %s - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); } else vrrp->unicast_chksum_compat = CHKSUM_COMPATIBILITY_CONFIG; } #endif static void vrrp_native_ipv6_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->family == AF_INET) { report_config_error(CONFIG_GENERAL_ERROR,"(%s) Cannot specify native_ipv6 with IPv4 addresses", vrrp->iname); return; } vrrp->family = AF_INET6; vrrp->version = VRRP_VERSION_3; } static void vrrp_state_handler(vector_t *strvec) { char *str = strvec_slot(strvec, 1); vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (!strcmp(str, "MASTER")) vrrp->wantstate = VRRP_STATE_MAST; else if (!strcmp(str, "BACKUP")) { if (vrrp->wantstate == VRRP_STATE_MAST) report_config_error(CONFIG_GENERAL_ERROR, "(%s) state previously set as MASTER - ignoring BACKUP", vrrp->iname); else vrrp->wantstate = VRRP_STATE_BACK; } else { report_config_error(CONFIG_GENERAL_ERROR,"(%s) unknown state '%s', defaulting to BACKUP", vrrp->iname, str); vrrp->wantstate = VRRP_STATE_BACK; } } static void vrrp_int_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); char *name = strvec_slot(strvec, 1); if (strlen(name) >= IFNAMSIZ) { report_config_error(CONFIG_GENERAL_ERROR, "Interface name '%s' too long - ignoring", name); return; } vrrp->ifp = if_get_by_ifname(name, IF_CREATE_IF_DYNAMIC); if (!vrrp->ifp) report_config_error(CONFIG_GENERAL_ERROR, "WARNING - interface %s for vrrp_instance %s doesn't exist", name, vrrp->iname); else if (vrrp->ifp->hw_type == ARPHRD_LOOPBACK) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) cannot use a loopback interface (%s) for vrrp - ignoring", vrrp->iname, vrrp->ifp->ifname); vrrp->ifp = NULL; } #ifdef _HAVE_VRRP_VMAC_ vrrp->configured_ifp = vrrp->ifp; #endif } static void vrrp_linkbeat_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->linkbeat_use_polling = true; } static void vrrp_track_if_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_track_if, vector_slot(strvec, 0)); } static void vrrp_track_scr_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_track_script, vector_slot(strvec, 0)); } static void vrrp_track_file_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_track_file, vector_slot(strvec, 0)); } static void vrrp_dont_track_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->dont_track_primary = true; } #ifdef _WITH_BFD_ static void vrrp_track_bfd_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_track_bfd, vector_slot(strvec, 0)); } #endif static void vrrp_srcip_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); struct sockaddr_storage *saddr = &vrrp->saddr; if (inet_stosockaddr(strvec_slot(strvec, 1), NULL, saddr)) { report_config_error(CONFIG_GENERAL_ERROR, "Configuration error: VRRP instance[%s] malformed" " src address[%s]. Skipping..." , vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } vrrp->saddr_from_config = true; if (vrrp->family == AF_UNSPEC) vrrp->family = saddr->ss_family; else if (saddr->ss_family != vrrp->family) { report_config_error(CONFIG_GENERAL_ERROR, "Configuration error: VRRP instance[%s] and src address" "[%s] MUST be of the same family !!! Skipping..." , vrrp->iname, FMT_STR_VSLOT(strvec, 1)); saddr->ss_family = AF_UNSPEC; vrrp->saddr_from_config = false; } } static void vrrp_track_srcip_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->track_saddr = true; } static void vrrp_vrid_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned vrid; if (!read_unsigned_strvec(strvec, 1, &vrid, 1, 255, false)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): VRID '%s' not valid - must be between 1 & 255", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } vrrp->vrid = (uint8_t)vrid; } static void vrrp_prio_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned base_priority; if (!read_unsigned_strvec(strvec, 1, &base_priority, 1, VRRP_PRIO_OWNER, false)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) Priority not valid! must be between 1 & %d. Using default %d", vrrp->iname, VRRP_PRIO_OWNER, VRRP_PRIO_DFL); vrrp->base_priority = VRRP_PRIO_DFL; } else vrrp->base_priority = (uint8_t)base_priority; } static void vrrp_adv_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); double adver_int; bool res; res = read_double_strvec(strvec, 1, &adver_int, 0.01, 255.0, true); /* Simple check - just positive */ if (!res || adver_int <= 0) report_config_error(CONFIG_GENERAL_ERROR, "(%s) Advert interval (%s) not valid! Must be > 0 - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); else vrrp->adver_int = (unsigned)(adver_int * TIMER_HZ); } static void vrrp_debug_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned debug; if (!read_unsigned_strvec(strvec, 1, &debug, 0, 4, true)) report_config_error(CONFIG_GENERAL_ERROR, "(%s) Debug value '%s' not valid; must be between 0-4", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); else vrrp->debug = debug; } static void vrrp_skip_check_adv_addr_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); int res; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec, 1)); if (res >= 0) vrrp->skip_check_adv_addr = (bool)res; else report_config_error(CONFIG_GENERAL_ERROR, "(%s) invalid skip_check_adv_addr %s specified", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); } else { /* Defaults to true */ vrrp->skip_check_adv_addr = true; } } static void vrrp_strict_mode_handler(vector_t *strvec) { int res; vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec, 1)); if (res >= 0) vrrp->strict_mode = (bool)res; else report_config_error(CONFIG_GENERAL_ERROR, "(%s) invalid strict_mode %s specified", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); } else { /* Defaults to true */ vrrp->strict_mode = true; } } static void vrrp_nopreempt_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->nopreempt = 1; } static void /* backwards compatibility */ vrrp_preempt_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->nopreempt = 0; } static void vrrp_preempt_delay_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); double preempt_delay; if (!read_double_strvec(strvec, 1, &preempt_delay, 0, TIMER_MAX_SEC, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) Preempt_delay not valid! must be between 0-%d", vrrp->iname, TIMER_MAX_SEC); vrrp->preempt_delay = 0; } else vrrp->preempt_delay = (unsigned long)(preempt_delay * TIMER_HZ); } static void vrrp_notify_backup_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->script_backup) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) notify_backup script already specified - ignoring %s", vrrp->iname, FMT_STR_VSLOT(strvec,1)); return; } vrrp->script_backup = set_vrrp_notify_script(strvec, 0); vrrp->notify_exec = true; } static void vrrp_notify_master_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->script_master) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) notify_master script already specified - ignoring %s", vrrp->iname, FMT_STR_VSLOT(strvec,1)); return; } vrrp->script_master = set_vrrp_notify_script(strvec, 0); vrrp->notify_exec = true; } static void vrrp_notify_fault_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->script_fault) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) notify_fault script already specified - ignoring %s", vrrp->iname, FMT_STR_VSLOT(strvec,1)); return; } vrrp->script_fault = set_vrrp_notify_script(strvec, 0); vrrp->notify_exec = true; } static void vrrp_notify_stop_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->script_stop) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) notify_stop script already specified - ignoring %s", vrrp->iname, FMT_STR_VSLOT(strvec,1)); return; } vrrp->script_stop = set_vrrp_notify_script(strvec, 0); vrrp->notify_exec = true; } static void vrrp_notify_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->script) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) notify script already specified - ignoring %s", vrrp->iname, FMT_STR_VSLOT(strvec,1)); return; } vrrp->script = set_vrrp_notify_script(strvec, 4); vrrp->notify_exec = true; } static void vrrp_notify_master_rx_lower_pri(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->script_master_rx_lower_pri) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) notify_master_rx_lower_pri script already specified - ignoring %s", vrrp->iname, FMT_STR_VSLOT(strvec,1)); return; } vrrp->script_master_rx_lower_pri = set_vrrp_notify_script(strvec, 0); vrrp->notify_exec = true; } static void vrrp_smtp_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec, 1)); if (res == -1) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_instance smtp_alert parameter %s", FMT_STR_VSLOT(strvec, 1)); return; } } vrrp->smtp_alert = res; } #ifdef _WITH_LVS_ static void vrrp_lvs_syncd_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); report_config_error(CONFIG_GENERAL_ERROR, "(%s) Specifying lvs_sync_daemon_interface against a vrrp is deprecated.", vrrp->iname); /* Deprecated after v1.2.19 */ report_config_error(CONFIG_GENERAL_ERROR, " %*sPlease use global lvs_sync_daemon", (int)strlen(vrrp->iname) - 2, ""); if (global_data->lvs_syncd.ifname) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) lvs_sync_daemon_interface has already been specified as %s - ignoring", vrrp->iname, global_data->lvs_syncd.ifname); return; } global_data->lvs_syncd.ifname = set_value(strvec); global_data->lvs_syncd.vrrp = vrrp; } #endif static void vrrp_garp_delay_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned delay; if (!read_unsigned_strvec(strvec, 1, &delay, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): garp_master_delay '%s' invalid - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } vrrp->garp_delay = delay * TIMER_HZ; } static void vrrp_garp_refresh_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned refresh; if (!read_unsigned_strvec(strvec, 1, &refresh, 0, UINT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): Invalid garp_master_refresh '%s' - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); vrrp->garp_refresh.tv_sec = 0; } else vrrp->garp_refresh.tv_sec = refresh; vrrp->garp_refresh.tv_usec = 0; } static void vrrp_garp_rep_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned repeats; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &repeats, 0, UINT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): garp_master_repeat '%s' invalid - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } if (repeats == 0) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): garp_master_repeat must be greater than 0, setting to 1", vrrp->iname); repeats = 1; } vrrp->garp_rep = repeats; } static void vrrp_garp_refresh_rep_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned repeats; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &repeats, 0, UINT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): garp_master_refresh_repeat '%s' invalid - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } if (repeats == 0) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): garp_master_refresh_repeat must be greater than 0, setting to 1", vrrp->iname); repeats = 1; } vrrp->garp_refresh_rep = repeats; } static void vrrp_garp_lower_prio_delay_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned delay; if (!read_unsigned_strvec(strvec, 1, &delay, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): garp_lower_prio_delay '%s' invalid - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } vrrp->garp_lower_prio_delay = delay * TIMER_HZ; } static void vrrp_garp_lower_prio_rep_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned garp_lower_prio_rep; if (!read_unsigned_strvec(strvec, 1, &garp_lower_prio_rep, 0, INT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): Invalid garp_lower_prio_repeat '%s'", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } vrrp->garp_lower_prio_rep = garp_lower_prio_rep; } static void vrrp_lower_prio_no_advert_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); int res; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec, 1)); if (res >= 0) vrrp->lower_prio_no_advert = (unsigned)res; else report_config_error(CONFIG_GENERAL_ERROR, "(%s) invalid lower_prio_no_advert %s specified", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); } else { /* Defaults to true */ vrrp->lower_prio_no_advert = true; } } static void vrrp_higher_prio_send_advert_handler(vector_t *strvec) { int res; vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec, 1)); if (res >= 0) vrrp->higher_prio_send_advert = (unsigned)res; else report_config_error(CONFIG_GENERAL_ERROR, "(%s) invalid higher_prio_send_advert %s specified", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); } else { /* Defaults to true */ vrrp->higher_prio_send_advert = true; } } static void kernel_rx_buf_size_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned rx_buf_size; if (vector_size(strvec) == 2 && read_unsigned_strvec(strvec, 1, &rx_buf_size, 0, UINT_MAX, false)) { vrrp->kernel_rx_buf_size = rx_buf_size; return; } report_config_error(CONFIG_GENERAL_ERROR, "(%s) invalid kernel_rx_buf_size specified", vrrp->iname); } #if defined _WITH_VRRP_AUTH_ static void vrrp_auth_type_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); char *str = strvec_slot(strvec, 1); if (!strcmp(str, "AH")) vrrp->auth_type = VRRP_AUTH_AH; else if (!strcmp(str, "PASS")) vrrp->auth_type = VRRP_AUTH_PASS; else report_config_error(CONFIG_GENERAL_ERROR, "(%s) unknown authentication type '%s'", vrrp->iname, str); } static void vrrp_auth_pass_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); char *str = strvec_slot(strvec, 1); size_t max_size = sizeof (vrrp->auth_data); size_t str_len = strlen(str); if (str_len > max_size) { str_len = max_size; report_config_error(CONFIG_GENERAL_ERROR, "Truncating auth_pass to %zu characters", max_size); } memset(vrrp->auth_data, 0, max_size); memcpy(vrrp->auth_data, str, str_len); } #endif static void vrrp_vip_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_vip, vector_slot(strvec, 0)); } static void vrrp_evip_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_evip, vector_slot(strvec, 0)); } static void vrrp_promote_secondaries_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->promote_secondaries = true; } #ifdef _HAVE_FIB_ROUTING_ static void vrrp_vroutes_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_vroute, vector_slot(strvec, 0)); } static void vrrp_vrules_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_vrule, vector_slot(strvec, 0)); } #endif static void vrrp_script_handler(vector_t *strvec) { if (!strvec) return; alloc_vrrp_script(strvec_slot(strvec, 1)); script_user_set = false; remove_script = false; } static void vrrp_vscript_script_handler(__attribute__((unused)) vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); vector_t *strvec_qe; /* We need to allow quoted and escaped strings for the script and parameters */ strvec_qe = alloc_strvec_quoted_escaped(NULL); set_script_params_array(strvec_qe, &vscript->script, 0); free_strvec(strvec_qe); } static void vrrp_vscript_interval_handler(vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); unsigned interval; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &interval, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): vrrp script interval '%s' must be between 1 and %u - ignoring", vscript->sname, FMT_STR_VSLOT(strvec, 1), UINT_MAX / TIMER_HZ); return; } if (interval == 0) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): vrrp script interval must be greater than 0, setting to 1", vscript->sname); interval = 1; } vscript->interval = interval * TIMER_HZ; } static void vrrp_vscript_timeout_handler(vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); unsigned timeout; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &timeout, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): vrrp script timeout '%s' invalid - ignoring", vscript->sname, FMT_STR_VSLOT(strvec, 1)); return; } if (timeout == 0) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): vrrp script timeout must be greater than 0, setting to 1", vscript->sname); timeout = 1; } vscript->timeout = timeout * TIMER_HZ; } static void vrrp_vscript_weight_handler(vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); int weight; if (!read_int_strvec(strvec, 1, &weight, -253, 253, true)) report_config_error(CONFIG_GENERAL_ERROR, "vrrp_script %s weight %s must be in [-253, 253]", vscript->sname, FMT_STR_VSLOT(strvec, 1)); vscript->weight = weight; } static void vrrp_vscript_rise_handler(vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); unsigned rise; if (!read_unsigned_strvec(strvec, 1, &rise, 1, INT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): vrrp script rise value '%s' invalid, defaulting to 1", vscript->sname, FMT_STR_VSLOT(strvec, 1)); vscript->rise = 1; } else vscript->rise = rise; } static void vrrp_vscript_fall_handler(vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); unsigned fall; if (!read_unsigned_strvec(strvec, 1, &fall, 1, INT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): vrrp script fall value '%s' invalid, defaulting to 1", vscript->sname, FMT_STR_VSLOT(strvec, 1)); vscript->fall = 1; } else vscript->fall = fall; } static void vrrp_vscript_user_handler(vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); if (set_script_uid_gid(strvec, 1, &vscript->script.uid, &vscript->script.gid)) { report_config_error(CONFIG_GENERAL_ERROR, "Unable to set uid/gid for script %s", cmd_str(&vscript->script)); remove_script = true; } else { remove_script = false; script_user_set = true; } } static void vrrp_vscript_end_handler(void) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); if (!vscript->script.args || !vscript->script.args[0]) { report_config_error(CONFIG_GENERAL_ERROR, "No script set for vrrp_script %s - removing", vscript->sname); remove_script = true; } else if (!remove_script) { if (script_user_set) return; if (set_default_script_user(NULL, NULL)) { report_config_error(CONFIG_GENERAL_ERROR, "Unable to set default user for vrrp script %s - removing", vscript->sname); remove_script = true; } } if (remove_script) { free_list_element(vrrp_data->vrrp_script, vrrp_data->vrrp_script->tail); return; } vscript->script.uid = default_script_uid; vscript->script.gid = default_script_gid; } static void vrrp_tfile_handler(vector_t *strvec) { if (!strvec) return; alloc_vrrp_file(strvec_slot(strvec, 1)); track_file_init = TRACK_FILE_NO_INIT; } static void vrrp_tfile_file_handler(vector_t *strvec) { vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files); if (tfile->file_path) { report_config_error(CONFIG_GENERAL_ERROR, "File already set for track file %s - ignoring %s", tfile->fname, FMT_STR_VSLOT(strvec, 1)); return; } tfile->file_path = set_value(strvec); } static void vrrp_tfile_weight_handler(vector_t *strvec) { int weight; vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files); if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No weight specified for track file %s - ignoring", tfile->fname); return; } if (tfile->weight != 1) { report_config_error(CONFIG_GENERAL_ERROR, "Weight already set for track file %s - ignoring %s", tfile->fname, FMT_STR_VSLOT(strvec, 1)); return; } if (!read_int_strvec(strvec, 1, &weight, -254, 254, true)) { report_config_error(CONFIG_GENERAL_ERROR, "Weight (%s) for vrrp_track_file %s must be between " "[-254..254] inclusive. Ignoring...", FMT_STR_VSLOT(strvec, 1), tfile->fname); weight = 1; } tfile->weight = weight; } static void vrrp_tfile_init_handler(vector_t *strvec) { unsigned i; char *word; vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files); int value; track_file_init = TRACK_FILE_CREATE; track_file_init_value = 0; for (i = 1; i < vector_size(strvec); i++) { word = strvec_slot(strvec, i); word += strspn(word, WHITE_SPACE); if (isdigit(word[0]) || word[0] == '-') { if (!read_int_strvec(strvec, i, &value, INT_MIN, INT_MAX, false)) { /* It is not a valid integer */ report_config_error(CONFIG_GENERAL_ERROR, "Track file %s init value %s is invalid", tfile->fname, word); value = 0; } else if (value < -254 || value > 254) report_config_error(CONFIG_GENERAL_ERROR, "Track file %s init value %d is outside sensible range [%d, %d]", tfile->fname, value, -254, 254); track_file_init_value = value; } else if (!strcmp(word, "overwrite")) track_file_init = TRACK_FILE_INIT; else report_config_error(CONFIG_GENERAL_ERROR, "Unknown track file init option %s", word); } } static void vrrp_tfile_end_handler(void) { vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files); struct stat statb; FILE *tf; int ret; if (!tfile->file_path) { report_config_error(CONFIG_GENERAL_ERROR, "No file set for track_file %s - removing", tfile->fname); free_list_element(vrrp_data->vrrp_track_files, vrrp_data->vrrp_track_files->tail); return; } if (track_file_init == TRACK_FILE_NO_INIT) return; ret = stat(tfile->file_path, &statb); if (!ret) { if (track_file_init == TRACK_FILE_CREATE) { /* The file exists */ return; } if ((statb.st_mode & S_IFMT) != S_IFREG) { /* It is not a regular file */ report_config_error(CONFIG_GENERAL_ERROR, "Cannot initialise track file %s - it is not a regular file", tfile->fname); return; } /* Don't overwrite a file on reload */ if (reload) return; } if (!__test_bit(CONFIG_TEST_BIT, &debug)) { /* Write the value to the file */ if ((tf = fopen_safe(tfile->file_path, "w"))) { fprintf(tf, "%d\n", track_file_init_value); fclose(tf); } else report_config_error(CONFIG_GENERAL_ERROR, "Unable to initialise track file %s", tfile->fname); } } static void vrrp_vscript_init_fail_handler(__attribute__((unused)) vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); vscript->init_state = SCRIPT_INIT_STATE_FAILED; } static void vrrp_version_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); int version; if (!read_int_strvec(strvec, 1, &version, 2, 3, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): Version must be either 2 or 3", vrrp->iname); return; } if ((vrrp->version && vrrp->version != version) || (version == VRRP_VERSION_2 && vrrp->family == AF_INET6)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) vrrp_version %d conflicts with configured or deduced version %d; ignoring.", vrrp->iname, version, vrrp->version); return; } vrrp->version = version; } static void vrrp_accept_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->accept = true; } static void vrrp_no_accept_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->accept = false; } static void garp_group_handler(vector_t *strvec) { if (!strvec) return; alloc_garp_delay(); } static void garp_group_garp_interval_handler(vector_t *strvec) { garp_delay_t *delay = LIST_TAIL_DATA(garp_delay); double val; if (!read_double_strvec(strvec, 1, &val, 0, INT_MAX / 1000000, true)) { report_config_error(CONFIG_GENERAL_ERROR, "garp_group garp_interval '%s' invalid", FMT_STR_VSLOT(strvec, 1)); return; } delay->garp_interval.tv_sec = (time_t)val; delay->garp_interval.tv_usec = (suseconds_t)((val - delay->garp_interval.tv_sec) * 1000000); delay->have_garp_interval = true; if (delay->garp_interval.tv_sec >= 1) log_message(LOG_INFO, "The garp_interval is very large - %s seconds", FMT_STR_VSLOT(strvec,1)); } static void garp_group_gna_interval_handler(vector_t *strvec) { garp_delay_t *delay = LIST_TAIL_DATA(garp_delay); double val; if (!read_double_strvec(strvec, 1, &val, 0, INT_MAX / 1000000, true)) { report_config_error(CONFIG_GENERAL_ERROR, "garp_group gna_interval '%s' invalid", FMT_STR_VSLOT(strvec, 1)); return; } delay->gna_interval.tv_sec = (time_t)val; delay->gna_interval.tv_usec = (suseconds_t)((val - delay->gna_interval.tv_sec) * 1000000); delay->have_gna_interval = true; if (delay->gna_interval.tv_sec >= 1) log_message(LOG_INFO, "The gna_interval is very large - %s seconds", FMT_STR_VSLOT(strvec,1)); } static void garp_group_interface_handler(vector_t *strvec) { interface_t *ifp = if_get_by_ifname(strvec_slot(strvec, 1), IF_CREATE_IF_DYNAMIC); if (!ifp) { report_config_error(CONFIG_GENERAL_ERROR, "WARNING - interface %s specified for garp_group doesn't exist", FMT_STR_VSLOT(strvec, 1)); return; } if (ifp->garp_delay) { report_config_error(CONFIG_GENERAL_ERROR, "garp_group already specified for %s - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } #ifdef _HAVE_VRRP_VMAC_ /* We cannot have a group on a vmac interface */ if (ifp->vmac_type) { report_config_error(CONFIG_GENERAL_ERROR, "Cannot specify garp_delay on a vmac (%s) - ignoring", ifp->ifname); return; } #endif ifp->garp_delay = LIST_TAIL_DATA(garp_delay); } static void garp_group_interfaces_handler(vector_t *strvec) { garp_delay_t *delay = LIST_TAIL_DATA(garp_delay); interface_t *ifp; vector_t *interface_vec = read_value_block(strvec); size_t i; garp_delay_t *gd; element e; /* Handle the interfaces block being empty */ if (!interface_vec) { report_config_error(CONFIG_GENERAL_ERROR, "Warning - empty garp_group interfaces block"); return; } /* First set the next aggregation group number */ delay->aggregation_group = 1; for (e = LIST_HEAD(garp_delay); e; ELEMENT_NEXT(e)) { gd = ELEMENT_DATA(e); if (gd->aggregation_group && gd != delay) delay->aggregation_group++; } for (i = 0; i < vector_size(interface_vec); i++) { ifp = if_get_by_ifname(vector_slot(interface_vec, i), IF_CREATE_IF_DYNAMIC); if (!ifp) { if (global_data->dynamic_interfaces) log_message(LOG_INFO, "WARNING - interface %s specified for garp_group doesn't exist", FMT_STR_VSLOT(strvec, i)); else report_config_error(CONFIG_GENERAL_ERROR, "WARNING - interface %s specified for garp_group doesn't exist", FMT_STR_VSLOT(strvec, i)); continue; } if (ifp->garp_delay) { report_config_error(CONFIG_GENERAL_ERROR, "garp_group already specified for %s - ignoring", FMT_STR_VSLOT(strvec, 1)); continue; } #ifdef _HAVE_VRRP_VMAC_ if (ifp->vmac_type) { report_config_error(CONFIG_GENERAL_ERROR, "Cannot specify garp_delay on a vmac (%s) - ignoring", ifp->ifname); continue; } #endif ifp->garp_delay = delay; } free_strvec(interface_vec); } static void garp_group_end_handler(void) { garp_delay_t *delay = LIST_TAIL_DATA(garp_delay); element e, next; interface_t *ifp; if (!delay->have_garp_interval && !delay->have_gna_interval) { report_config_error(CONFIG_GENERAL_ERROR, "garp group %d does not have any delay set - removing", delay->aggregation_group); /* Remove the garp_delay from any interfaces that are using it */ LIST_FOREACH_NEXT(get_if_list(), ifp, e, next) { if (ifp->garp_delay == delay) ifp->garp_delay = NULL; } free_list_element(garp_delay, garp_delay->tail); } } void init_vrrp_keywords(bool active) { /* Static addresses/routes/rules */ install_keyword_root("track_group", &static_track_group_handler, active); install_keyword("group", &static_track_group_group_handler); install_keyword_root("static_ipaddress", &static_addresses_handler, active); #ifdef _HAVE_FIB_ROUTING_ install_keyword_root("static_routes", &static_routes_handler, active); install_keyword_root("static_rules", &static_rules_handler, active); #endif /* Sync group declarations */ install_keyword_root("vrrp_sync_group", &vrrp_sync_group_handler, active); install_keyword("group", &vrrp_group_handler); install_keyword("track_interface", &vrrp_group_track_if_handler); install_keyword("track_script", &vrrp_group_track_scr_handler); install_keyword("track_file", &vrrp_group_track_file_handler); #ifdef _WITH_BFD_ install_keyword("track_bfd", &vrrp_group_track_bfd_handler); #endif install_keyword("notify_backup", &vrrp_gnotify_backup_handler); install_keyword("notify_master", &vrrp_gnotify_master_handler); install_keyword("notify_fault", &vrrp_gnotify_fault_handler); install_keyword("notify_stop", &vrrp_gnotify_stop_handler); install_keyword("notify", &vrrp_gnotify_handler); install_keyword("smtp_alert", &vrrp_gsmtp_handler); install_keyword("global_tracking", &vrrp_gglobal_tracking_handler); install_keyword("sync_group_tracking_weight", &vrrp_sg_tracking_weight_handler); install_keyword_root("garp_group", &garp_group_handler, active); install_keyword("garp_interval", &garp_group_garp_interval_handler); install_keyword("gna_interval", &garp_group_gna_interval_handler); install_keyword("interface", &garp_group_interface_handler); install_keyword("interfaces", &garp_group_interfaces_handler); install_sublevel_end_handler(&garp_group_end_handler); /* VRRP Instance mapping */ install_keyword_root("vrrp_instance", &vrrp_handler, active); #ifdef _HAVE_VRRP_VMAC_ install_keyword("use_vmac", &vrrp_vmac_handler); install_keyword("vmac_xmit_base", &vrrp_vmac_xmit_base_handler); #endif install_keyword("unicast_peer", &vrrp_unicast_peer_handler); #ifdef _WITH_UNICAST_CHKSUM_COMPAT_ install_keyword("old_unicast_checksum", &vrrp_unicast_chksum_handler); #endif install_keyword("native_ipv6", &vrrp_native_ipv6_handler); install_keyword("state", &vrrp_state_handler); install_keyword("interface", &vrrp_int_handler); install_keyword("dont_track_primary", &vrrp_dont_track_handler); install_keyword("track_interface", &vrrp_track_if_handler); install_keyword("track_script", &vrrp_track_scr_handler); install_keyword("track_file", &vrrp_track_file_handler); #ifdef _WITH_BFD_ install_keyword("track_bfd", &vrrp_track_bfd_handler); #endif install_keyword("mcast_src_ip", &vrrp_srcip_handler); install_keyword("unicast_src_ip", &vrrp_srcip_handler); install_keyword("track_src_ip", &vrrp_track_srcip_handler); install_keyword("virtual_router_id", &vrrp_vrid_handler); install_keyword("version", &vrrp_version_handler); install_keyword("priority", &vrrp_prio_handler); install_keyword("advert_int", &vrrp_adv_handler); install_keyword("virtual_ipaddress", &vrrp_vip_handler); install_keyword("virtual_ipaddress_excluded", &vrrp_evip_handler); install_keyword("promote_secondaries", &vrrp_promote_secondaries_handler); install_keyword("linkbeat_use_polling", &vrrp_linkbeat_handler); #ifdef _HAVE_FIB_ROUTING_ install_keyword("virtual_routes", &vrrp_vroutes_handler); install_keyword("virtual_rules", &vrrp_vrules_handler); #endif install_keyword("accept", &vrrp_accept_handler); install_keyword("no_accept", &vrrp_no_accept_handler); install_keyword("skip_check_adv_addr", &vrrp_skip_check_adv_addr_handler); install_keyword("strict_mode", &vrrp_strict_mode_handler); install_keyword("preempt", &vrrp_preempt_handler); install_keyword("nopreempt", &vrrp_nopreempt_handler); install_keyword("preempt_delay", &vrrp_preempt_delay_handler); install_keyword("debug", &vrrp_debug_handler); install_keyword("notify_backup", &vrrp_notify_backup_handler); install_keyword("notify_master", &vrrp_notify_master_handler); install_keyword("notify_fault", &vrrp_notify_fault_handler); install_keyword("notify_stop", &vrrp_notify_stop_handler); install_keyword("notify", &vrrp_notify_handler); install_keyword("notify_master_rx_lower_pri", vrrp_notify_master_rx_lower_pri); install_keyword("smtp_alert", &vrrp_smtp_handler); #ifdef _WITH_LVS_ install_keyword("lvs_sync_daemon_interface", &vrrp_lvs_syncd_handler); #endif install_keyword("garp_master_delay", &vrrp_garp_delay_handler); install_keyword("garp_master_refresh", &vrrp_garp_refresh_handler); install_keyword("garp_master_repeat", &vrrp_garp_rep_handler); install_keyword("garp_master_refresh_repeat", &vrrp_garp_refresh_rep_handler); install_keyword("garp_lower_prio_delay", &vrrp_garp_lower_prio_delay_handler); install_keyword("garp_lower_prio_repeat", &vrrp_garp_lower_prio_rep_handler); install_keyword("lower_prio_no_advert", &vrrp_lower_prio_no_advert_handler); install_keyword("higher_prio_send_advert", &vrrp_higher_prio_send_advert_handler); install_keyword("kernel_rx_buf_size", &kernel_rx_buf_size_handler); #if defined _WITH_VRRP_AUTH_ install_keyword("authentication", NULL); install_sublevel(); install_keyword("auth_type", &vrrp_auth_type_handler); install_keyword("auth_pass", &vrrp_auth_pass_handler); install_sublevel_end(); #endif install_keyword_root("vrrp_script", &vrrp_script_handler, active); install_keyword("script", &vrrp_vscript_script_handler); install_keyword("interval", &vrrp_vscript_interval_handler); install_keyword("timeout", &vrrp_vscript_timeout_handler); install_keyword("weight", &vrrp_vscript_weight_handler); install_keyword("rise", &vrrp_vscript_rise_handler); install_keyword("fall", &vrrp_vscript_fall_handler); install_keyword("user", &vrrp_vscript_user_handler); install_keyword("init_fail", &vrrp_vscript_init_fail_handler); install_sublevel_end_handler(&vrrp_vscript_end_handler); /* Track file declarations */ install_keyword_root("vrrp_track_file", &vrrp_tfile_handler, active); install_keyword("file", &vrrp_tfile_file_handler); install_keyword("weight", &vrrp_tfile_weight_handler); install_keyword("init_file", &vrrp_tfile_init_handler); install_sublevel_end_handler(&vrrp_tfile_end_handler); } vector_t * vrrp_init_keywords(void) { /* global definitions mapping */ init_global_keywords(reload); init_vrrp_keywords(true); #ifdef _WITH_LVS_ init_check_keywords(false); #endif #ifdef _WITH_BFD_ init_bfd_keywords(true); #endif return keywords; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_5
crossvul-cpp_data_good_436_8
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: logging facility. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <stdio.h> #include <stdbool.h> #include <time.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <memory.h> #include "logger.h" #include "bitops.h" #include "utils.h" /* Boolean flag - send messages to console as well as syslog */ static bool log_console = false; /* File to write log messages to */ char *log_file_name; static FILE *log_file; bool always_flush_log_file; void enable_console_log(void) { log_console = true; } void set_flush_log_file(void) { always_flush_log_file = true; } void close_log_file(void) { if (log_file) { fclose(log_file); log_file = NULL; } } void open_log_file(const char *name, const char *prog, const char *namespace, const char *instance) { char *file_name; if (log_file) { fclose(log_file); log_file = NULL; } if (!name) return; file_name = make_file_name(name, prog, namespace, instance); log_file = fopen_safe(file_name, "a"); if (log_file) { int n = fileno(log_file); fcntl(n, F_SETFD, FD_CLOEXEC | fcntl(n, F_GETFD)); fcntl(n, F_SETFL, O_NONBLOCK | fcntl(n, F_GETFL)); } FREE(file_name); } void flush_log_file(void) { if (log_file) fflush(log_file); } void vlog_message(const int facility, const char* format, va_list args) { #if !HAVE_VSYSLOG char buf[MAX_LOG_MSG+1]; vsnprintf(buf, sizeof(buf), format, args); #endif /* Don't write syslog if testing configuration */ if (__test_bit(CONFIG_TEST_BIT, &debug)) return; if (log_file || (__test_bit(DONT_FORK_BIT, &debug) && log_console)) { #if HAVE_VSYSLOG va_list args1; char buf[2 * MAX_LOG_MSG + 1]; va_copy(args1, args); vsnprintf(buf, sizeof(buf), format, args1); va_end(args1); #endif /* timestamp setup */ time_t t = time(NULL); struct tm tm; localtime_r(&t, &tm); char timestamp[64]; strftime(timestamp, sizeof(timestamp), "%c", &tm); if (log_console && __test_bit(DONT_FORK_BIT, &debug)) fprintf(stderr, "%s: %s\n", timestamp, buf); if (log_file) { fprintf(log_file, "%s: %s\n", timestamp, buf); if (always_flush_log_file) fflush(log_file); } } if (!__test_bit(NO_SYSLOG_BIT, &debug)) #if HAVE_VSYSLOG vsyslog(facility, format, args); #else syslog(facility, "%s", buf); #endif } void log_message(const int facility, const char *format, ...) { va_list args; va_start(args, format); vlog_message(facility, format, args); va_end(args); } void conf_write(FILE *fp, const char *format, ...) { va_list args; va_start(args, format); if (fp) { vfprintf(fp, format, args); fprintf(fp, "\n"); } else vlog_message(LOG_INFO, format, args); va_end(args); }
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_8
crossvul-cpp_data_good_436_7
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Sheduling framework for vrrp code. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <errno.h> #include <netinet/ip.h> #include <signal.h> #if defined _WITH_VRRP_AUTH_ #include <netinet/in.h> #endif #include <stdint.h> #include <stdio.h> #include "vrrp_scheduler.h" #include "vrrp_track.h" #ifdef _HAVE_VRRP_VMAC_ #include "vrrp_vmac.h" #endif #include "vrrp_sync.h" #include "vrrp_notify.h" #include "vrrp_data.h" #include "vrrp_arp.h" #include "vrrp_ndisc.h" #include "vrrp_if.h" #include "global_data.h" #include "memory.h" #include "list.h" #include "logger.h" #include "main.h" #include "signals.h" #include "utils.h" #include "bitops.h" #include "vrrp_sock.h" #ifdef _WITH_SNMP_RFCV3_ #include "vrrp_snmp.h" #endif #ifdef _WITH_BFD_ #include "bfd_event.h" #include "bfd_daemon.h" #endif #ifdef THREAD_DUMP #include "scheduler.h" #endif /* global vars */ timeval_t garp_next_time; thread_t *garp_thread; bool vrrp_initialised; #ifdef _TSM_DEBUG_ bool do_tsm_debug; #endif /* local variables */ #ifdef _WITH_BFD_ static thread_t *bfd_thread; /* BFD control pipe read thread */ #endif /* VRRP FSM (Finite State Machine) design. * * The state transition diagram implemented is : * * +---------------+ * +----------------| |----------------+ * | | Fault | | * | +------------>| |<------------+ | * | | +---------------+ | | * | | | | | * | | V | | * | | +---------------+ | | * | | +--------->| |<---------+ | | * | | | | Initialize | | | | * | | | +-------| |-------+ | | | * | | | | +---------------+ | | | | * | | | | | | | | * V | | V V | | V * +---------------+ +---------------+ * | |---------------------->| | * | Master | | Backup | * | |<----------------------| | * +---------------+ +---------------+ */ static int vrrp_script_child_thread(thread_t *); static int vrrp_script_thread(thread_t *); #ifdef _WITH_BFD_ static int vrrp_bfd_thread(thread_t *); #endif static int vrrp_read_dispatcher_thread(thread_t *); /* VRRP TSM (Transition State Matrix) design. * * Introducing the Synchronization extension to VRRP * protocol, introduce the need for a transition machinery. * This mechanism can be designed using a diagonal matrix. * We call this matrix the VRRP TSM: * * \ E | B | M | F | * S \ | | | | * ------+-----+-----+-----+ Legend: * B | x 1 2 | B: VRRP BACKUP state * ------+ | M: VRRP MASTER state * M | 3 x 4 | F: VRRP FAULT state * ------+ | S: VRRP start state (before transition) * F | 5 6 x | E: VRRP end state (after transition) * ------+-----------------+ [1..6]: Handler functions. * * So we have have to implement n(n-1) handlers in order to deal with * all transitions possible. This matrix defines the maximum handlers * to implement for having the most time optimized transition machine. * For example: * . The handler (1) will sync all the BACKUP VRRP instances of a * group to MASTER state => we will call it vrrp_sync_master. * .... and so on for all other state .... * * This matrix is the strict implementation way. For readability and * performance we have implemented some handlers directly into the VRRP * FSM or they are handled when the trigger events to/from FAULT state occur. * For instance the handlers (2), (4), (5) & (6) are handled when it is * detected that a script or an interface has failed or recovered since * it will speed up convergence to init state. * Additionaly, we have implemented some other handlers into the matrix * in order to speed up group synchronization takeover. For instance * transition: * o B->B: To catch wantstate MASTER transition to force sync group * to this transition state too. * o F->F: To speed up FAULT state transition if group is not already * synced to FAULT state. */ static struct { void (*handler) (vrrp_t *); } VRRP_TSM[VRRP_MAX_TSM_STATE + 1][VRRP_MAX_TSM_STATE + 1] = { /* From: To: > BACKUP MASTER FAULT */ /* v */ { {NULL}, {NULL}, {NULL}, {NULL} }, /* BACKUP */ { {NULL}, {NULL}, {vrrp_sync_master}, {NULL} }, /* MASTER */ { {NULL}, {vrrp_sync_backup}, {vrrp_sync_master}, {NULL} }, /* FAULT */ { {NULL}, {NULL}, {vrrp_sync_master}, {NULL} } }; /* * Initialize state handling * --rfc2338.6.4.1 */ static void vrrp_init_state(list l) { vrrp_t *vrrp; vrrp_sgroup_t *vgroup; element e; bool is_up; int new_state; /* We can send SMTP messages from this point, so set the time */ set_time_now(); /* Do notifications for any sync groups in fault state */ for (e = LIST_HEAD(vrrp_data->vrrp_sync_group); e; ELEMENT_NEXT(e)) { /* Init group if needed */ vgroup = ELEMENT_DATA(e); if (vgroup->state == VRRP_STATE_FAULT) send_group_notifies(vgroup); } for (e = LIST_HEAD(l); e; ELEMENT_NEXT(e)) { vrrp = ELEMENT_DATA(e); /* wantstate is the state we would be in disregarding any sync group */ if (vrrp->state == VRRP_STATE_FAULT) vrrp->wantstate = VRRP_STATE_FAULT; new_state = vrrp->sync ? vrrp->sync->state : vrrp->wantstate; is_up = VRRP_ISUP(vrrp); if (is_up && new_state == VRRP_STATE_MAST && !vrrp->num_script_init && (!vrrp->sync || !vrrp->sync->num_member_init) && (vrrp->base_priority == VRRP_PRIO_OWNER || vrrp->reload_master) && vrrp->wantstate == VRRP_STATE_MAST) { #ifdef _WITH_LVS_ /* Check if sync daemon handling is needed */ if (global_data->lvs_syncd.ifname && global_data->lvs_syncd.vrrp == vrrp) ipvs_syncd_cmd(IPVS_STARTDAEMON, &global_data->lvs_syncd, vrrp->state == VRRP_STATE_MAST ? IPVS_MASTER : IPVS_BACKUP, false, false); #endif if (!vrrp->reload_master) { #ifdef _WITH_SNMP_RFCV3_ vrrp->stats->next_master_reason = VRRPV3_MASTER_REASON_PREEMPTED; #endif /* The simplest way to become master is to timeout from the backup state * very quickly (1usec) */ vrrp->state = VRRP_STATE_BACK; vrrp->ms_down_timer = 1; } // TODO Do we need -> vrrp_restore_interface(vrrp, false, false); // It removes everything, so probably if !reload } else { if (new_state == VRRP_STATE_BACK && vrrp->wantstate == VRRP_STATE_MAST) vrrp->ms_down_timer = vrrp->master_adver_int + VRRP_TIMER_SKEW_MIN(vrrp); else vrrp->ms_down_timer = 3 * vrrp->master_adver_int + VRRP_TIMER_SKEW(vrrp); #ifdef _WITH_SNMP_RFCV3_ vrrp->stats->next_master_reason = VRRPV3_MASTER_REASON_MASTER_NO_RESPONSE; #endif #ifdef _WITH_LVS_ /* Check if sync daemon handling is needed */ if (global_data->lvs_syncd.ifname && global_data->lvs_syncd.vrrp == vrrp) ipvs_syncd_cmd(IPVS_STARTDAEMON, &global_data->lvs_syncd, IPVS_BACKUP, false, false); #endif /* Set interface state */ vrrp_restore_interface(vrrp, false, false); if (is_up && new_state != VRRP_STATE_FAULT && !vrrp->num_script_init && (!vrrp->sync || !vrrp->sync->num_member_init)) { if (is_up) { vrrp->state = VRRP_STATE_BACK; log_message(LOG_INFO, "(%s) Entering BACKUP STATE (init)", vrrp->iname); } else { vrrp->state = VRRP_STATE_FAULT; log_message(LOG_INFO, "(%s) Entering FAULT STATE (init)", vrrp->iname); } send_instance_notifies(vrrp); } vrrp->last_transition = timer_now(); } #ifdef _WITH_SNMP_RFC_ vrrp->stats->uptime = timer_now(); #endif } } /* Declare vrrp_timer_cmp() rbtree compare function */ RB_TIMER_CMP(vrrp); /* Compute the new instance sands */ void vrrp_init_instance_sands(vrrp_t * vrrp) { set_time_now(); if (vrrp->state == VRRP_STATE_MAST) { if (vrrp->reload_master) vrrp->sands = time_now; else vrrp->sands = timer_add_long(time_now, vrrp->adver_int); } else if (vrrp->state == VRRP_STATE_BACK) { /* * When in the BACKUP state the expiry timer should be updated to * time_now plus the Master Down Timer, when a non-preemptable packet is * received. */ vrrp->sands = timer_add_long(time_now, vrrp->ms_down_timer); } else if (vrrp->state == VRRP_STATE_FAULT || vrrp->state == VRRP_STATE_INIT) vrrp->sands.tv_sec = TIMER_DISABLED; rb_move_cached(&vrrp->sockets->rb_sands, vrrp, rb_sands, vrrp_timer_cmp); } static void vrrp_init_sands(list l) { vrrp_t *vrrp; element e; LIST_FOREACH(l, vrrp, e) { vrrp->sands.tv_sec = TIMER_DISABLED; rb_insert_sort_cached(&vrrp->sockets->rb_sands, vrrp, rb_sands, vrrp_timer_cmp); vrrp_init_instance_sands(vrrp); vrrp->reload_master = false; } } static void vrrp_init_script(list l) { vrrp_script_t *vscript; element e; LIST_FOREACH(l, vscript, e) { if (vscript->init_state == SCRIPT_INIT_STATE_INIT) vscript->result = vscript->rise - 1; /* one success is enough */ else if (vscript->init_state == SCRIPT_INIT_STATE_FAILED) vscript->result = 0; /* assume failed by config */ thread_add_event(master, vrrp_script_thread, vscript, (int)vscript->interval); } } /* Timer functions */ static timeval_t * vrrp_compute_timer(const sock_t *sock) { vrrp_t *vrrp; static timeval_t timer = { .tv_sec = TIMER_DISABLED }; /* The sock won't exist if there isn't a vrrp instance on it, * so rb_first will always exist. */ vrrp = rb_entry(rb_first_cached(&sock->rb_sands), vrrp_t, rb_sands); if (vrrp) return &vrrp->sands; return &timer; } void vrrp_thread_requeue_read(vrrp_t *vrrp) { thread_requeue_read(master, vrrp->sockets->fd_in, vrrp_compute_timer(vrrp->sockets)); } /* Thread functions */ static void vrrp_register_workers(list l) { sock_t *sock; timeval_t timer; element e; /* Init compute timer */ memset(&timer, 0, sizeof(timer)); /* Init the VRRP instances state */ vrrp_init_state(vrrp_data->vrrp); /* Init VRRP instances sands */ vrrp_init_sands(vrrp_data->vrrp); /* Init VRRP tracking scripts */ if (!LIST_ISEMPTY(vrrp_data->vrrp_script)) vrrp_init_script(vrrp_data->vrrp_script); #ifdef _WITH_BFD_ if (!LIST_ISEMPTY(vrrp_data->vrrp)) { // TODO - should we only do this if we have track_bfd? Probably not /* Init BFD tracking thread */ bfd_thread = thread_add_read(master, vrrp_bfd_thread, NULL, bfd_vrrp_event_pipe[0], TIMER_NEVER); } #endif /* Register VRRP workers threads */ LIST_FOREACH(l, sock, e) { /* Register a timer thread if interface exists */ if (sock->fd_in != -1) sock->thread = thread_add_read_sands(master, vrrp_read_dispatcher_thread, sock, sock->fd_in, vrrp_compute_timer(sock)); } } void vrrp_thread_add_read(vrrp_t *vrrp) { vrrp->sockets->thread = thread_add_read_sands(master, vrrp_read_dispatcher_thread, vrrp->sockets, vrrp->sockets->fd_in, vrrp_compute_timer(vrrp->sockets)); } /* VRRP dispatcher functions */ static sock_t * already_exist_sock(list l, sa_family_t family, int proto, ifindex_t ifindex, bool unicast) { sock_t *sock; element e; LIST_FOREACH(l, sock, e) { if ((sock->family == family) && (sock->proto == proto) && (sock->ifindex == ifindex) && (sock->unicast == unicast)) return sock; } return NULL; } static sock_t * alloc_sock(sa_family_t family, list l, int proto, ifindex_t ifindex, bool unicast) { sock_t *new; new = (sock_t *)MALLOC(sizeof (sock_t)); new->family = family; new->proto = proto; new->ifindex = ifindex; new->unicast = unicast; new->rb_vrid = RB_ROOT; new->rb_sands = RB_ROOT_CACHED; list_add(l, new); return new; } static inline int vrrp_vrid_cmp(const vrrp_t *v1, const vrrp_t *v2) { return v1->vrid - v2->vrid; } static void vrrp_create_sockpool(list l) { vrrp_t *vrrp; element e; ifindex_t ifindex; int proto; bool unicast; sock_t *sock; LIST_FOREACH(vrrp_data->vrrp, vrrp, e) { ifindex = #ifdef _HAVE_VRRP_VMAC_ (__test_bit(VRRP_VMAC_XMITBASE_BIT, &vrrp->vmac_flags)) ? IF_BASE_INDEX(vrrp->ifp) : #endif IF_INDEX(vrrp->ifp); unicast = !LIST_ISEMPTY(vrrp->unicast_peer); #if defined _WITH_VRRP_AUTH_ if (vrrp->auth_type == VRRP_AUTH_AH) proto = IPPROTO_AH; else #endif proto = IPPROTO_VRRP; /* add the vrrp element if not exist */ if (!(sock = already_exist_sock(l, vrrp->family, proto, ifindex, unicast))) sock = alloc_sock(vrrp->family, l, proto, ifindex, unicast); /* Add the vrrp_t indexed by vrid to the socket */ rb_insert_sort(&sock->rb_vrid, vrrp, rb_vrid, vrrp_vrid_cmp); if (vrrp->kernel_rx_buf_size) sock->rx_buf_size += vrrp->kernel_rx_buf_size; else if (global_data->vrrp_rx_bufs_policy & RX_BUFS_SIZE) sock->rx_buf_size += global_data->vrrp_rx_bufs_size; else if (global_data->vrrp_rx_bufs_policy & RX_BUFS_POLICY_ADVERT) sock->rx_buf_size += global_data->vrrp_rx_bufs_multiples * vrrp_adv_len(vrrp); else if (global_data->vrrp_rx_bufs_policy & RX_BUFS_POLICY_MTU) sock->rx_buf_size += global_data->vrrp_rx_bufs_multiples * vrrp->ifp->mtu; } } static void vrrp_open_sockpool(list l) { sock_t *sock; element e; interface_t *ifp; LIST_FOREACH(l, sock, e) { if (!sock->ifindex) { sock->fd_in = sock->fd_out = -1; continue; } ifp = if_get_by_ifindex(sock->ifindex); sock->fd_in = open_vrrp_read_socket(sock->family, sock->proto, ifp, sock->unicast, sock->rx_buf_size); if (sock->fd_in == -1) sock->fd_out = -1; else sock->fd_out = open_vrrp_send_socket(sock->family, sock->proto, ifp, sock->unicast); } } static void vrrp_set_fds(list l) { sock_t *sock; vrrp_t *vrrp; element e; LIST_FOREACH(l, sock, e) { rb_for_each_entry(vrrp, &sock->rb_vrid, rb_vrid) vrrp->sockets = sock; } } /* * We create & allocate a socket pool here. The soft design * can be sum up by the following sketch : * * fd1 fd2 fd3 fd4 fdi fdi+1 * -----\__/--------\__/---........---\__/--- * | ETH0 | | ETH1 | | ETHn | * +------+ +------+ +------+ * * TODO TODO - this description is way out of date * Here we have n physical NIC. Each NIC own a maximum of 2 fds. * (one for VRRP the other for IPSEC_AH). All our VRRP instances * are multiplexed through this fds. So our design can handle 2*n * multiplexing points. */ int vrrp_dispatcher_init(__attribute__((unused)) thread_t * thread) { vrrp_create_sockpool(vrrp_data->vrrp_socket_pool); /* open the VRRP socket pool */ vrrp_open_sockpool(vrrp_data->vrrp_socket_pool); /* set VRRP instance fds to sockpool */ vrrp_set_fds(vrrp_data->vrrp_socket_pool); /* create the VRRP socket pool list */ /* register read dispatcher worker thread */ vrrp_register_workers(vrrp_data->vrrp_socket_pool); /* Dump socket pool */ if (__test_bit(LOG_DETAIL_BIT, &debug)) dump_list(NULL, vrrp_data->vrrp_socket_pool); vrrp_initialised = true; return 1; } void vrrp_dispatcher_release(vrrp_data_t *data) { free_list(&data->vrrp_socket_pool); #ifdef _WITH_BFD_ thread_cancel(bfd_thread); bfd_thread = NULL; #endif } static void vrrp_goto_master(vrrp_t * vrrp) { /* handle master state transition */ vrrp->wantstate = VRRP_STATE_MAST; vrrp_state_goto_master(vrrp); } /* Delayed gratuitous ARP thread */ int vrrp_gratuitous_arp_thread(thread_t * thread) { vrrp_t *vrrp = THREAD_ARG(thread); /* Simply broadcast the gratuitous ARP */ vrrp_send_link_update(vrrp, vrrp->garp_rep); return 0; } /* Delayed gratuitous ARP thread after receiving a lower priority advert */ int vrrp_lower_prio_gratuitous_arp_thread(thread_t * thread) { vrrp_t *vrrp = THREAD_ARG(thread); /* Simply broadcast the gratuitous ARP */ vrrp_send_link_update(vrrp, vrrp->garp_lower_prio_rep); return 0; } static void vrrp_master(vrrp_t * vrrp) { /* Send the VRRP advert */ vrrp_state_master_tx(vrrp); } void try_up_instance(vrrp_t *vrrp, bool leaving_init) { int wantstate; if (leaving_init) { if (vrrp->num_script_if_fault) return; } else if (--vrrp->num_script_if_fault || vrrp->num_script_init) return; if (vrrp->wantstate == VRRP_STATE_MAST && vrrp->base_priority == VRRP_PRIO_OWNER) { vrrp->wantstate = VRRP_STATE_MAST; #ifdef _WITH_SNMP_RFCV3_ vrrp->stats->next_master_reason = VRRPV3_MASTER_REASON_PREEMPTED; #endif } else { vrrp->wantstate = VRRP_STATE_BACK; #ifdef _WITH_SNMP_RFCV3_ vrrp->stats->next_master_reason = VRRPV3_MASTER_REASON_MASTER_NO_RESPONSE; #endif } vrrp->master_adver_int = vrrp->adver_int; if (vrrp->wantstate == VRRP_STATE_MAST && vrrp->base_priority == VRRP_PRIO_OWNER) vrrp->ms_down_timer = vrrp->master_adver_int + VRRP_TIMER_SKEW(vrrp); else vrrp->ms_down_timer = 3 * vrrp->master_adver_int + VRRP_TIMER_SKEW(vrrp); if (vrrp->sync) { if (leaving_init) { if (vrrp->sync->num_member_fault) return; } else if (--vrrp->sync->num_member_fault || vrrp->sync->num_member_init) return; } /* If the sync group can't go to master, we must go to backup state */ wantstate = vrrp->wantstate; if (vrrp->sync && vrrp->wantstate == VRRP_STATE_MAST && !vrrp_sync_can_goto_master(vrrp)) vrrp->wantstate = VRRP_STATE_BACK; /* We can come up */ vrrp_state_leave_fault(vrrp); vrrp_init_instance_sands(vrrp); vrrp_thread_requeue_read(vrrp); vrrp->wantstate = wantstate; if (vrrp->sync) { if (vrrp->state == VRRP_STATE_MAST) vrrp_sync_master(vrrp); else vrrp_sync_backup(vrrp); } } #ifdef _WITH_BFD_ static void vrrp_handle_bfd_event(bfd_event_t * evt) { vrrp_tracked_bfd_t *vbfd; tracking_vrrp_t *tbfd; vrrp_t * vrrp; element e, e1; struct timeval time_now; struct timeval timer_tmp; uint32_t delivery_time; if (__test_bit(LOG_DETAIL_BIT, &debug)) { time_now = timer_now(); timersub(&time_now, &evt->sent_time, &timer_tmp); delivery_time = timer_long(timer_tmp); log_message(LOG_INFO, "Received BFD event: instance %s is in" " state %s (delivered in %i usec)", evt->iname, BFD_STATE_STR(evt->state), delivery_time); } LIST_FOREACH(vrrp_data->vrrp_track_bfds, vbfd, e) { if (strcmp(vbfd->bname, evt->iname)) continue; if ((vbfd->bfd_up && evt->state == BFD_STATE_UP) || (!vbfd->bfd_up && evt->state == BFD_STATE_DOWN)) continue; vbfd->bfd_up = (evt->state == BFD_STATE_UP); LIST_FOREACH(vbfd->tracking_vrrp, tbfd, e1) { vrrp = tbfd->vrrp; log_message(LOG_INFO, "VRRP_Instance(%s) Tracked BFD" " instance %s is %s", vrrp->iname, evt->iname, vbfd->bfd_up ? "UP" : "DOWN"); if (tbfd->weight) { if (vbfd->bfd_up) vrrp->total_priority += abs(tbfd->weight); else vrrp->total_priority -= abs(tbfd->weight); vrrp_set_effective_priority(vrrp); continue; } if (vbfd->bfd_up) try_up_instance(vrrp, false); else down_instance(vrrp); } break; } } static int vrrp_bfd_thread(thread_t * thread) { bfd_event_t evt; bfd_thread = thread_add_read(master, vrrp_bfd_thread, NULL, thread->u.fd, TIMER_NEVER); if (thread->type != THREAD_READY_FD) return 0; while (read(thread->u.fd, &evt, sizeof(bfd_event_t)) != -1) vrrp_handle_bfd_event(&evt); return 0; } #endif /* Handle dispatcher read timeout */ static int vrrp_dispatcher_read_timeout(sock_t *sock) { vrrp_t *vrrp; int prev_state; set_time_now(); rb_for_each_entry_cached(vrrp, &sock->rb_sands, rb_sands) { if (vrrp->sands.tv_sec == TIMER_DISABLED || timercmp(&vrrp->sands, &time_now, >)) break; prev_state = vrrp->state; if (vrrp->state == VRRP_STATE_BACK) { if (__test_bit(LOG_DETAIL_BIT, &debug)) log_message(LOG_INFO, "(%s) Receive advertisement timeout", vrrp->iname); vrrp_goto_master(vrrp); } else if (vrrp->state == VRRP_STATE_MAST) vrrp_master(vrrp); /* handle instance synchronization */ #ifdef _TSM_DEBUG_ if (do_tsm_debug) log_message(LOG_INFO, "Send [%s] TSM transition : [%d,%d] Wantstate = [%d]", vrrp->iname, prev_state, vrrp->state, vrrp->wantstate); #endif VRRP_TSM_HANDLE(prev_state, vrrp); vrrp_init_instance_sands(vrrp); } return sock->fd_in; } /* Handle dispatcher read packet */ static int vrrp_dispatcher_read(sock_t * sock) { vrrp_t *vrrp; vrrphdr_t *hd; ssize_t len = 0; int prev_state = 0; unsigned proto = 0; struct sockaddr_storage src_addr; socklen_t src_addr_len = sizeof(src_addr); vrrp_t vrrp_lookup; /* Clean the read buffer */ memset(vrrp_buffer, 0, vrrp_buffer_len); /* read & affect received buffer */ len = recvfrom(sock->fd_in, vrrp_buffer, vrrp_buffer_len, 0, (struct sockaddr *) &src_addr, &src_addr_len); hd = vrrp_get_header(sock->family, vrrp_buffer, &proto); vrrp_lookup.vrid = hd->vrid; vrrp = rb_search(&sock->rb_vrid, &vrrp_lookup, rb_vrid, vrrp_vrid_cmp); /* If no instance found => ignore the advert */ if (!vrrp) return sock->fd_in; if (vrrp->state == VRRP_STATE_FAULT || vrrp->state == VRRP_STATE_INIT) { /* We just ignore a message received when we are in fault state or * not yet fully initialised */ return sock->fd_in; } vrrp->pkt_saddr = src_addr; prev_state = vrrp->state; if (vrrp->state == VRRP_STATE_BACK) vrrp_state_backup(vrrp, vrrp_buffer, len); else if (vrrp->state == VRRP_STATE_MAST) { if (vrrp_state_master_rx(vrrp, vrrp_buffer, len)) vrrp_state_leave_master(vrrp, false); } else log_message(LOG_INFO, "(%s) In dispatcher_read with state %d", vrrp->iname, vrrp->state); /* handle instance synchronization */ #ifdef _TSM_DEBUG_ if (do_tsm_debug) log_message(LOG_INFO, "Read [%s] TSM transition : [%d,%d] Wantstate = [%d]", vrrp->iname, prev_state, vrrp->state, vrrp->wantstate); #endif VRRP_TSM_HANDLE(prev_state, vrrp); /* If we have sent an advert, reset the timer */ if (vrrp->state != VRRP_STATE_MAST || !vrrp->lower_prio_no_advert) vrrp_init_instance_sands(vrrp); return sock->fd_in; } /* Our read packet dispatcher */ static int vrrp_read_dispatcher_thread(thread_t * thread) { sock_t *sock; int fd; /* Fetch thread arg */ sock = THREAD_ARG(thread); /* Dispatcher state handler */ if (thread->type == THREAD_READ_TIMEOUT || sock->fd_in == -1) fd = vrrp_dispatcher_read_timeout(sock); else fd = vrrp_dispatcher_read(sock); /* register next dispatcher thread */ if (fd != -1) sock->thread = thread_add_read_sands(thread->master, vrrp_read_dispatcher_thread, sock, fd, vrrp_compute_timer(sock)); return 0; } static int vrrp_script_thread(thread_t * thread) { vrrp_script_t *vscript = THREAD_ARG(thread); int ret; /* Register next timer tracker */ thread_add_timer(thread->master, vrrp_script_thread, vscript, vscript->interval); if (vscript->state != SCRIPT_STATE_IDLE) { /* We don't want the system to be overloaded with scripts that we are executing */ log_message(LOG_INFO, "Track script %s is %s, expect idle - skipping run", vscript->sname, vscript->state == SCRIPT_STATE_RUNNING ? "already running" : "being timed out"); return 0; } /* Execute the script in a child process. Parent returns, child doesn't */ ret = system_call_script(thread->master, vrrp_script_child_thread, vscript, (vscript->timeout) ? vscript->timeout : vscript->interval, &vscript->script); if (!ret) vscript->state = SCRIPT_STATE_RUNNING; return ret; } static int vrrp_script_child_thread(thread_t * thread) { int wait_status; pid_t pid; vrrp_script_t *vscript = THREAD_ARG(thread); int sig_num; unsigned timeout = 0; char *script_exit_type = NULL; bool script_success; char *reason = NULL; int reason_code; if (thread->type == THREAD_CHILD_TIMEOUT) { pid = THREAD_CHILD_PID(thread); if (vscript->state == SCRIPT_STATE_RUNNING) { vscript->state = SCRIPT_STATE_REQUESTING_TERMINATION; sig_num = SIGTERM; timeout = 2; } else if (vscript->state == SCRIPT_STATE_REQUESTING_TERMINATION) { vscript->state = SCRIPT_STATE_FORCING_TERMINATION; sig_num = SIGKILL; timeout = 2; } else if (vscript->state == SCRIPT_STATE_FORCING_TERMINATION) { log_message(LOG_INFO, "Child (PID %d) failed to terminate after kill", pid); sig_num = SIGKILL; timeout = 10; /* Give it longer to terminate */ } /* Kill it off. */ if (timeout) { /* If kill returns an error, we can't kill the process since either the process has terminated, * or we don't have permission. If we can't kill it, there is no point trying again. */ if (kill(-pid, sig_num)) { if (errno == ESRCH) { /* The process does not exist; presumably it * has just terminated. We should get * notification of it's termination, so allow * that to handle it. */ timeout = 1; } else { log_message(LOG_INFO, "kill -%d of process %s(%d) with new state %d failed with errno %d", sig_num, vscript->script.args[0], pid, vscript->state, errno); timeout = 1000; } } } else if (vscript->state != SCRIPT_STATE_IDLE) { log_message(LOG_INFO, "Child thread pid %d timeout with unknown script state %d", pid, vscript->state); timeout = 10; /* We need some timeout */ } if (timeout) thread_add_child(thread->master, vrrp_script_child_thread, vscript, pid, timeout * TIMER_HZ); return 0; } wait_status = THREAD_CHILD_STATUS(thread); if (WIFEXITED(wait_status)) { int status = WEXITSTATUS(wait_status); /* Report if status has changed */ if (status != vscript->last_status) log_message(LOG_INFO, "Script `%s` now returning %d", vscript->sname, status); if (status == 0) { /* success */ script_exit_type = "succeeded"; script_success = true; } else { /* failure */ script_exit_type = "failed"; script_success = false; reason = "exited with status"; reason_code = status; } vscript->last_status = status; } else if (WIFSIGNALED(wait_status)) { if (vscript->state == SCRIPT_STATE_REQUESTING_TERMINATION && WTERMSIG(wait_status) == SIGTERM) { /* The script terminated due to a SIGTERM, and we sent it a SIGTERM to * terminate the process. Now make sure any children it created have * died too. */ pid = THREAD_CHILD_PID(thread); kill(-pid, SIGKILL); } /* We treat forced termination as a failure */ if ((vscript->state == SCRIPT_STATE_REQUESTING_TERMINATION && WTERMSIG(wait_status) == SIGTERM) || (vscript->state == SCRIPT_STATE_FORCING_TERMINATION && (WTERMSIG(wait_status) == SIGKILL || WTERMSIG(wait_status) == SIGTERM))) script_exit_type = "timed_out"; else { script_exit_type = "failed"; reason = "due to signal"; reason_code = WTERMSIG(wait_status); } script_success = false; } if (script_exit_type) { if (script_success) { if (vscript->result < vscript->rise - 1) { vscript->result++; } else if (vscript->result != vscript->rise + vscript->fall - 1) { if (vscript->result < vscript->rise) { /* i.e. == vscript->rise - 1 */ log_message(LOG_INFO, "VRRP_Script(%s) %s", vscript->sname, script_exit_type); update_script_priorities(vscript, true); } vscript->result = vscript->rise + vscript->fall - 1; } } else { if (vscript->result > vscript->rise) { vscript->result--; } else { if (vscript->result == vscript->rise || vscript->init_state == SCRIPT_INIT_STATE_INIT) { if (reason) log_message(LOG_INFO, "VRRP_Script(%s) %s (%s %d)", vscript->sname, script_exit_type, reason, reason_code); else log_message(LOG_INFO, "VRRP_Script(%s) %s", vscript->sname, script_exit_type); update_script_priorities(vscript, false); } vscript->result = 0; } } } vscript->state = SCRIPT_STATE_IDLE; vscript->init_state = SCRIPT_INIT_STATE_DONE; return 0; } /* Delayed ARP/NA thread */ int vrrp_arp_thread(thread_t *thread) { element e, a; list l; ip_address_t *ipaddress; timeval_t next_time = { .tv_sec = INT_MAX /* We're never going to delay this long - I hope! */ }; interface_t *ifp; vrrp_t *vrrp; enum { VIP, EVIP } i; set_time_now(); for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { vrrp = ELEMENT_DATA(e); if (!vrrp->garp_pending && !vrrp->gna_pending) continue; vrrp->garp_pending = false; vrrp->gna_pending = false; if (vrrp->state != VRRP_STATE_MAST || !vrrp->vipset) continue; for (i = VIP; i <= EVIP; i++) { l = (i == VIP) ? vrrp->vip : vrrp->evip; if (!LIST_ISEMPTY(l)) { for (a = LIST_HEAD(l); a; ELEMENT_NEXT(a)) { ipaddress = ELEMENT_DATA(a); if (!ipaddress->garp_gna_pending) continue; if (!ipaddress->set) { ipaddress->garp_gna_pending = false; continue; } ifp = IF_BASE_IFP(ipaddress->ifp); /* This should never happen */ if (!ifp->garp_delay) { ipaddress->garp_gna_pending = false; continue; } if (!IP_IS6(ipaddress)) { if (timercmp(&time_now, &ifp->garp_delay->garp_next_time, >=)) { send_gratuitous_arp_immediate(ifp, ipaddress); ipaddress->garp_gna_pending = false; } else { vrrp->garp_pending = true; if (timercmp(&ifp->garp_delay->garp_next_time, &next_time, <)) next_time = ifp->garp_delay->garp_next_time; } } else { if (timercmp(&time_now, &ifp->garp_delay->gna_next_time, >=)) { ndisc_send_unsolicited_na_immediate(ifp, ipaddress); ipaddress->garp_gna_pending = false; } else { vrrp->gna_pending = true; if (timercmp(&ifp->garp_delay->gna_next_time, &next_time, <)) next_time = ifp->garp_delay->gna_next_time; } } } } } } if (next_time.tv_sec != INT_MAX) { /* Register next timer tracker */ garp_next_time = next_time; garp_thread = thread_add_timer(thread->master, vrrp_arp_thread, NULL, timer_long(timer_sub_now(next_time))); } else garp_thread = NULL; return 0; } #ifdef _WITH_DUMP_THREADS_ void dump_threads(void) { FILE *fp; char time_buf[26]; element e; vrrp_t *vrrp; char *file_name; file_name = make_file_name("/tmp/thread_dump.dat", "vrrp", #if HAVE_DECL_CLONE_NEWNET global_data->network_namespace, #else NULL, #endif global_data->instance_name); fp = fopen_safe(file_name, "a"); FREE(file_name); set_time_now(); ctime_r(&time_now.tv_sec, time_buf); fprintf(fp, "\n%.19s.%6.6ld: Thread dump\n", time_buf, time_now.tv_usec); dump_thread_data(master, fp); fprintf(fp, "alloc = %lu\n", master->alloc); fprintf(fp, "\n"); LIST_FOREACH(vrrp_data->vrrp, vrrp, e) { ctime_r(&vrrp->sands.tv_sec, time_buf); fprintf(fp, "VRRP instance %s, sands %.19s.%6.6lu, status %s\n", vrrp->iname, time_buf, vrrp->sands.tv_usec, vrrp->state == VRRP_STATE_INIT ? "INIT" : vrrp->state == VRRP_STATE_BACK ? "BACKUP" : vrrp->state == VRRP_STATE_MAST ? "MASTER" : vrrp->state == VRRP_STATE_FAULT ? "FAULT" : vrrp->state == VRRP_STATE_STOP ? "STOP" : vrrp->state == VRRP_DISPATCHER ? "DISPATCHER" : "unknown"); } fclose(fp); } #endif #ifdef THREAD_DUMP void register_vrrp_scheduler_addresses(void) { register_thread_address("vrrp_arp_thread", vrrp_arp_thread); register_thread_address("vrrp_dispatcher_init", vrrp_dispatcher_init); register_thread_address("vrrp_gratuitous_arp_thread", vrrp_gratuitous_arp_thread); register_thread_address("vrrp_lower_prio_gratuitous_arp_thread", vrrp_lower_prio_gratuitous_arp_thread); register_thread_address("vrrp_script_child_thread", vrrp_script_child_thread); register_thread_address("vrrp_script_thread", vrrp_script_thread); register_thread_address("vrrp_read_dispatcher_thread", vrrp_read_dispatcher_thread); #ifdef _WITH_BFD_ register_thread_address("vrrp_bfd_thread", vrrp_bfd_thread); #endif } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_7
crossvul-cpp_data_good_3262_0
/* * ProFTPD - FTP server daemon * Copyright (c) 1997, 1998 Public Flood Software * Copyright (c) 1999, 2000 MacGyver aka Habeeb J. Dihu <macgyver@tos.net> * Copyright (c) 2001-2017 The ProFTPD Project team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. * * As a special exemption, Public Flood Software/MacGyver aka Habeeb J. Dihu * and other respective copyright holders give permission to link this program * with OpenSSL, and distribute the resulting executable, without including * the source code for OpenSSL in the source distribution. */ /* Authentication module for ProFTPD */ #include "conf.h" #include "privs.h" extern pid_t mpid; module auth_module; #ifdef PR_USE_LASTLOG static unsigned char lastlog = FALSE; #endif /* PR_USE_LASTLOG */ static unsigned char mkhome = FALSE; static unsigned char authenticated_without_pass = FALSE; static int TimeoutLogin = PR_TUNABLE_TIMEOUTLOGIN; static int logged_in = 0; static int auth_tries = 0; static char *auth_pass_resp_code = R_230; static pr_fh_t *displaylogin_fh = NULL; static int TimeoutSession = 0; static int auth_scan_scoreboard(void); static int auth_count_scoreboard(cmd_rec *, char *); /* auth_cmd_chk_cb() is hooked into the main server's auth_hook function, * so that we can deny all commands until authentication is complete. * * Note: Once this function returns true (i.e. client has authenticated), * it will ALWAYS return true. At least until REIN is implemented. Thus * we have a flag for such a situation, to save on redundant lookups for * the "authenticated" record. */ static int auth_have_authenticated = FALSE; static int auth_cmd_chk_cb(cmd_rec *cmd) { if (auth_have_authenticated == FALSE) { unsigned char *authd; authd = get_param_ptr(cmd->server->conf, "authenticated", FALSE); if (authd == NULL || *authd == FALSE) { pr_response_send(R_530, _("Please login with USER and PASS")); return FALSE; } auth_have_authenticated = TRUE; } return TRUE; } static int auth_login_timeout_cb(CALLBACK_FRAME) { pr_response_send_async(R_421, _("Login timeout (%d %s): closing control connection"), TimeoutLogin, TimeoutLogin != 1 ? "seconds" : "second"); /* It's possible that any listeners of this event might terminate the * session process themselves (e.g. mod_ban). So write out that the * TimeoutLogin has been exceeded to the log here, in addition to the * scheduled session exit message. */ pr_log_pri(PR_LOG_NOTICE, "%s", "Login timeout exceeded, disconnected"); pr_event_generate("core.timeout-login", NULL); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT, "TimeoutLogin"); /* Do not restart the timer (should never be reached). */ return 0; } static int auth_session_timeout_cb(CALLBACK_FRAME) { pr_event_generate("core.timeout-session", NULL); pr_response_send_async(R_421, _("Session Timeout (%d seconds): closing control connection"), TimeoutSession); pr_log_pri(PR_LOG_NOTICE, "%s", "FTP session timed out, disconnected"); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT, "TimeoutSession"); /* no need to restart the timer -- session's over */ return 0; } /* Event listeners */ static void auth_exit_ev(const void *event_data, void *user_data) { /* Close the scoreboard descriptor that we opened. */ (void) pr_close_scoreboard(FALSE); } static int auth_sess_init(void) { config_rec *c = NULL; unsigned char *tmp = NULL; int res = 0; /* Check for a server-specific TimeoutLogin */ c = find_config(main_server->conf, CONF_PARAM, "TimeoutLogin", FALSE); if (c != NULL) { TimeoutLogin = *((int *) c->argv[0]); } /* Start the login timer */ if (TimeoutLogin) { pr_timer_remove(PR_TIMER_LOGIN, &auth_module); pr_timer_add(TimeoutLogin, PR_TIMER_LOGIN, &auth_module, auth_login_timeout_cb, "TimeoutLogin"); } PRIVS_ROOT res = pr_open_scoreboard(O_RDWR); PRIVS_RELINQUISH if (res < 0) { switch (res) { case PR_SCORE_ERR_BAD_MAGIC: pr_log_debug(DEBUG0, "error opening scoreboard: bad/corrupted file"); break; case PR_SCORE_ERR_OLDER_VERSION: pr_log_debug(DEBUG0, "error opening scoreboard: bad version (too old)"); break; case PR_SCORE_ERR_NEWER_VERSION: pr_log_debug(DEBUG0, "error opening scoreboard: bad version (too new)"); break; default: pr_log_debug(DEBUG0, "error opening scoreboard: %s", strerror(errno)); break; } } pr_event_register(&auth_module, "core.exit", auth_exit_ev, NULL); /* Create an entry in the scoreboard for this session, if we don't already * have one. */ if (pr_scoreboard_entry_get(PR_SCORE_CLIENT_ADDR) == NULL) { if (pr_scoreboard_entry_add() < 0) { pr_log_pri(PR_LOG_NOTICE, "notice: unable to add scoreboard entry: %s", strerror(errno)); } pr_scoreboard_entry_update(session.pid, PR_SCORE_USER, "(none)", PR_SCORE_SERVER_PORT, main_server->ServerPort, PR_SCORE_SERVER_ADDR, session.c->local_addr, session.c->local_port, PR_SCORE_SERVER_LABEL, main_server->ServerName, PR_SCORE_CLIENT_ADDR, session.c->remote_addr, PR_SCORE_CLIENT_NAME, session.c->remote_name, PR_SCORE_CLASS, session.conn_class ? session.conn_class->cls_name : "", PR_SCORE_PROTOCOL, "ftp", PR_SCORE_BEGIN_SESSION, time(NULL), NULL); } else { /* We're probably handling a HOST comand, and the server changed; just * update the SERVER_LABEL field. */ pr_scoreboard_entry_update(session.pid, PR_SCORE_SERVER_LABEL, main_server->ServerName, NULL); } /* Should we create the home for a user, if they don't have one? */ tmp = get_param_ptr(main_server->conf, "CreateHome", FALSE); if (tmp != NULL && *tmp == TRUE) { mkhome = TRUE; } else { mkhome = FALSE; } #ifdef PR_USE_LASTLOG /* Use the lastlog file, if supported and requested. */ tmp = get_param_ptr(main_server->conf, "UseLastlog", FALSE); if (tmp && *tmp == TRUE) { lastlog = TRUE; } else { lastlog = FALSE; } #endif /* PR_USE_LASTLOG */ /* Scan the scoreboard now, in order to tally up certain values for * substituting in any of the Display* file variables. This function * also performs the MaxConnectionsPerHost enforcement. */ auth_scan_scoreboard(); return 0; } static int auth_init(void) { /* Add the commands handled by this module to the HELP list. */ pr_help_add(C_USER, _("<sp> username"), TRUE); pr_help_add(C_PASS, _("<sp> password"), TRUE); pr_help_add(C_ACCT, _("is not implemented"), FALSE); pr_help_add(C_REIN, _("is not implemented"), FALSE); /* By default, enable auth checking */ set_auth_check(auth_cmd_chk_cb); return 0; } static int _do_auth(pool *p, xaset_t *conf, char *u, char *pw) { char *cpw = NULL; config_rec *c; if (conf) { c = find_config(conf, CONF_PARAM, "UserPassword", FALSE); while (c) { if (strcmp(c->argv[0], u) == 0) { cpw = (char *) c->argv[1]; break; } c = find_config_next(c, c->next, CONF_PARAM, "UserPassword", FALSE); } } if (cpw) { if (pr_auth_getpwnam(p, u) == NULL) { int xerrno = errno; if (xerrno == ENOENT) { pr_log_pri(PR_LOG_NOTICE, "no such user '%s'", u); } errno = xerrno; return PR_AUTH_NOPWD; } return pr_auth_check(p, cpw, u, pw); } return pr_auth_authenticate(p, u, pw); } /* Command handlers */ MODRET auth_post_host(cmd_rec *cmd) { /* If the HOST command changed the main_server pointer, reinitialize * ourselves. */ if (session.prev_server != NULL) { int res; /* Remove the TimeoutLogin timer. */ pr_timer_remove(PR_TIMER_LOGIN, &auth_module); pr_event_unregister(&auth_module, "core.exit", auth_exit_ev); /* Reset the CreateHome setting. */ mkhome = FALSE; #ifdef PR_USE_LASTLOG /* Reset the UseLastLog setting. */ lastlog = FALSE; #endif /* PR_USE_LASTLOG */ res = auth_sess_init(); if (res < 0) { pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_SESSION_INIT_FAILED, NULL); } } return PR_DECLINED(cmd); } MODRET auth_err_pass(cmd_rec *cmd) { /* Remove the stashed original USER name here in a LOG_CMD_ERR handler, so * that other modules, who may want to lookup the original USER parameter on * a failed login in an earlier command handler phase, have a chance to do * so. This removal of the USER parameter on failure was happening directly * in the CMD handler previously, thus preventing POST_CMD_ERR handlers from * using USER. */ pr_table_remove(session.notes, "mod_auth.orig-user", NULL); return PR_HANDLED(cmd); } MODRET auth_log_pass(cmd_rec *cmd) { size_t passwd_len; /* Only log, to the syslog, that the login has succeeded here, where we * know that the login has definitely succeeded. */ pr_log_auth(PR_LOG_INFO, "%s %s: Login successful.", (session.anon_config != NULL) ? "ANON" : C_USER, session.user); if (cmd->arg != NULL) { /* And scrub the memory holding the password sent by the client, for * safety/security. */ passwd_len = strlen(cmd->arg); pr_memscrub(cmd->arg, passwd_len); } return PR_DECLINED(cmd); } MODRET auth_post_pass(cmd_rec *cmd) { config_rec *c = NULL; char *grantmsg = NULL, *user; unsigned int ctxt_precedence = 0; unsigned char have_user_timeout, have_group_timeout, have_class_timeout, have_all_timeout, *root_revoke = NULL, *authenticated; struct stat st; /* Was there a precending USER command? Was the client successfully * authenticated? */ authenticated = get_param_ptr(cmd->server->conf, "authenticated", FALSE); /* Clear the list of auth-only modules. */ pr_auth_clear_auth_only_modules(); if (authenticated != NULL && *authenticated == TRUE) { /* At this point, we can look up the Protocols config if the client * has been authenticated, which may have been tweaked via mod_ifsession's * user/group/class-specific sections. */ c = find_config(main_server->conf, CONF_PARAM, "Protocols", FALSE); if (c) { register unsigned int i; array_header *protocols; char **elts; const char *protocol; protocols = c->argv[0]; elts = protocols->elts; protocol = pr_session_get_protocol(PR_SESS_PROTO_FL_LOGOUT); /* We only want to check for 'ftp' in the configured Protocols list * if a) a RFC2228 mechanism (e.g. SSL or GSS) is not in use, and * b) an SSH protocol is not in use. */ if (session.rfc2228_mech == NULL && strncmp(protocol, "SSH2", 5) != 0) { int allow_ftp = FALSE; for (i = 0; i < protocols->nelts; i++) { char *proto; proto = elts[i]; if (proto != NULL) { if (strncasecmp(proto, "ftp", 4) == 0) { allow_ftp = TRUE; break; } } } if (!allow_ftp) { pr_log_debug(DEBUG0, "%s", "ftp protocol denied by Protocols config"); pr_response_send(R_530, "%s", _("Login incorrect.")); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by Protocols setting"); } } } } user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); /* Count up various quantities in the scoreboard, checking them against * the Max* limits to see if the session should be barred from going * any further. */ auth_count_scoreboard(cmd, session.user); /* Check for dynamic configuration. This check needs to be after the * setting of any possible anon_config, as that context may be allowed * or denied .ftpaccess-parsing separately from the containing server. */ if (pr_fsio_stat(session.cwd, &st) != -1) build_dyn_config(cmd->tmp_pool, session.cwd, &st, TRUE); have_user_timeout = have_group_timeout = have_class_timeout = have_all_timeout = FALSE; c = find_config(TOPLEVEL_CONF, CONF_PARAM, "TimeoutSession", FALSE); while (c != NULL) { pr_signals_handle(); if (c->argc == 3) { if (strncmp(c->argv[1], "user", 5) == 0) { if (pr_expr_eval_user_or((char **) &c->argv[2]) == TRUE) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_group_timeout = have_class_timeout = have_all_timeout = FALSE; have_user_timeout = TRUE; } } } else if (strncmp(c->argv[1], "group", 6) == 0) { if (pr_expr_eval_group_and((char **) &c->argv[2]) == TRUE) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_class_timeout = have_all_timeout = FALSE; have_group_timeout = TRUE; } } } else if (strncmp(c->argv[1], "class", 6) == 0) { if (session.conn_class != NULL && strcmp(session.conn_class->cls_name, c->argv[2]) == 0) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_group_timeout = have_all_timeout = FALSE; have_class_timeout = TRUE; } } } } else { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_group_timeout = have_class_timeout = FALSE; have_all_timeout = TRUE; } } c = find_config_next(c, c->next, CONF_PARAM, "TimeoutSession", FALSE); } /* If configured, start a session timer. The timer ID value for * session timers will not be #defined, as I think that is a bad approach. * A better mechanism would be to use the random timer ID generation, and * store the returned ID in order to later remove the timer. */ if (have_user_timeout || have_group_timeout || have_class_timeout || have_all_timeout) { pr_log_debug(DEBUG4, "setting TimeoutSession of %d seconds for current %s", TimeoutSession, have_user_timeout ? "user" : have_group_timeout ? "group" : have_class_timeout ? "class" : "all"); pr_timer_add(TimeoutSession, PR_TIMER_SESSION, &auth_module, auth_session_timeout_cb, "TimeoutSession"); } /* Handle a DisplayLogin file. */ if (displaylogin_fh) { if (!(session.sf_flags & SF_ANON)) { if (pr_display_fh(displaylogin_fh, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin_fh->fh_path, strerror(errno)); } pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } else { /* We're an <Anonymous> login, but there was a previous DisplayLogin * configured which was picked up earlier. Close that filehandle, * and look for a new one. */ char *displaylogin; pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin) { if (pr_display_file(displaylogin, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } } } } else { char *displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin) { if (pr_display_file(displaylogin, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } } } grantmsg = get_param_ptr(TOPLEVEL_CONF, "AccessGrantMsg", FALSE); if (grantmsg == NULL) { /* Append the final greeting lines. */ if (session.sf_flags & SF_ANON) { pr_response_add(auth_pass_resp_code, "%s", _("Anonymous access granted, restrictions apply")); } else { pr_response_add(auth_pass_resp_code, _("User %s logged in"), user); } } else { /* Handle any AccessGrantMsg directive. */ grantmsg = sreplace(cmd->tmp_pool, grantmsg, "%u", user, NULL); pr_response_add(auth_pass_resp_code, "%s", grantmsg); } /* A RootRevoke value of 0 indicates 'false', 1 indicates 'true', and * 2 indicates 'NonCompliantActiveTransfer'. We will drop root privs for any * RootRevoke value greater than 0. */ root_revoke = get_param_ptr(TOPLEVEL_CONF, "RootRevoke", FALSE); if (root_revoke != NULL && *root_revoke > 0) { pr_signals_block(); PRIVS_ROOT PRIVS_REVOKE pr_signals_unblock(); /* Disable future attempts at UID/GID manipulation. */ session.disable_id_switching = TRUE; if (*root_revoke == 1) { /* If the server's listening port is less than 1024, block PORT * commands (effectively allowing only passive connections, which is * not necessarily a Bad Thing). Only log this here -- the blocking * will need to occur in mod_core's handling of the PORT/EPRT commands. */ if (session.c->local_port < 1024) { pr_log_debug(DEBUG0, "RootRevoke in effect, active data transfers may not succeed"); } } pr_log_debug(DEBUG0, "RootRevoke in effect, dropped root privs"); } return PR_DECLINED(cmd); } /* Handle group based authentication, only checked if pw * based fails */ static config_rec *_auth_group(pool *p, char *user, char **group, char **ournamep, char **anonnamep, char *pass) { config_rec *c; char *ourname = NULL,*anonname = NULL; char **grmem; struct group *grp; ourname = (char*)get_param_ptr(main_server->conf,"UserName",FALSE); if (ournamep && ourname) *ournamep = ourname; c = find_config(main_server->conf, CONF_PARAM, "GroupPassword", TRUE); if (c) do { grp = pr_auth_getgrnam(p, c->argv[0]); if (!grp) continue; for (grmem = grp->gr_mem; *grmem; grmem++) if (strcmp(*grmem, user) == 0) { if (pr_auth_check(p, c->argv[1], user, pass) == 0) break; } if (*grmem) { if (group) *group = c->argv[0]; if (c->parent) c = c->parent; if (c->config_type == CONF_ANON) anonname = (char*)get_param_ptr(c->subset,"UserName",FALSE); if (anonnamep) *anonnamep = anonname; if (anonnamep && !anonname && ourname) *anonnamep = ourname; break; } } while((c = find_config_next(c,c->next,CONF_PARAM,"GroupPassword",TRUE)) != NULL); return c; } /* Determine any applicable chdirs */ static char *get_default_chdir(pool *p, xaset_t *conf) { config_rec *c; char *dir = NULL; int ret; c = find_config(conf, CONF_PARAM, "DefaultChdir", FALSE); while (c) { /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } ret = pr_expr_eval_group_and(((char **) c->argv)+1); if (ret) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultChdir", FALSE); } /* If the directory is relative, concatenate w/ session.cwd. */ if (dir && *dir != '/' && *dir != '~') dir = pdircat(p, session.cwd, dir, NULL); /* Check for any expandable variables. */ if (dir) dir = path_subst_uservar(p, &dir); return dir; } static int is_symlink_path(pool *p, const char *path, size_t pathlen) { int res, xerrno = 0; struct stat st; char *ptr; if (pathlen == 0) { return 0; } pr_fs_clear_cache(); res = pr_fsio_lstat(path, &st); if (res < 0) { xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path, strerror(xerrno)); errno = xerrno; return -1; } if (S_ISLNK(st.st_mode)) { errno = EPERM; return -1; } /* To handle the case where a component further up the path might be a * symlink (which lstat(2) will NOT handle), we walk the path backwards, * calling ourselves recursively. */ ptr = strrchr(path, '/'); if (ptr != NULL) { char *new_path; size_t new_pathlen; pr_signals_handle(); new_pathlen = ptr - path; /* Make sure our pointer actually changed position. */ if (new_pathlen == pathlen) { return 0; } new_path = pstrndup(p, path, new_pathlen); pr_log_debug(DEBUG10, "AllowChrootSymlink: path '%s' not a symlink, checking '%s'", path, new_path); res = is_symlink_path(p, new_path, new_pathlen); if (res < 0) { return -1; } } return 0; } /* Determine if the user (non-anon) needs a default root dir other than /. */ static int get_default_root(pool *p, int allow_symlinks, char **root) { config_rec *c = NULL; char *dir = NULL; int res; c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE); while (c) { pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE); } if (dir) { char *new_dir; /* Check for any expandable variables. */ new_dir = path_subst_uservar(p, &dir); if (new_dir != NULL) { dir = new_dir; } if (strncmp(dir, "/", 2) == 0) { dir = NULL; } else { char *realdir; int xerrno = 0; if (allow_symlinks == FALSE) { char *path, target_path[PR_TUNABLE_PATH_MAX + 1]; size_t pathlen; /* First, deal with any possible interpolation. dir_realpath() will * do this for us, but dir_realpath() ALSO automatically follows * symlinks, which is what we do NOT want to do here. */ path = dir; if (*path != '/') { if (*path == '~') { if (pr_fs_interpolate(dir, target_path, sizeof(target_path)-1) < 0) { return -1; } path = target_path; } } /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ pathlen = strlen(path); if (pathlen > 1 && path[pathlen-1] == '/') { path[pathlen-1] = '\0'; } res = is_symlink_path(p, path, pathlen); if (res < 0) { if (errno == EPERM) { pr_log_pri(PR_LOG_WARNING, "error: DefaultRoot %s is a symlink " "(denied by AllowChrootSymlinks config)", path); } errno = EPERM; return -1; } } /* We need to be the final user here so that if the user has their home * directory with a mode the user proftpd is running (i.e. the User * directive) as can not traverse down, we can still have the default * root. */ PRIVS_USER realdir = dir_realpath(p, dir); xerrno = errno; PRIVS_RELINQUISH if (realdir) { dir = realdir; } else { /* Try to provide a more informative message. */ char interp_dir[PR_TUNABLE_PATH_MAX + 1]; memset(interp_dir, '\0', sizeof(interp_dir)); (void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1); pr_log_pri(PR_LOG_NOTICE, "notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s", dir, interp_dir, strerror(xerrno)); errno = xerrno; } } } *root = dir; return 0; } static struct passwd *passwd_dup(pool *p, struct passwd *pw) { struct passwd *npw; npw = pcalloc(p, sizeof(struct passwd)); npw->pw_name = pstrdup(p, pw->pw_name); npw->pw_passwd = pstrdup(p, pw->pw_passwd); npw->pw_uid = pw->pw_uid; npw->pw_gid = pw->pw_gid; npw->pw_gecos = pstrdup(p, pw->pw_gecos); npw->pw_dir = pstrdup(p, pw->pw_dir); npw->pw_shell = pstrdup(p, pw->pw_shell); return npw; } static void ensure_open_passwd(pool *p) { /* Make sure pass/group is open. */ pr_auth_setpwent(p); pr_auth_setgrent(p); /* On some unices the following is necessary to ensure the files * are open. (BSDI 3.1) */ pr_auth_getpwent(p); pr_auth_getgrent(p); } /* Next function (the biggie) handles all authentication, setting * up chroot() jail, etc. */ static int setup_env(pool *p, cmd_rec *cmd, char *user, char *pass) { struct passwd *pw; config_rec *c, *tmpc; char *origuser, *ourname = NULL, *anonname = NULL, *anongroup = NULL, *ugroup = NULL; char *defaulttransfermode, *defroot = NULL,*defchdir = NULL,*xferlog = NULL; const char *sess_ttyname; int aclp, i, res = 0, allow_chroot_symlinks = TRUE, showsymlinks; unsigned char *wtmp_log = NULL, *anon_require_passwd = NULL; /********************* Authenticate the user here *********************/ session.hide_password = TRUE; origuser = user; c = pr_auth_get_anon_config(p, &user, &ourname, &anonname); if (c) session.anon_config = c; if (!user) { pr_log_auth(PR_LOG_NOTICE, "USER %s: user is not a UserAlias from %s [%s] " "to %s:%i", origuser, session.c->remote_name, pr_netaddr_get_ipstr(session.c->remote_addr), pr_netaddr_get_ipstr(session.c->local_addr), session.c->local_port); goto auth_failure; } pw = pr_auth_getpwnam(p, user); if (pw == NULL && c != NULL && ourname != NULL) { /* If the client is authenticating using an alias (e.g. "AuthAliasOnly on"), * then we need to try checking using the real username, too (Bug#4255). */ pr_trace_msg("auth", 16, "no user entry found for <Anonymous> alias '%s', using '%s'", user, ourname); pw = pr_auth_getpwnam(p, ourname); } if (pw == NULL) { int auth_code = PR_AUTH_NOPWD; pr_log_auth(PR_LOG_NOTICE, "USER %s: no such user found from %s [%s] to %s:%i", user, session.c->remote_name, pr_netaddr_get_ipstr(session.c->remote_addr), pr_netaddr_get_ipstr(session.c->local_addr), session.c->local_port); pr_event_generate("mod_auth.authentication-code", &auth_code); goto auth_failure; } /* Security: other functions perform pw lookups, thus we need to make * a local copy of the user just looked up. */ pw = passwd_dup(p, pw); if (pw->pw_uid == PR_ROOT_UID) { unsigned char *root_allow = NULL; pr_event_generate("mod_auth.root-login", NULL); /* If RootLogin is set to true, we allow this... even though we * still log a warning. :) */ if ((root_allow = get_param_ptr(c ? c->subset : main_server->conf, "RootLogin", FALSE)) == NULL || *root_allow != TRUE) { if (pass) { pr_memscrub(pass, strlen(pass)); } pr_log_auth(PR_LOG_NOTICE, "SECURITY VIOLATION: Root login attempted"); return 0; } } session.user = pstrdup(p, pw->pw_name); session.group = pstrdup(p, pr_auth_gid2name(p, pw->pw_gid)); /* Set the login_uid and login_uid */ session.login_uid = pw->pw_uid; session.login_gid = pw->pw_gid; /* Check for any expandable variables in session.cwd. */ pw->pw_dir = path_subst_uservar(p, &pw->pw_dir); /* Before we check for supplemental groups, check to see if the locally * resolved name of the user, returned via auth_getpwnam(), is different * from the USER argument sent by the client. The name can change, since * auth modules can play all sorts of neat tricks on us. * * If the names differ, assume that any cached data in the session.gids * and session.groups lists are stale, and clear them out. */ if (strcmp(pw->pw_name, user) != 0) { pr_log_debug(DEBUG10, "local user name '%s' differs from client-sent " "user name '%s', clearing cached group data", pw->pw_name, user); session.gids = NULL; session.groups = NULL; } if (!session.gids && !session.groups) { /* Get the supplemental groups. Note that we only look up the * supplemental group credentials if we have not cached the group * credentials before, in session.gids and session.groups. * * Those credentials may have already been retrieved, as part of the * pr_auth_get_anon_config() call. */ res = pr_auth_getgroups(p, pw->pw_name, &session.gids, &session.groups); if (res < 1) { pr_log_debug(DEBUG2, "no supplemental groups found for user '%s'", pw->pw_name); } } tmpc = find_config(main_server->conf, CONF_PARAM, "AllowChrootSymlinks", FALSE); if (tmpc != NULL) { allow_chroot_symlinks = *((int *) tmpc->argv[0]); } /* If c != NULL from this point on, we have an anonymous login */ aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); if (c) { anongroup = get_param_ptr(c->subset, "GroupName", FALSE); if (!anongroup) anongroup = get_param_ptr(main_server->conf, "GroupName",FALSE); /* Check for configured AnonRejectPasswords regex here, and fail the login * if the given password matches the regex. */ #ifdef PR_USE_REGEX if ((tmpc = find_config(c->subset, CONF_PARAM, "AnonRejectPasswords", FALSE)) != NULL) { int re_res; pr_regex_t *pw_regex = (pr_regex_t *) tmpc->argv[0]; if (pw_regex && pass && ((re_res = pr_regexp_exec(pw_regex, pass, 0, NULL, 0, 0, 0)) == 0)) { char errstr[200] = {'\0'}; pr_regexp_error(re_res, pw_regex, errstr, sizeof(errstr)); pr_log_auth(PR_LOG_NOTICE, "ANON %s: AnonRejectPasswords denies login", origuser); pr_event_generate("mod_auth.anon-reject-passwords", session.c); goto auth_failure; } } #endif if (!login_check_limits(c->subset, FALSE, TRUE, &i) || (!aclp && !i) ){ pr_log_auth(PR_LOG_NOTICE, "ANON %s (Login failed): Limit access denies " "login", origuser); goto auth_failure; } } if (c == NULL && aclp == 0) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Limit access denies login", origuser); goto auth_failure; } if (c) { anon_require_passwd = get_param_ptr(c->subset, "AnonRequirePassword", FALSE); } if (!c || (anon_require_passwd && *anon_require_passwd == TRUE)) { int auth_code; char *user_name = user; if (c && origuser && strcasecmp(user, origuser) != 0) { unsigned char *auth_using_alias = get_param_ptr(c->subset, "AuthUsingAlias", FALSE); /* If 'AuthUsingAlias' set and we're logging in under an alias, * then auth using that alias. */ if (auth_using_alias && *auth_using_alias == TRUE) { user_name = origuser; pr_log_auth(PR_LOG_INFO, "ANON AUTH: User %s, authenticating using alias %s", user, user_name); } } /* It is possible for the user to have already been authenticated during * the handling of the USER command, as by an RFC2228 mechanism. If * that had happened, we won't need to call _do_auth() here. */ if (!authenticated_without_pass) { auth_code = _do_auth(p, c ? c->subset : main_server->conf, user_name, pass); } else { auth_code = PR_AUTH_OK_NO_PASS; } pr_event_generate("mod_auth.authentication-code", &auth_code); if (auth_code < 0) { /* Normal authentication has failed, see if group authentication * passes */ c = _auth_group(p, user, &anongroup, &ourname, &anonname, pass); if (c != NULL) { if (c->config_type != CONF_ANON) { c = NULL; ugroup = anongroup; anongroup = NULL; } auth_code = PR_AUTH_OK; } } if (pass) pr_memscrub(pass, strlen(pass)); if (session.auth_mech) pr_log_debug(DEBUG2, "user '%s' authenticated by %s", user, session.auth_mech); switch (auth_code) { case PR_AUTH_OK_NO_PASS: auth_pass_resp_code = R_232; break; case PR_AUTH_OK: auth_pass_resp_code = R_230; break; case PR_AUTH_NOPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): No such user found", user); goto auth_failure; case PR_AUTH_BADPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Incorrect password", origuser); goto auth_failure; case PR_AUTH_AGEPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Password expired", user); goto auth_failure; case PR_AUTH_DISABLEDPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Account disabled", user); goto auth_failure; default: break; }; /* Catch the case where we forgot to handle a bad auth code above. */ if (auth_code < 0) goto auth_failure; if (pw->pw_uid == PR_ROOT_UID) { pr_log_auth(PR_LOG_WARNING, "ROOT FTP login successful"); } } else if (c && (!anon_require_passwd || *anon_require_passwd == FALSE)) { session.hide_password = FALSE; } pr_auth_setgrent(p); res = pr_auth_is_valid_shell(c ? c->subset : main_server->conf, pw->pw_shell); if (res == FALSE) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Invalid shell: '%s'", user, pw->pw_shell); goto auth_failure; } res = pr_auth_banned_by_ftpusers(c ? c->subset : main_server->conf, pw->pw_name); if (res == TRUE) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): User in " PR_FTPUSERS_PATH, user); goto auth_failure; } if (c) { struct group *grp = NULL; unsigned char *add_userdir = NULL; char *u, *chroot_dir; u = pr_table_get(session.notes, "mod_auth.orig-user", NULL); add_userdir = get_param_ptr(c->subset, "UserDirRoot", FALSE); /* If resolving an <Anonymous> user, make sure that user's groups * are set properly for the check of the home directory path (which * depend on those supplemental group memberships). Additionally, * temporarily switch to the new user's uid. */ pr_signals_block(); PRIVS_ROOT res = set_groups(p, pw->pw_gid, session.gids); if (res < 0) { pr_log_pri(PR_LOG_WARNING, "error: unable to set groups: %s", strerror(errno)); } #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(pw->pw_uid, pw->pw_gid) if ((add_userdir && *add_userdir == TRUE) && strcmp(u, user) != 0) { chroot_dir = pdircat(p, c->name, u, NULL); } else { chroot_dir = c->name; } if (allow_chroot_symlinks == FALSE) { char *chroot_path, target_path[PR_TUNABLE_PATH_MAX+1]; struct stat st; chroot_path = chroot_dir; if (chroot_path[0] != '/') { if (chroot_path[0] == '~') { if (pr_fs_interpolate(chroot_path, target_path, sizeof(target_path)-1) == 0) { chroot_path = target_path; } else { chroot_path = NULL; } } } if (chroot_path != NULL) { size_t chroot_pathlen; /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ chroot_pathlen = strlen(chroot_path); if (chroot_pathlen > 1 && chroot_path[chroot_pathlen-1] == '/') { chroot_path[chroot_pathlen-1] = '\0'; } pr_fs_clear_cache(); res = pr_fsio_lstat(chroot_path, &st); if (res < 0) { int xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", chroot_path, strerror(xerrno)); errno = xerrno; chroot_path = NULL; } else { if (S_ISLNK(st.st_mode)) { pr_log_pri(PR_LOG_WARNING, "error: <Anonymous %s> is a symlink (denied by " "AllowChrootSymlinks config)", chroot_path); errno = EPERM; chroot_path = NULL; } } } if (chroot_path != NULL) { session.chroot_path = dir_realpath(p, chroot_dir); } else { session.chroot_path = NULL; } if (session.chroot_path == NULL) { pr_log_debug(DEBUG8, "error resolving '%s': %s", chroot_dir, strerror(errno)); } } else { session.chroot_path = dir_realpath(p, chroot_dir); if (session.chroot_path == NULL) { pr_log_debug(DEBUG8, "error resolving '%s': %s", chroot_dir, strerror(errno)); } } if (session.chroot_path && pr_fsio_access(session.chroot_path, X_OK, session.uid, session.gid, session.gids) != 0) { session.chroot_path = NULL; } else { session.chroot_path = pstrdup(session.pool, session.chroot_path); } /* Return all privileges back to that of the daemon, for now. */ PRIVS_ROOT res = set_groups(p, daemon_gid, daemon_gids); if (res < 0) { pr_log_pri(PR_LOG_ERR, "error: unable to set groups: %s", strerror(errno)); } #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(daemon_uid, daemon_gid) pr_signals_unblock(); /* Sanity check, make sure we have daemon_uid and daemon_gid back */ #ifdef HAVE_GETEUID if (getegid() != daemon_gid || geteuid() != daemon_uid) { PRIVS_RELINQUISH pr_log_pri(PR_LOG_WARNING, "switching IDs from user %s back to daemon uid/gid failed: %s", session.user, strerror(errno)); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL); } #endif /* HAVE_GETEUID */ if (anon_require_passwd && *anon_require_passwd == TRUE) { session.anon_user = pstrdup(session.pool, origuser); } else { session.anon_user = pstrdup(session.pool, pass); } if (!session.chroot_path) { pr_log_pri(PR_LOG_NOTICE, "%s: Directory %s is not accessible", session.user, c->name); pr_response_add_err(R_530, _("Unable to set anonymous privileges.")); goto auth_failure; } sstrncpy(session.cwd, "/", sizeof(session.cwd)); xferlog = get_param_ptr(c->subset, "TransferLog", FALSE); if (anongroup) { grp = pr_auth_getgrnam(p, anongroup); if (grp) { pw->pw_gid = grp->gr_gid; session.group = pstrdup(p, grp->gr_name); } } } else { struct group *grp; char *homedir; if (ugroup) { grp = pr_auth_getgrnam(p, ugroup); if (grp) { pw->pw_gid = grp->gr_gid; session.group = pstrdup(p, grp->gr_name); } } /* Attempt to resolve any possible symlinks. */ PRIVS_USER homedir = dir_realpath(p, pw->pw_dir); PRIVS_RELINQUISH if (homedir) sstrncpy(session.cwd, homedir, sizeof(session.cwd)); else sstrncpy(session.cwd, pw->pw_dir, sizeof(session.cwd)); } /* Create the home directory, if need be. */ if (!c && mkhome) { if (create_home(p, session.cwd, origuser, pw->pw_uid, pw->pw_gid) < 0) { /* NOTE: should this cause the login to fail? */ goto auth_failure; } } /* Get default chdir (if any) */ defchdir = get_default_chdir(p, (c ? c->subset : main_server->conf)); if (defchdir) sstrncpy(session.cwd, defchdir, sizeof(session.cwd)); /* Check limits again to make sure deny/allow directives still permit * access. */ if (!login_check_limits((c ? c->subset : main_server->conf), FALSE, TRUE, &i)) { pr_log_auth(PR_LOG_NOTICE, "%s %s: Limit access denies login", (c != NULL) ? "ANON" : C_USER, origuser); goto auth_failure; } /* Perform a directory fixup. */ resolve_deferred_dirs(main_server); fixup_dirs(main_server, CF_DEFER); /* If running under an anonymous context, resolve all <Directory> * blocks inside it. */ if (c && c->subset) resolve_anonymous_dirs(c->subset); /* Write the login to wtmp. This must be done here because we won't * have access after we give up root. This can result in falsified * wtmp entries if an error kicks the user out before we get * through with the login process. Oh well. */ sess_ttyname = pr_session_get_ttyname(p); /* Perform wtmp logging only if not turned off in <Anonymous> * or the current server */ if (c) wtmp_log = get_param_ptr(c->subset, "WtmpLog", FALSE); if (wtmp_log == NULL) wtmp_log = get_param_ptr(main_server->conf, "WtmpLog", FALSE); /* As per Bug#3482, we need to disable WtmpLog for FreeBSD 9.0, as * an interim measure. * * The issue is that some platforms update multiple files for a single * pututxline(3) call; proftpd tries to update those files manually, * do to chroots (after which a pututxline(3) call will fail). A proper * solution requires a separate process, running with the correct * privileges, which would handle wtmp logging. The proftpd session * processes would send messages to this logging daemon (via Unix domain * socket, or FIFO, or TCP socket). * * Also note that this hack to disable WtmpLog may need to be extended * to other platforms in the future. */ #if defined(HAVE_UTMPX_H) && \ defined(__FreeBSD_version) && __FreeBSD_version >= 900007 if (wtmp_log == NULL || *wtmp_log == TRUE) { wtmp_log = pcalloc(p, sizeof(unsigned char)); *wtmp_log = FALSE; pr_log_debug(DEBUG5, "WtpmLog automatically disabled; see Bug#3482 for details"); } #endif PRIVS_ROOT if (wtmp_log == NULL || *wtmp_log == TRUE) { log_wtmp(sess_ttyname, session.user, session.c->remote_name, session.c->remote_addr); session.wtmp_log = TRUE; } #ifdef PR_USE_LASTLOG if (lastlog) { log_lastlog(pw->pw_uid, session.user, sess_ttyname, session.c->remote_addr); } #endif /* PR_USE_LASTLOG */ /* Open any TransferLogs */ if (!xferlog) { if (c) xferlog = get_param_ptr(c->subset, "TransferLog", FALSE); if (!xferlog) xferlog = get_param_ptr(main_server->conf, "TransferLog", FALSE); if (!xferlog) xferlog = PR_XFERLOG_PATH; } if (strcasecmp(xferlog, "NONE") == 0) { xferlog_open(NULL); } else { xferlog_open(xferlog); } res = set_groups(p, pw->pw_gid, session.gids); if (res < 0) { pr_log_pri(PR_LOG_ERR, "error: unable to set groups: %s", strerror(errno)); } PRIVS_RELINQUISH /* Now check to see if the user has an applicable DefaultRoot */ if (c == NULL) { if (get_default_root(session.pool, allow_chroot_symlinks, &defroot) < 0) { pr_log_pri(PR_LOG_NOTICE, "error: unable to determine DefaultRoot directory"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } ensure_open_passwd(p); if (defroot != NULL) { if (pr_auth_chroot(defroot) == -1) { pr_log_pri(PR_LOG_NOTICE, "error: unable to set DefaultRoot directory"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } /* Re-calc the new cwd based on this root dir. If not applicable * place the user in / (of defroot) */ if (strncmp(session.cwd, defroot, strlen(defroot)) == 0) { char *newcwd = &session.cwd[strlen(defroot)]; if (*newcwd == '/') newcwd++; session.cwd[0] = '/'; sstrncpy(&session.cwd[1], newcwd, sizeof(session.cwd)); } } } if (c) ensure_open_passwd(p); if (c && pr_auth_chroot(session.chroot_path) == -1) { pr_log_pri(PR_LOG_NOTICE, "error: unable to set anonymous privileges"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } /* new in 1.1.x, I gave in and we don't give up root permanently.. * sigh. */ PRIVS_ROOT #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(pw->pw_uid, pw->pw_gid) #ifdef HAVE_GETEUID if (getegid() != pw->pw_gid || geteuid() != pw->pw_uid) { PRIVS_RELINQUISH pr_log_pri(PR_LOG_ERR, "error: %s setregid() or setreuid(): %s", session.user, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } #endif /* If the home directory is NULL or "", reject the login. */ if (pw->pw_dir == NULL || strncmp(pw->pw_dir, "", 1) == 0) { pr_log_pri(PR_LOG_WARNING, "error: user %s home directory is NULL or \"\"", session.user); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } { unsigned char *show_symlinks = get_param_ptr( c ? c->subset : main_server->conf, "ShowSymlinks", FALSE); if (!show_symlinks || *show_symlinks == TRUE) showsymlinks = TRUE; else showsymlinks = FALSE; } /* chdir to the proper directory, do this even if anonymous * to make sure we aren't outside our chrooted space. */ /* Attempt to change to the correct directory -- use session.cwd first. * This will contain the DefaultChdir directory, if configured... */ if (pr_fsio_chdir_canon(session.cwd, !showsymlinks) == -1) { /* if we've got DefaultRoot or anonymous login, ignore this error * and chdir to / */ if (session.chroot_path != NULL || defroot) { pr_log_debug(DEBUG2, "unable to chdir to %s (%s), defaulting to chroot " "directory %s", session.cwd, strerror(errno), (session.chroot_path ? session.chroot_path : defroot)); if (pr_fsio_chdir_canon("/", !showsymlinks) == -1) { pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"/\") failed: %s", session.user, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } else if (defchdir) { /* If we've got defchdir, failure is ok as well, simply switch to * user's homedir. */ pr_log_debug(DEBUG2, "unable to chdir to %s (%s), defaulting to home " "directory %s", session.cwd, strerror(errno), pw->pw_dir); if (pr_fsio_chdir_canon(pw->pw_dir, !showsymlinks) == -1) { pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"%s\") failed: %s", session.user, session.cwd, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } else { /* Unable to switch to user's real home directory, which is not * allowed. */ pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"%s\") failed: %s", session.user, session.cwd, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } sstrncpy(session.cwd, pr_fs_getcwd(), sizeof(session.cwd)); sstrncpy(session.vwd, pr_fs_getvwd(), sizeof(session.vwd)); /* Make sure directory config pointers are set correctly */ dir_check_full(p, cmd, G_NONE, session.cwd, NULL); if (c) { if (!session.hide_password) { session.proc_prefix = pstrcat(session.pool, session.c->remote_name, ": anonymous/", pass, NULL); } else { session.proc_prefix = pstrcat(session.pool, session.c->remote_name, ": anonymous", NULL); } session.sf_flags = SF_ANON; } else { session.proc_prefix = pstrdup(session.pool, session.c->remote_name); session.sf_flags = 0; } /* While closing the pointer to the password database would avoid any * potential attempt to hijack this information, it is unfortunately needed * in a chroot()ed environment. Otherwise, mappings from UIDs to names, * among other things, would fail. */ /* pr_auth_endpwent(p); */ /* Default transfer mode is ASCII */ defaulttransfermode = (char *) get_param_ptr(main_server->conf, "DefaultTransferMode", FALSE); if (defaulttransfermode && strcasecmp(defaulttransfermode, "binary") == 0) { session.sf_flags &= (SF_ALL^SF_ASCII); } else { session.sf_flags |= SF_ASCII; } /* Authentication complete, user logged in, now kill the login * timer. */ /* Update the scoreboard entry */ pr_scoreboard_entry_update(session.pid, PR_SCORE_USER, session.user, PR_SCORE_CWD, session.cwd, NULL); pr_session_set_idle(); pr_timer_remove(PR_TIMER_LOGIN, &auth_module); /* These copies are made from the session.pool, instead of the more * volatile pool used originally, in order that the copied data maintain * its integrity for the lifetime of the session. */ session.user = pstrdup(session.pool, session.user); if (session.group) session.group = pstrdup(session.pool, session.group); if (session.gids) session.gids = copy_array(session.pool, session.gids); /* session.groups is an array of strings, so we must copy the string data * as well as the pointers. */ session.groups = copy_array_str(session.pool, session.groups); /* Resolve any deferred-resolution paths in the FS layer */ pr_resolve_fs_map(); return 1; auth_failure: if (pass) pr_memscrub(pass, strlen(pass)); session.user = session.group = NULL; session.gids = session.groups = NULL; session.wtmp_log = FALSE; return 0; } /* This function counts the number of connected users. It only fills in the * Class-based counters and an estimate for the number of clients. The primary * purpose is to make it so that the %N/%y escapes work in a DisplayConnect * greeting. A secondary purpose is to enforce any configured * MaxConnectionsPerHost limit. */ static int auth_scan_scoreboard(void) { char *key; void *v; config_rec *c = NULL; pr_scoreboard_entry_t *score = NULL; unsigned int cur = 0, ccur = 0, hcur = 0; char curr_server_addr[80] = {'\0'}; const char *client_addr = pr_netaddr_get_ipstr(session.c->remote_addr); snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; /* Determine how many users are currently connected */ if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { pr_signals_handle(); /* Make sure it matches our current server */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { cur++; if (strcmp(score->sce_client_addr, client_addr) == 0) hcur++; /* Only count up authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) continue; /* Note: the class member of the scoreboard entry will never be * NULL. At most, it may be the empty string. */ if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Lookup any configured MaxConnectionsPerHost. */ c = find_config(main_server->conf, CONF_PARAM, "MaxConnectionsPerHost", FALSE); if (c) { unsigned int *max = c->argv[0]; if (*max && hcur > *max) { char maxstr[20]; char *msg = "Sorry, the maximum number of connections (%m) for your host " "are already connected."; pr_event_generate("mod_auth.max-connections-per-host", session.c); if (c->argc == 2) msg = c->argv[1]; memset(maxstr, '\0', sizeof(maxstr)); snprintf(maxstr, sizeof(maxstr), "%u", *max); maxstr[sizeof(maxstr)-1] = '\0'; pr_response_send(R_530, "%s", sreplace(session.pool, msg, "%m", maxstr, NULL)); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxConnectionsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxConnectionsPerHost"); } } return 0; } static int have_client_limits(cmd_rec *cmd) { if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerClass", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE) != NULL) { return TRUE; } return FALSE; } static int auth_count_scoreboard(cmd_rec *cmd, char *user) { char *key; void *v; pr_scoreboard_entry_t *score = NULL; long cur = 0, hcur = 0, ccur = 0, hostsperuser = 1, usersessions = 0; config_rec *c = NULL, *maxc = NULL; /* First, check to see which Max* directives are configured. If none * are configured, then there is no need for us to needlessly scan the * ScoreboardFile. */ if (have_client_limits(cmd) == FALSE) { return 0; } /* Determine how many users are currently connected. */ /* We use this call to get the possibly-changed user name. */ (void) pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Gather our statistics. */ if (user) { char curr_server_addr[80] = {'\0'}; snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { unsigned char same_host = FALSE; pr_signals_handle(); /* Make sure it matches our current server. */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { if ((c && c->config_type == CONF_ANON && !strcmp(score->sce_user, user)) || !c) { /* This small hack makes sure that cur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c && c->config_type == CONF_ANON && cur == 0) cur = 1; /* Only count authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) continue; cur++; /* Count up sessions on a per-host basis. */ if (!strcmp(score->sce_client_addr, pr_netaddr_get_ipstr(session.c->remote_addr))) { same_host = TRUE; /* This small hack makes sure that hcur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c && c->config_type == CONF_ANON && hcur == 0) hcur = 1; hcur++; } /* Take a per-user count of connections. */ if (strcmp(score->sce_user, user) == 0) { usersessions++; /* Count up unique hosts. */ if (!same_host) hostsperuser++; } } if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); PRIVS_RELINQUISH } key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Try to determine what MaxClients/MaxHosts limits apply to this session * (if any) and count through the runtime file to see if this limit would * be exceeded. */ maxc = find_config(cmd->server->conf, CONF_PARAM, "MaxClientsPerClass", FALSE); while (session.conn_class != NULL && maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your class " "are already connected."; unsigned int *max = maxc->argv[1]; if (strcmp(maxc->argv[0], session.conn_class->cls_name) != 0) { maxc = find_config_next(maxc, maxc->next, CONF_PARAM, "MaxClientsPerClass", FALSE); continue; } if (maxc->argc > 2) maxstr = maxc->argv[2]; if (*max && ccur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-class", session.conn_class->cls_name); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerClass %s %u)", session.conn_class->cls_name, *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerClass"); } break; } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your host " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) maxstr = maxc->argv[1]; if (*max && hcur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-host", session.c); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerHost"); } } /* Check for any configured MaxClientsPerUser. */ maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) for this user " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) maxstr = maxc->argv[1]; if (*max && usersessions > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerUser %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerUser"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of allowed clients (%m) are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) maxstr = maxc->argv[1]; if (*max && cur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients", NULL); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClients %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClients"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of hosts (%m) for this user are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) maxstr = maxc->argv[1]; if (*max && hostsperuser > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-hosts-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxHostsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxHostsPerUser"); } } return 0; } MODRET auth_pre_user(cmd_rec *cmd) { if (logged_in) return PR_DECLINED(cmd); /* Close the passwd and group databases, because libc won't let us see new * entries to these files without this (only in PersistentPasswd mode). */ pr_auth_endpwent(cmd->tmp_pool); pr_auth_endgrent(cmd->tmp_pool); /* Check for a user name that exceeds PR_TUNABLE_LOGIN_MAX. */ if (strlen(cmd->arg) > PR_TUNABLE_LOGIN_MAX) { pr_log_pri(PR_LOG_NOTICE, "USER %s (Login failed): " "maximum USER length exceeded", cmd->arg); pr_response_add_err(R_501, _("Login incorrect.")); return PR_ERROR(cmd); } return PR_DECLINED(cmd); } MODRET auth_user(cmd_rec *cmd) { int nopass = FALSE; config_rec *c; char *denymsg = NULL, *user, *origuser; int failnopwprompt = 0, aclp, i; unsigned char *anon_require_passwd = NULL, *login_passwd_prompt = NULL; if (cmd->argc < 2) { return PR_ERROR_MSG(cmd, R_500, _("USER: command requires a parameter")); } if (logged_in) { /* If the client has already authenticated, BUT the given USER command * here is for the exact same user name, then allow the command to * succeed (Bug#4217). */ origuser = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (origuser != NULL && strcmp(origuser, cmd->arg) == 0) { pr_response_add(R_230, _("User %s logged in"), origuser); return PR_HANDLED(cmd); } pr_response_add_err(R_501, "%s", _("Reauthentication not supported")); return PR_ERROR(cmd); } user = cmd->arg; (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (pr_table_add_dup(session.notes, "mod_auth.orig-user", user, 0) < 0) { pr_log_debug(DEBUG3, "error stashing 'mod_auth.orig-user' in " "session.notes: %s", strerror(errno)); } origuser = user; c = pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Check for AccessDenyMsg */ denymsg = get_param_ptr((c ? c->subset : cmd->server->conf), "AccessDenyMsg", FALSE); if (denymsg != NULL) { if (strstr(denymsg, "%u") != NULL) { denymsg = sreplace(cmd->tmp_pool, denymsg, "%u", user, NULL); } } login_passwd_prompt = get_param_ptr( (c && c->config_type == CONF_ANON) ? c->subset : main_server->conf, "LoginPasswordPrompt", FALSE); if (login_passwd_prompt && *login_passwd_prompt == FALSE) { failnopwprompt = TRUE; } else { failnopwprompt = FALSE; } if (failnopwprompt) { if (!user) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_pri(PR_LOG_NOTICE, "USER %s (Login failed): Not a UserAlias", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, _("Login incorrect.")); } pr_session_end(0); } aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); if (c && c->config_type != CONF_ANON) { c = (config_rec *) pcalloc(session.pool, sizeof(config_rec)); c->config_type = CONF_ANON; c->name = ""; /* don't really need this yet */ c->subset = main_server->conf; } if (c) { if (!login_check_limits(c->subset, FALSE, TRUE, &i) || (!aclp && !i) ) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_auth(PR_LOG_NOTICE, "ANON %s: Limit access denies login", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, _("Login incorrect.")); } pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by <Limit LOGIN>"); } } if (c == NULL && aclp == 0) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_auth(PR_LOG_NOTICE, "USER %s: Limit access denies login", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, "%s", _("Login incorrect.")); } pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by <Limit LOGIN>"); } } if (c) anon_require_passwd = get_param_ptr(c->subset, "AnonRequirePassword", FALSE); if (c && user && (!anon_require_passwd || *anon_require_passwd == FALSE)) nopass = TRUE; session.gids = NULL; session.groups = NULL; session.user = NULL; session.group = NULL; if (nopass) { pr_response_add(R_331, _("Anonymous login ok, send your complete email " "address as your password")); } else if (pr_auth_requires_pass(cmd->tmp_pool, user) == FALSE) { /* Check to see if a password from the client is required. In the * vast majority of cases, a password will be required. */ /* Act as if we received a PASS command from the client. */ cmd_rec *fakecmd = pr_cmd_alloc(cmd->pool, 2, NULL); /* We use pstrdup() here, rather than assigning C_PASS directly, since * code elsewhere will attempt to modify this buffer, and C_PASS is * a string literal. */ fakecmd->argv[0] = pstrdup(fakecmd->pool, C_PASS); fakecmd->argv[1] = NULL; fakecmd->arg = NULL; c = add_config_param_set(&cmd->server->conf, "authenticated", 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = TRUE; authenticated_without_pass = TRUE; pr_log_auth(PR_LOG_NOTICE, "USER %s: Authenticated without password", user); pr_cmd_dispatch(fakecmd); } else { pr_response_add(R_331, _("Password required for %s"), cmd->argv[1]); } return PR_HANDLED(cmd); } /* Close the passwd and group databases, similar to auth_pre_user(). */ MODRET auth_pre_pass(cmd_rec *cmd) { char *displaylogin; pr_auth_endpwent(cmd->tmp_pool); pr_auth_endgrent(cmd->tmp_pool); /* Look for a DisplayLogin file which has an absolute path. If we find one, * open a filehandle, such that that file can be displayed even if the * session is chrooted. DisplayLogin files with relative paths will be * handled after chroot, preserving the old behavior. */ displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin && *displaylogin == '/') { struct stat st; displaylogin_fh = pr_fsio_open(displaylogin, O_RDONLY); if (displaylogin_fh == NULL) { pr_log_debug(DEBUG6, "unable to open DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } else { if (pr_fsio_fstat(displaylogin_fh, &st) < 0) { pr_log_debug(DEBUG6, "unable to stat DisplayLogin file '%s': %s", displaylogin, strerror(errno)); pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } else { if (S_ISDIR(st.st_mode)) { errno = EISDIR; pr_log_debug(DEBUG6, "unable to use DisplayLogin file '%s': %s", displaylogin, strerror(errno)); pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } } } } return PR_DECLINED(cmd); } MODRET auth_pass(cmd_rec *cmd) { char *user = NULL; int res = 0; if (logged_in) return PR_ERROR_MSG(cmd, R_503, _("You are already logged in")); user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (!user) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); return PR_ERROR_MSG(cmd, R_503, _("Login with USER first")); } /* Clear any potentially cached directory config */ session.anon_config = NULL; session.dir_config = NULL; res = setup_env(cmd->tmp_pool, cmd, user, cmd->arg); if (res == 1) { config_rec *c = NULL; c = add_config_param_set(&cmd->server->conf, "authenticated", 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = TRUE; set_auth_check(NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (session.sf_flags & SF_ANON) { if (pr_table_add_dup(session.notes, "mod_auth.anon-passwd", pr_fs_decode_path(cmd->server->pool, cmd->arg), 0) < 0) { pr_log_debug(DEBUG3, "error stashing anonymous password in session.notes: %s", strerror(errno)); } } logged_in = 1; return PR_HANDLED(cmd); } (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (res == 0) { unsigned int max_logins, *max = NULL; char *denymsg = NULL; /* check for AccessDenyMsg */ if ((denymsg = get_param_ptr((session.anon_config ? session.anon_config->subset : cmd->server->conf), "AccessDenyMsg", FALSE)) != NULL) { if (strstr(denymsg, "%u") != NULL) { denymsg = sreplace(cmd->tmp_pool, denymsg, "%u", user, NULL); } } max = get_param_ptr(main_server->conf, "MaxLoginAttempts", FALSE); if (max != NULL) { max_logins = *max; } else { max_logins = 3; } if (max_logins > 0 && ++auth_tries >= max_logins) { if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, "%s", _("Login incorrect.")); } pr_log_auth(PR_LOG_NOTICE, "Maximum login attempts (%u) exceeded, connection refused", max_logins); /* Generate an event about this limit being exceeded. */ pr_event_generate("mod_auth.max-login-attempts", session.c); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxLoginAttempts"); } return PR_ERROR_MSG(cmd, R_530, denymsg ? denymsg : _("Login incorrect.")); } return PR_HANDLED(cmd); } MODRET auth_acct(cmd_rec *cmd) { pr_response_add(R_502, _("ACCT command not implemented")); return PR_HANDLED(cmd); } MODRET auth_rein(cmd_rec *cmd) { pr_response_add(R_502, _("REIN command not implemented")); return PR_HANDLED(cmd); } /* Configuration handlers */ MODRET set_accessdenymsg(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_accessgrantmsg(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: AllowChrootSymlinks on|off */ MODRET set_allowchrootsymlinks(cmd_rec *cmd) { int b = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); b = get_boolean(cmd, 1); if (b == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = b; return PR_HANDLED(cmd); } MODRET set_anonrequirepassword(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_anonrejectpasswords(cmd_rec *cmd) { #ifdef PR_USE_REGEX pr_regex_t *pre = NULL; int res; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); pre = pr_regexp_alloc(&auth_module); res = pr_regexp_compile(pre, cmd->argv[1], REG_EXTENDED|REG_NOSUB); if (res != 0) { char errstr[200] = {'\0'}; pr_regexp_error(res, pre, errstr, 200); pr_regexp_free(NULL, pre); CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "Unable to compile regex '", cmd->argv[1], "': ", errstr, NULL)); } (void) add_config_param(cmd->argv[0], 1, (void *) pre); return PR_HANDLED(cmd); #else CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0], " directive " "cannot be used on this system, as you do not have POSIX compliant " "regex support", NULL)); #endif } MODRET set_authaliasonly(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_authusingalias(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_createhome(cmd_rec *cmd) { int bool = -1, start = 2; mode_t mode = (mode_t) 0700, dirmode = (mode_t) 0711; char *skel_path = NULL; config_rec *c = NULL; uid_t cuid = 0; gid_t cgid = 0, hgid = -1; unsigned long flags = 0UL; if (cmd->argc-1 < 1) { CONF_ERROR(cmd, "wrong number of parameters"); } CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } /* No need to process the rest if bool is FALSE. */ if (bool == FALSE) { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } /* Check the mode parameter, if present */ if (cmd->argc-1 >= 2 && strcasecmp(cmd->argv[2], "dirmode") != 0 && strcasecmp(cmd->argv[2], "skel") != 0) { char *tmp = NULL; mode = strtol(cmd->argv[2], &tmp, 8); if (tmp && *tmp) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": bad mode parameter: '", cmd->argv[2], "'", NULL)); start = 3; } if (cmd->argc-1 > 2) { register unsigned int i; /* Cycle through the rest of the parameters */ for (i = start; i < cmd->argc;) { if (strcasecmp(cmd->argv[i], "skel") == 0) { struct stat st; /* Check that the skel directory, if configured, meets the * requirements. */ skel_path = cmd->argv[++i]; if (*skel_path != '/') { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "skel path '", skel_path, "' is not a full path", NULL)); } if (pr_fsio_stat(skel_path, &st) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to stat '", skel_path, "': ", strerror(errno), NULL)); } if (!S_ISDIR(st.st_mode)) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", skel_path, "' is not a directory", NULL)); } /* Must not be world-writable. */ if (st.st_mode & S_IWOTH) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", skel_path, "' is world-writable", NULL)); } /* Move the index past the skel parameter */ i++; } else if (strcasecmp(cmd->argv[i], "dirmode") == 0) { char *tmp = NULL; dirmode = strtol(cmd->argv[++i], &tmp, 8); if (tmp && *tmp) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad mode parameter: '", cmd->argv[i], "'", NULL)); /* Move the index past the dirmode parameter */ i++; } else if (strcasecmp(cmd->argv[i], "uid") == 0) { /* Check for a "~" parameter. */ if (strncmp(cmd->argv[i+1], "~", 2) != 0) { char *tmp = NULL; uid_t uid; uid = strtol(cmd->argv[++i], &tmp, 10); if (tmp && *tmp) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad UID parameter: '", cmd->argv[i], "'", NULL)); } cuid = uid; } else { cuid = (uid_t) -1; i++; } /* Move the index past the uid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "gid") == 0) { /* Check for a "~" parameter. */ if (strncmp(cmd->argv[i+1], "~", 2) != 0) { char *tmp = NULL; gid_t gid; gid = strtol(cmd->argv[++i], &tmp, 10); if (tmp && *tmp) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad GID parameter: '", cmd->argv[i], "'", NULL)); } cgid = gid; } else { cgid = (gid_t) -1; i++; } /* Move the index past the gid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "homegid") == 0) { char *tmp = NULL; gid_t gid; gid = strtol(cmd->argv[++i], &tmp, 10); if (tmp && *tmp) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad GID parameter: '", cmd->argv[i], "'", NULL)); } hgid = gid; /* Move the index past the homegid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "NoRootPrivs") == 0) { flags |= PR_MKHOME_FL_USE_USER_PRIVS; i++; } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown parameter: '", cmd->argv[i], "'", NULL)); } } } c = add_config_param(cmd->argv[0], 8, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->argv[1] = pcalloc(c->pool, sizeof(mode_t)); *((mode_t *) c->argv[1]) = mode; c->argv[2] = pcalloc(c->pool, sizeof(mode_t)); *((mode_t *) c->argv[2]) = dirmode; if (skel_path) { c->argv[3] = pstrdup(c->pool, skel_path); } c->argv[4] = pcalloc(c->pool, sizeof(uid_t)); *((uid_t *) c->argv[4]) = cuid; c->argv[5] = pcalloc(c->pool, sizeof(gid_t)); *((gid_t *) c->argv[5]) = cgid; c->argv[6] = pcalloc(c->pool, sizeof(gid_t)); *((gid_t *) c->argv[6]) = hgid; c->argv[7] = pcalloc(c->pool, sizeof(unsigned long)); *((unsigned long *) c->argv[7]) = flags; return PR_HANDLED(cmd); } MODRET add_defaultroot(cmd_rec *cmd) { config_rec *c; char *dir,**argv; int argc; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (cmd->argc < 2) CONF_ERROR(cmd,"syntax: DefaultRoot <directory> [<group-expression>]"); argv = cmd->argv; argc = cmd->argc - 2; dir = *++argv; /* dir must be / or ~. */ if (*dir != '/' && *dir != '~') CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") absolute pathname " "required", NULL)); if (strchr(dir, '*')) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); if (*(dir + strlen(dir) - 1) != '/') dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); acl = pr_expr_create(cmd->tmp_pool, &argc, argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(char *)); argv = (char **) c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } *argv = NULL; return PR_HANDLED(cmd); } MODRET add_defaultchdir(cmd_rec *cmd) { config_rec *c; char *dir,**argv; int argc; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2) CONF_ERROR(cmd, "syntax: DefaultChdir <directory> [<group-expression>]"); argv = cmd->argv; argc = cmd->argc - 2; dir = *++argv; if (strchr(dir, '*')) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); if (*(dir + strlen(dir) - 1) != '/') dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); acl = pr_expr_create(cmd->tmp_pool, &argc, argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(char *)); argv = (char **) c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } *argv = NULL; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_displaylogin(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_grouppassword(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_loginpasswordprompt(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerClass class max|"none" ["message"] */ MODRET set_maxclientsclass(cmd_rec *cmd) { int max; config_rec *c; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[2], "none") == 0) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[2], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "max must be 'none' or a number greater than 0"); } if (cmd->argc == 4) { c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL); c->argv[0] = pstrdup(c->pool, cmd->argv[1]); c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = max; c->argv[2] = pstrdup(c->pool, cmd->argv[3]); } else { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pstrdup(c->pool, cmd->argv[1]); c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = max; } return PR_HANDLED(cmd); } /* usage: MaxClients max|"none" ["message"] */ MODRET set_maxclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerHost max|"none" ["message"] */ MODRET set_maxhostclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerUser max|"none" ["message"] */ MODRET set_maxuserclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxConnectionsPerHost max|"none" ["message"] */ MODRET set_maxconnectsperhost(cmd_rec *cmd) { int max; config_rec *c; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[1], "none") == 0) max = 0; else { char *tmp = NULL; max = (int) strtol(cmd->argv[1], &tmp, 10); if ((tmp && *tmp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; return PR_HANDLED(cmd); } /* usage: MaxHostsPerUser max|"none" ["message"] */ MODRET set_maxhostsperuser(cmd_rec *cmd) { int max; config_rec *c = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_maxloginattempts(cmd_rec *cmd) { int max; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[1], "none") == 0) { max = 0; } else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; return PR_HANDLED(cmd); } MODRET set_requirevalidshell(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: RewriteHome on|off */ MODRET set_rewritehome(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_rootlogin(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd,1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = (unsigned char) bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: RootRevoke on|off|UseNonCompliantActiveTransfer */ MODRET set_rootrevoke(cmd_rec *cmd) { int root_revoke = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* A RootRevoke value of 0 indicates 'false', 1 indicates 'true', and * 2 indicates 'NonCompliantActiveTransfer'. */ root_revoke = get_boolean(cmd, 1); if (root_revoke == -1) { if (strcasecmp(cmd->argv[1], "UseNonCompliantActiveTransfer") != 0 && strcasecmp(cmd->argv[1], "UseNonCompliantActiveTransfers") != 0) { CONF_ERROR(cmd, "expected Boolean parameter"); } root_revoke = 2; } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = (unsigned char) root_revoke; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_timeoutlogin(cmd_rec *cmd) { int timeout = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; return PR_HANDLED(cmd); } MODRET set_timeoutsession(cmd_rec *cmd) { int timeout = 0, precedence = 0; config_rec *c = NULL; int ctxt = (cmd->config && cmd->config->config_type != CONF_PARAM ? cmd->config->config_type : cmd->server->config_type ? cmd->server->config_type : CONF_ROOT); /* this directive must have either 1 or 3 arguments */ if (cmd->argc-1 != 1 && cmd->argc-1 != 3) CONF_ERROR(cmd, "missing arguments"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Set the precedence for this config_rec based on its configuration * context. */ if (ctxt & CONF_GLOBAL) { precedence = 1; /* These will never appear simultaneously */ } else if ((ctxt & CONF_ROOT) || (ctxt & CONF_VIRTUAL)) { precedence = 2; } else if (ctxt & CONF_ANON) { precedence = 3; } if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } if (timeout == 0) { /* do nothing */ return PR_HANDLED(cmd); } if (cmd->argc-1 == 3) { if (strncmp(cmd->argv[2], "user", 5) == 0 || strncmp(cmd->argv[2], "group", 6) == 0 || strncmp(cmd->argv[2], "class", 6) == 0) { /* no op */ } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[0], ": unknown classifier used: '", cmd->argv[2], "'", NULL)); } } if (cmd->argc-1 == 1) { c = add_config_param(cmd->argv[0], 2, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = precedence; } else if (cmd->argc-1 == 3) { array_header *acl = NULL; int argc = cmd->argc - 3; char **argv = cmd->argv + 2; acl = pr_expr_create(cmd->tmp_pool, &argc, argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 2; /* add 3 to argc for the argv of the config_rec: one for the * seconds value, one for the precedence, one for the classifier, * and one for the terminating NULL */ c->argv = pcalloc(c->pool, ((argc + 4) * sizeof(char *))); /* capture the config_rec's argv pointer for doing the by-hand * population */ argv = (char **) c->argv; /* Copy in the seconds. */ *argv = pcalloc(c->pool, sizeof(int)); *((int *) *argv++) = timeout; /* Copy in the precedence. */ *argv = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) *argv++) = precedence; /* Copy in the classifier. */ *argv++ = pstrdup(c->pool, cmd->argv[2]); /* now, copy in the expression arguments */ if (argc && acl) { while (argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } } /* don't forget the terminating NULL */ *argv = NULL; } else { /* Should never reach here. */ CONF_ERROR(cmd, "wrong number of parameters"); } c->flags |= CF_MERGEDOWN_MULTI; return PR_HANDLED(cmd); } MODRET set_useftpusers(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: UseLastlog on|off */ MODRET set_uselastlog(cmd_rec *cmd) { #ifdef PR_USE_LASTLOG int bool; config_rec *c; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); #else CONF_ERROR(cmd, "requires lastlog support (--with-lastlog)"); #endif /* PR_USE_LASTLOG */ } /* usage: UserAlias alias real-user */ MODRET set_useralias(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Make sure that the given names differ. */ if (strcmp(cmd->argv[1], cmd->argv[2]) == 0) CONF_ERROR(cmd, "alias and real user names must differ"); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); /* Note: only merge this directive down if it is not appearing in an * <Anonymous> context. */ if (!check_context(cmd, CONF_ANON)) { c->flags |= CF_MERGEDOWN_MULTI; } return PR_HANDLED(cmd); } MODRET set_userdirroot(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_userpassword(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* Module API tables */ static conftable auth_conftab[] = { { "AccessDenyMsg", set_accessdenymsg, NULL }, { "AccessGrantMsg", set_accessgrantmsg, NULL }, { "AllowChrootSymlinks", set_allowchrootsymlinks, NULL }, { "AnonRequirePassword", set_anonrequirepassword, NULL }, { "AnonRejectPasswords", set_anonrejectpasswords, NULL }, { "AuthAliasOnly", set_authaliasonly, NULL }, { "AuthUsingAlias", set_authusingalias, NULL }, { "CreateHome", set_createhome, NULL }, { "DefaultChdir", add_defaultchdir, NULL }, { "DefaultRoot", add_defaultroot, NULL }, { "DisplayLogin", set_displaylogin, NULL }, { "GroupPassword", set_grouppassword, NULL }, { "LoginPasswordPrompt", set_loginpasswordprompt, NULL }, { "MaxClients", set_maxclients, NULL }, { "MaxClientsPerClass", set_maxclientsclass, NULL }, { "MaxClientsPerHost", set_maxhostclients, NULL }, { "MaxClientsPerUser", set_maxuserclients, NULL }, { "MaxConnectionsPerHost", set_maxconnectsperhost, NULL }, { "MaxHostsPerUser", set_maxhostsperuser, NULL }, { "MaxLoginAttempts", set_maxloginattempts, NULL }, { "RequireValidShell", set_requirevalidshell, NULL }, { "RewriteHome", set_rewritehome, NULL }, { "RootLogin", set_rootlogin, NULL }, { "RootRevoke", set_rootrevoke, NULL }, { "TimeoutLogin", set_timeoutlogin, NULL }, { "TimeoutSession", set_timeoutsession, NULL }, { "UseFtpUsers", set_useftpusers, NULL }, { "UseLastlog", set_uselastlog, NULL }, { "UserAlias", set_useralias, NULL }, { "UserDirRoot", set_userdirroot, NULL }, { "UserPassword", set_userpassword, NULL }, { NULL, NULL, NULL } }; static cmdtable auth_cmdtab[] = { { PRE_CMD, C_USER, G_NONE, auth_pre_user, FALSE, FALSE, CL_AUTH }, { CMD, C_USER, G_NONE, auth_user, FALSE, FALSE, CL_AUTH }, { PRE_CMD, C_PASS, G_NONE, auth_pre_pass, FALSE, FALSE, CL_AUTH }, { CMD, C_PASS, G_NONE, auth_pass, FALSE, FALSE, CL_AUTH }, { POST_CMD, C_PASS, G_NONE, auth_post_pass, FALSE, FALSE, CL_AUTH }, { LOG_CMD, C_PASS, G_NONE, auth_log_pass, FALSE, FALSE }, { LOG_CMD_ERR,C_PASS, G_NONE, auth_err_pass, FALSE, FALSE }, { CMD, C_ACCT, G_NONE, auth_acct, FALSE, FALSE, CL_AUTH }, { CMD, C_REIN, G_NONE, auth_rein, FALSE, FALSE, CL_AUTH }, { POST_CMD, C_HOST, G_NONE, auth_post_host, FALSE, FALSE }, { 0, NULL } }; /* Module interface */ module auth_module = { NULL, NULL, /* Module API version */ 0x20, /* Module name */ "auth", /* Module configuration directive table */ auth_conftab, /* Module command handler table */ auth_cmdtab, /* Module authentication handler table */ NULL, /* Module initialization function */ auth_init, /* Session initialization function */ auth_sess_init };
./CrossVul/dataset_final_sorted/CWE-59/c/good_3262_0
crossvul-cpp_data_good_1471_2
/* * lxc: linux Container library * * (C) Copyright IBM Corp. 2007, 2008 * * Authors: * Daniel Lezcano <daniel.lezcano at free.fr> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <dirent.h> #include <fcntl.h> #include <ctype.h> #include <pthread.h> #include <grp.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/param.h> #include <sys/inotify.h> #include <sys/mount.h> #include <netinet/in.h> #include <net/if.h> #include <poll.h> #include "error.h" #include "commands.h" #include "list.h" #include "conf.h" #include "utils.h" #include "bdev.h" #include "log.h" #include "cgroup.h" #include "start.h" #include "state.h" #define CGM_SUPPORTS_GET_ABS 3 #define CGM_SUPPORTS_NAMED 4 #define CGM_SUPPORTS_MULT_CONTROLLERS 10 #ifdef HAVE_CGMANAGER lxc_log_define(lxc_cgmanager, lxc); #include <nih-dbus/dbus_connection.h> #include <cgmanager/cgmanager-client.h> #include <nih/alloc.h> #include <nih/error.h> #include <nih/string.h> struct cgm_data { char *name; char *cgroup_path; const char *cgroup_pattern; }; static pthread_mutex_t cgm_mutex = PTHREAD_MUTEX_INITIALIZER; static void lock_mutex(pthread_mutex_t *l) { int ret; if ((ret = pthread_mutex_lock(l)) != 0) { fprintf(stderr, "pthread_mutex_lock returned:%d %s\n", ret, strerror(ret)); exit(1); } } static void unlock_mutex(pthread_mutex_t *l) { int ret; if ((ret = pthread_mutex_unlock(l)) != 0) { fprintf(stderr, "pthread_mutex_unlock returned:%d %s\n", ret, strerror(ret)); exit(1); } } void cgm_lock(void) { lock_mutex(&cgm_mutex); } void cgm_unlock(void) { unlock_mutex(&cgm_mutex); } #ifdef HAVE_PTHREAD_ATFORK __attribute__((constructor)) static void process_lock_setup_atfork(void) { pthread_atfork(cgm_lock, cgm_unlock, cgm_unlock); } #endif static NihDBusProxy *cgroup_manager = NULL; static int32_t api_version; static struct cgroup_ops cgmanager_ops; static int nr_subsystems; static char **subsystems, **subsystems_inone; static bool dbus_threads_initialized = false; static void cull_user_controllers(void); static void cgm_dbus_disconnect(void) { if (cgroup_manager) { dbus_connection_flush(cgroup_manager->connection); dbus_connection_close(cgroup_manager->connection); nih_free(cgroup_manager); } cgroup_manager = NULL; cgm_unlock(); } #define CGMANAGER_DBUS_SOCK "unix:path=/sys/fs/cgroup/cgmanager/sock" static bool cgm_dbus_connect(void) { DBusError dbus_error; static DBusConnection *connection; cgm_lock(); if (!dbus_threads_initialized) { // tell dbus to do struct locking for thread safety dbus_threads_init_default(); dbus_threads_initialized = true; } dbus_error_init(&dbus_error); connection = dbus_connection_open_private(CGMANAGER_DBUS_SOCK, &dbus_error); if (!connection) { DEBUG("Failed opening dbus connection: %s: %s", dbus_error.name, dbus_error.message); dbus_error_free(&dbus_error); cgm_unlock(); return false; } dbus_connection_set_exit_on_disconnect(connection, FALSE); dbus_error_free(&dbus_error); cgroup_manager = nih_dbus_proxy_new(NULL, connection, NULL /* p2p */, "/org/linuxcontainers/cgmanager", NULL, NULL); dbus_connection_unref(connection); if (!cgroup_manager) { NihError *nerr; nerr = nih_error_get(); ERROR("Error opening cgmanager proxy: %s", nerr->message); nih_free(nerr); cgm_dbus_disconnect(); return false; } // get the api version if (cgmanager_get_api_version_sync(NULL, cgroup_manager, &api_version) != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("Error cgroup manager api version: %s", nerr->message); nih_free(nerr); cgm_dbus_disconnect(); return false; } if (api_version < CGM_SUPPORTS_NAMED) cull_user_controllers(); return true; } static bool cgm_supports_multiple_controllers; /* * if cgm_all_controllers_same is true, then cgm_supports_multiple_controllers * is true */ static bool cgm_all_controllers_same; /* * Check whether we can use "all" when talking to cgmanager. * We check two things: * 1. whether cgmanager is new enough to support this. * 2. whether the task we are interested in is in the same * cgroup for all controllers. * In cgm_init (before an lxc-start) we care about our own * cgroup. In cgm_attach, we care about the target task's * cgroup. */ static void check_supports_multiple_controllers(pid_t pid) { FILE *f; char *line = NULL, *prevpath = NULL; size_t sz = 0; char path[100]; cgm_supports_multiple_controllers = false; cgm_all_controllers_same = false; if (api_version < CGM_SUPPORTS_MULT_CONTROLLERS) { cgm_supports_multiple_controllers = false; return; } cgm_supports_multiple_controllers = true; if (pid == -1) sprintf(path, "/proc/self/cgroup"); else sprintf(path, "/proc/%d/cgroup", pid); f = fopen(path, "r"); if (!f) return; cgm_all_controllers_same = true; while (getline(&line, &sz, f) != -1) { /* file format: hierarchy:subsystems:group */ char *colon; if (!line[0]) continue; colon = strchr(line, ':'); if (!colon) continue; colon = strchr(colon+1, ':'); if (!colon) continue; colon++; if (!prevpath) { prevpath = alloca(strlen(colon)+1); strcpy(prevpath, colon); continue; } if (strcmp(prevpath, colon) != 0) { cgm_all_controllers_same = false; break; } } fclose(f); free(line); } static int send_creds(int sock, int rpid, int ruid, int rgid) { struct msghdr msg = { 0 }; struct iovec iov; struct cmsghdr *cmsg; struct ucred cred = { .pid = rpid, .uid = ruid, .gid = rgid, }; char cmsgbuf[CMSG_SPACE(sizeof(cred))]; char buf[1]; buf[0] = 'p'; msg.msg_control = cmsgbuf; msg.msg_controllen = sizeof(cmsgbuf); cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred)); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_CREDENTIALS; memcpy(CMSG_DATA(cmsg), &cred, sizeof(cred)); msg.msg_name = NULL; msg.msg_namelen = 0; iov.iov_base = buf; iov.iov_len = sizeof(buf); msg.msg_iov = &iov; msg.msg_iovlen = 1; if (sendmsg(sock, &msg, 0) < 0) return -1; return 0; } static bool lxc_cgmanager_create(const char *controller, const char *cgroup_path, int32_t *existed) { bool ret = true; if ( cgmanager_create_sync(NULL, cgroup_manager, controller, cgroup_path, existed) != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("call to cgmanager_create_sync failed: %s", nerr->message); nih_free(nerr); ERROR("Failed to create %s:%s", controller, cgroup_path); ret = false; } return ret; } /* * Escape to the root cgroup if we are root, so that the container will * be in "/lxc/c1" rather than "/user/..../c1" * called internally with connection already open */ static bool lxc_cgmanager_escape(void) { bool ret = true; pid_t me = getpid(); char **slist = subsystems; int i; if (cgm_all_controllers_same) slist = subsystems_inone; for (i = 0; slist[i]; i++) { if (cgmanager_move_pid_abs_sync(NULL, cgroup_manager, slist[i], "/", me) != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("call to cgmanager_move_pid_abs_sync(%s) failed: %s", slist[i], nerr->message); nih_free(nerr); ret = false; break; } } return ret; } struct chown_data { const char *cgroup_path; uid_t origuid; }; static int do_chown_cgroup(const char *controller, const char *cgroup_path, uid_t newuid) { int sv[2] = {-1, -1}, optval = 1, ret = -1; char buf[1]; struct pollfd fds; if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sv) < 0) { SYSERROR("Error creating socketpair"); goto out; } if (setsockopt(sv[1], SOL_SOCKET, SO_PASSCRED, &optval, sizeof(optval)) == -1) { SYSERROR("setsockopt failed"); goto out; } if (setsockopt(sv[0], SOL_SOCKET, SO_PASSCRED, &optval, sizeof(optval)) == -1) { SYSERROR("setsockopt failed"); goto out; } if ( cgmanager_chown_scm_sync(NULL, cgroup_manager, controller, cgroup_path, sv[1]) != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("call to cgmanager_chown_scm_sync failed: %s", nerr->message); nih_free(nerr); goto out; } /* now send credentials */ fds.fd = sv[0]; fds.events = POLLIN; fds.revents = 0; if (poll(&fds, 1, -1) <= 0) { ERROR("Error getting go-ahead from server: %s", strerror(errno)); goto out; } if (read(sv[0], &buf, 1) != 1) { ERROR("Error getting reply from server over socketpair"); goto out; } if (send_creds(sv[0], getpid(), getuid(), getgid())) { SYSERROR("%s: Error sending pid over SCM_CREDENTIAL", __func__); goto out; } fds.fd = sv[0]; fds.events = POLLIN; fds.revents = 0; if (poll(&fds, 1, -1) <= 0) { ERROR("Error getting go-ahead from server: %s", strerror(errno)); goto out; } if (read(sv[0], &buf, 1) != 1) { ERROR("Error getting reply from server over socketpair"); goto out; } if (send_creds(sv[0], getpid(), newuid, 0)) { SYSERROR("%s: Error sending pid over SCM_CREDENTIAL", __func__); goto out; } fds.fd = sv[0]; fds.events = POLLIN; fds.revents = 0; if (poll(&fds, 1, -1) <= 0) { ERROR("Error getting go-ahead from server: %s", strerror(errno)); goto out; } ret = read(sv[0], buf, 1); out: close(sv[0]); close(sv[1]); if (ret == 1 && *buf == '1') return 0; return -1; } static int chown_cgroup_wrapper(void *data) { struct chown_data *arg = data; char **slist = subsystems; int i, ret = -1; uid_t destuid; if (setresgid(0,0,0) < 0) SYSERROR("Failed to setgid to 0"); if (setresuid(0,0,0) < 0) SYSERROR("Failed to setuid to 0"); if (setgroups(0, NULL) < 0) SYSERROR("Failed to clear groups"); cgm_dbus_disconnect(); if (!cgm_dbus_connect()) { ERROR("Error connecting to cgroup manager"); return -1; } destuid = get_ns_uid(arg->origuid); if (cgm_supports_multiple_controllers) slist = subsystems_inone; for (i = 0; slist[i]; i++) { if (do_chown_cgroup(slist[i], arg->cgroup_path, destuid) < 0) { ERROR("Failed to chown %s:%s to container root", slist[i], arg->cgroup_path); goto fail; } } ret = 0; fail: cgm_dbus_disconnect(); return ret; } /* Internal helper. Must be called with the cgmanager dbus socket open */ static bool lxc_cgmanager_chmod(const char *controller, const char *cgroup_path, const char *file, int mode) { if (cgmanager_chmod_sync(NULL, cgroup_manager, controller, cgroup_path, file, mode) != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("call to cgmanager_chmod_sync failed: %s", nerr->message); nih_free(nerr); return false; } return true; } /* Internal helper. Must be called with the cgmanager dbus socket open */ static bool chown_cgroup(const char *cgroup_path, struct lxc_conf *conf) { struct chown_data data; char **slist = subsystems; int i; if (lxc_list_empty(&conf->id_map)) /* If there's no mapping then we don't need to chown */ return true; data.cgroup_path = cgroup_path; data.origuid = geteuid(); /* Unpriv users can't chown it themselves, so chown from * a child namespace mapping both our own and the target uid */ if (userns_exec_1(conf, chown_cgroup_wrapper, &data) < 0) { ERROR("Error requesting cgroup chown in new namespace"); return false; } /* * Now chmod 775 the directory else the container cannot create cgroups. * This can't be done in the child namespace because it only group-owns * the cgroup */ if (cgm_supports_multiple_controllers) slist = subsystems_inone; for (i = 0; slist[i]; i++) { if (!lxc_cgmanager_chmod(slist[i], cgroup_path, "", 0775)) return false; if (!lxc_cgmanager_chmod(slist[i], cgroup_path, "tasks", 0775)) return false; if (!lxc_cgmanager_chmod(slist[i], cgroup_path, "cgroup.procs", 0775)) return false; } return true; } #define CG_REMOVE_RECURSIVE 1 /* Internal helper. Must be called with the cgmanager dbus socket open */ static void cgm_remove_cgroup(const char *controller, const char *path) { int existed; if ( cgmanager_remove_sync(NULL, cgroup_manager, controller, path, CG_REMOVE_RECURSIVE, &existed) != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("call to cgmanager_remove_sync failed: %s", nerr->message); nih_free(nerr); ERROR("Error removing %s:%s", controller, path); } if (existed == -1) INFO("cgroup removal attempt: %s:%s did not exist", controller, path); } static void *cgm_init(const char *name) { struct cgm_data *d; if (!cgm_dbus_connect()) { ERROR("Error connecting to cgroup manager"); return NULL; } check_supports_multiple_controllers(-1); d = malloc(sizeof(*d)); if (!d) { cgm_dbus_disconnect(); return NULL; } memset(d, 0, sizeof(*d)); d->name = strdup(name); if (!d->name) { cgm_dbus_disconnect(); goto err1; } d->cgroup_pattern = lxc_global_config_value("lxc.cgroup.pattern"); // cgm_create immediately gets called so keep the connection open return d; err1: free(d); return NULL; } /* Called after a failed container startup */ static void cgm_destroy(void *hdata) { struct cgm_data *d = hdata; char **slist = subsystems; int i; if (!d || !d->cgroup_path) return; if (!cgm_dbus_connect()) { ERROR("Error connecting to cgroup manager"); return; } if (cgm_supports_multiple_controllers) slist = subsystems_inone; for (i = 0; slist[i]; i++) cgm_remove_cgroup(slist[i], d->cgroup_path); free(d->name); free(d->cgroup_path); free(d); cgm_dbus_disconnect(); } /* * remove all the cgroups created * called internally with dbus connection open */ static inline void cleanup_cgroups(char *path) { int i; char **slist = subsystems; if (cgm_supports_multiple_controllers) slist = subsystems_inone; for (i = 0; slist[i]; i++) cgm_remove_cgroup(slist[i], path); } static inline bool cgm_create(void *hdata) { struct cgm_data *d = hdata; char **slist = subsystems; int i, index=0, baselen, ret; int32_t existed; char result[MAXPATHLEN], *tmp, *cgroup_path; if (!d) return false; // XXX we should send a hint to the cgmanager that when these // cgroups become empty they should be deleted. Requires a cgmanager // extension memset(result, 0, MAXPATHLEN); tmp = lxc_string_replace("%n", d->name, d->cgroup_pattern); if (!tmp) goto bad; if (strlen(tmp) >= MAXPATHLEN) { free(tmp); goto bad; } strcpy(result, tmp); baselen = strlen(result); free(tmp); tmp = result; while (*tmp == '/') tmp++; again: if (index == 100) { // turn this into a warn later ERROR("cgroup error? 100 cgroups with this name already running"); goto bad; } if (index) { ret = snprintf(result+baselen, MAXPATHLEN-baselen, "-%d", index); if (ret < 0 || ret >= MAXPATHLEN-baselen) goto bad; } existed = 0; if (cgm_supports_multiple_controllers) slist = subsystems_inone; for (i = 0; slist[i]; i++) { if (!lxc_cgmanager_create(slist[i], tmp, &existed)) { ERROR("Error creating cgroup %s:%s", slist[i], result); cleanup_cgroups(tmp); goto bad; } if (existed == 1) goto next; } // success cgroup_path = strdup(tmp); if (!cgroup_path) { cleanup_cgroups(tmp); goto bad; } d->cgroup_path = cgroup_path; cgm_dbus_disconnect(); return true; next: index++; goto again; bad: cgm_dbus_disconnect(); return false; } /* * Use the cgmanager to move a task into a cgroup for a particular * hierarchy. * All the subsystems in this hierarchy are co-mounted, so we only * need to transition the task into one of the cgroups * * Internal helper, must be called with cgmanager dbus socket open */ static bool lxc_cgmanager_enter(pid_t pid, const char *controller, const char *cgroup_path, bool abs) { int ret; if (abs) ret = cgmanager_move_pid_abs_sync(NULL, cgroup_manager, controller, cgroup_path, pid); else ret = cgmanager_move_pid_sync(NULL, cgroup_manager, controller, cgroup_path, pid); if (ret != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("call to cgmanager_move_pid_%ssync failed: %s", abs ? "abs_" : "", nerr->message); nih_free(nerr); return false; } return true; } static inline bool cgm_enter(void *hdata, pid_t pid) { struct cgm_data *d = hdata; char **slist = subsystems; bool ret = false; int i; if (!d || !d->cgroup_path) return false; if (!cgm_dbus_connect()) { ERROR("Error connecting to cgroup manager"); return false; } if (cgm_all_controllers_same) slist = subsystems_inone; for (i = 0; slist[i]; i++) { if (!lxc_cgmanager_enter(pid, slist[i], d->cgroup_path, false)) goto out; } ret = true; out: cgm_dbus_disconnect(); return ret; } static const char *cgm_get_cgroup(void *hdata, const char *subsystem) { struct cgm_data *d = hdata; if (!d || !d->cgroup_path) return NULL; return d->cgroup_path; } static const char *cgm_canonical_path(void *hdata) { struct cgm_data *d = hdata; if (!d || !d->cgroup_path) return NULL; return d->cgroup_path; } #if HAVE_CGMANAGER_GET_PID_CGROUP_ABS_SYNC static inline bool abs_cgroup_supported(void) { return api_version >= CGM_SUPPORTS_GET_ABS; } #else static inline bool abs_cgroup_supported(void) { return false; } #define cgmanager_get_pid_cgroup_abs_sync(...) -1 #endif static char *try_get_abs_cgroup(const char *name, const char *lxcpath, const char *controller) { char *cgroup = NULL; if (abs_cgroup_supported()) { /* get the container init pid and ask for its abs cgroup */ pid_t pid = lxc_cmd_get_init_pid(name, lxcpath); if (pid < 0) return NULL; if (cgmanager_get_pid_cgroup_abs_sync(NULL, cgroup_manager, controller, pid, &cgroup) != 0) { cgroup = NULL; NihError *nerr; nerr = nih_error_get(); nih_free(nerr); } return cgroup; } /* use the command interface to look for the cgroup */ return lxc_cmd_get_cgroup_path(name, lxcpath, controller); } /* * nrtasks is called by the utmp helper by the container monitor. * cgmanager socket was closed after cgroup setup was complete, so we need * to reopen here. * * Return -1 on error. */ static int cgm_get_nrtasks(void *hdata) { struct cgm_data *d = hdata; int32_t *pids; size_t pids_len; if (!d || !d->cgroup_path) return -1; if (!cgm_dbus_connect()) { ERROR("Error connecting to cgroup manager"); return -1; } if (cgmanager_get_tasks_sync(NULL, cgroup_manager, subsystems[0], d->cgroup_path, &pids, &pids_len) != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("call to cgmanager_get_tasks_sync failed: %s", nerr->message); nih_free(nerr); pids_len = -1; goto out; } nih_free(pids); out: cgm_dbus_disconnect(); return pids_len; } #if HAVE_CGMANAGER_LIST_CONTROLLERS static bool lxc_list_controllers(char ***list) { if (!cgm_dbus_connect()) { ERROR("Error connecting to cgroup manager"); return false; } if (cgmanager_list_controllers_sync(NULL, cgroup_manager, list) != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("call to cgmanager_list_controllers_sync failed: %s", nerr->message); nih_free(nerr); cgm_dbus_disconnect(); return false; } cgm_dbus_disconnect(); return true; } #else static bool lxc_list_controllers(char ***list) { return false; } #endif static inline void free_abs_cgroup(char *cgroup) { if (!cgroup) return; if (abs_cgroup_supported()) nih_free(cgroup); else free(cgroup); } static void do_cgm_get(const char *name, const char *lxcpath, const char *filename, int outp, bool sendvalue) { char *controller, *key, *cgroup = NULL, *cglast; int len = -1; int ret; nih_local char *result = NULL; controller = alloca(strlen(filename)+1); strcpy(controller, filename); key = strchr(controller, '.'); if (!key) { ret = write(outp, &len, sizeof(len)); if (ret != sizeof(len)) WARN("Failed to warn cgm_get of error; parent may hang"); exit(1); } *key = '\0'; if (!cgm_dbus_connect()) { ERROR("Error connecting to cgroup manager"); ret = write(outp, &len, sizeof(len)); if (ret != sizeof(len)) WARN("Failed to warn cgm_get of error; parent may hang"); exit(1); } cgroup = try_get_abs_cgroup(name, lxcpath, controller); if (!cgroup) { cgm_dbus_disconnect(); ret = write(outp, &len, sizeof(len)); if (ret != sizeof(len)) WARN("Failed to warn cgm_get of error; parent may hang"); exit(1); } cglast = strrchr(cgroup, '/'); if (!cglast) { cgm_dbus_disconnect(); free_abs_cgroup(cgroup); ret = write(outp, &len, sizeof(len)); if (ret != sizeof(len)) WARN("Failed to warn cgm_get of error; parent may hang"); exit(1); } *cglast = '\0'; if (!lxc_cgmanager_enter(getpid(), controller, cgroup, abs_cgroup_supported())) { ERROR("Failed to enter container cgroup %s:%s", controller, cgroup); ret = write(outp, &len, sizeof(len)); if (ret != sizeof(len)) WARN("Failed to warn cgm_get of error; parent may hang"); cgm_dbus_disconnect(); free_abs_cgroup(cgroup); exit(1); } if (cgmanager_get_value_sync(NULL, cgroup_manager, controller, cglast+1, filename, &result) != 0) { NihError *nerr; nerr = nih_error_get(); nih_free(nerr); free_abs_cgroup(cgroup); cgm_dbus_disconnect(); ret = write(outp, &len, sizeof(len)); if (ret != sizeof(len)) WARN("Failed to warn cgm_get of error; parent may hang"); exit(1); } free_abs_cgroup(cgroup); cgm_dbus_disconnect(); len = strlen(result); ret = write(outp, &len, sizeof(len)); if (ret != sizeof(len)) { WARN("Failed to send length to parent"); exit(1); } if (!len || !sendvalue) { exit(0); } ret = write(outp, result, len); if (ret < 0) exit(1); exit(0); } /* cgm_get is called to get container cgroup settings, not during startup */ static int cgm_get(const char *filename, char *value, size_t len, const char *name, const char *lxcpath) { pid_t pid; int p[2], ret, newlen, readlen; if (pipe(p) < 0) return -1; if ((pid = fork()) < 0) { close(p[0]); close(p[1]); return -1; } if (!pid) // do_cgm_get exits do_cgm_get(name, lxcpath, filename, p[1], len && value); close(p[1]); ret = read(p[0], &newlen, sizeof(newlen)); if (ret != sizeof(newlen)) { close(p[0]); ret = -1; goto out; } if (!len || !value) { close(p[0]); ret = newlen; goto out; } memset(value, 0, len); if (newlen < 0) { // child is reporting an error close(p[0]); ret = -1; goto out; } if (newlen == 0) { // empty read close(p[0]); ret = 0; goto out; } readlen = newlen > len ? len : newlen; ret = read(p[0], value, readlen); close(p[0]); if (ret != readlen) { ret = -1; goto out; } if (newlen >= len) { value[len-1] = '\0'; newlen = len-1; } else if (newlen+1 < len) { // cgmanager doesn't add eol to last entry value[newlen++] = '\n'; value[newlen] = '\0'; } ret = newlen; out: if (wait_for_pid(pid)) WARN("do_cgm_get exited with error"); return ret; } static void do_cgm_set(const char *name, const char *lxcpath, const char *filename, const char *value, int outp) { char *controller, *key, *cgroup = NULL; int retval = 0; // value we are sending to the parent over outp int ret; char *cglast; controller = alloca(strlen(filename)+1); strcpy(controller, filename); key = strchr(controller, '.'); if (!key) { ret = write(outp, &retval, sizeof(retval)); if (ret != sizeof(retval)) WARN("Failed to warn cgm_set of error; parent may hang"); exit(1); } *key = '\0'; if (!cgm_dbus_connect()) { ERROR("Error connecting to cgroup manager"); ret = write(outp, &retval, sizeof(retval)); if (ret != sizeof(retval)) WARN("Failed to warn cgm_set of error; parent may hang"); exit(1); } cgroup = try_get_abs_cgroup(name, lxcpath, controller); if (!cgroup) { cgm_dbus_disconnect(); ret = write(outp, &retval, sizeof(retval)); if (ret != sizeof(retval)) WARN("Failed to warn cgm_set of error; parent may hang"); exit(1); } cglast = strrchr(cgroup, '/'); if (!cglast) { cgm_dbus_disconnect(); free_abs_cgroup(cgroup); ret = write(outp, &retval, sizeof(retval)); if (ret != sizeof(retval)) WARN("Failed to warn cgm_set of error; parent may hang"); exit(1); } *cglast = '\0'; if (!lxc_cgmanager_enter(getpid(), controller, cgroup, abs_cgroup_supported())) { ERROR("Failed to enter container cgroup %s:%s", controller, cgroup); ret = write(outp, &retval, sizeof(retval)); if (ret != sizeof(retval)) WARN("Failed to warn cgm_set of error; parent may hang"); cgm_dbus_disconnect(); free_abs_cgroup(cgroup); exit(1); } if (cgmanager_set_value_sync(NULL, cgroup_manager, controller, cglast+1, filename, value) != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("Error setting cgroup value %s for %s:%s", filename, controller, cgroup); ERROR("call to cgmanager_set_value_sync failed: %s", nerr->message); nih_free(nerr); free_abs_cgroup(cgroup); cgm_dbus_disconnect(); ret = write(outp, &retval, sizeof(retval)); if (ret != sizeof(retval)) WARN("Failed to warn cgm_set of error; parent may hang"); exit(1); } free_abs_cgroup(cgroup); cgm_dbus_disconnect(); /* tell parent that we are done */ retval = 1; ret = write(outp, &retval, sizeof(retval)); if (ret != sizeof(retval)) { exit(1); } exit(0); } /* cgm_set is called to change cgroup settings, not during startup */ static int cgm_set(const char *filename, const char *value, const char *name, const char *lxcpath) { pid_t pid; int p[2], ret, v; if (pipe(p) < 0) return -1; if ((pid = fork()) < 0) { close(p[1]); close(p[0]); return -1; } if (!pid) // do_cgm_set exits do_cgm_set(name, lxcpath, filename, value, p[1]); close(p[1]); ret = read(p[0], &v, sizeof(v)); close(p[0]); if (wait_for_pid(pid)) WARN("do_cgm_set exited with error"); if (ret != sizeof(v) || !v) return -1; return 0; } static void free_subsystems(void) { int i; for (i = 0; i < nr_subsystems; i++) free(subsystems[i]); free(subsystems); subsystems = NULL; nr_subsystems = 0; } static void cull_user_controllers(void) { int i, j; for (i = 0; i < nr_subsystems; i++) { if (strncmp(subsystems[i], "name=", 5) != 0) continue; for (j = i; j < nr_subsystems-1; j++) subsystems[j] = subsystems[j+1]; nr_subsystems--; } } static bool in_comma_list(const char *inword, const char *cgroup_use) { char *e; size_t inlen = strlen(inword), len; do { e = strchr(cgroup_use, ','); len = e ? e - cgroup_use : strlen(cgroup_use); if (len == inlen && strncmp(inword, cgroup_use, len) == 0) return true; cgroup_use = e + 1; } while (e); return false; } static bool in_subsystem_list(const char *c) { int i; for (i = 0; i < nr_subsystems; i++) { if (strcmp(c, subsystems[i]) == 0) return true; } return false; } /* * If /etc/lxc/lxc.conf specifies lxc.cgroup.use = "freezer,memory", * then clear out any other subsystems, and make sure that freezer * and memory are both enabled */ static bool verify_and_prune(const char *cgroup_use) { const char *p; char *e; int i, j; for (p = cgroup_use; p && *p; p = e + 1) { e = strchr(p, ','); if (e) *e = '\0'; if (!in_subsystem_list(p)) { ERROR("Controller %s required by lxc.cgroup.use but not available\n", p); return false; } if (e) *e = ','; if (!e) break; } for (i = 0; i < nr_subsystems;) { if (in_comma_list(subsystems[i], cgroup_use)) { i++; continue; } free(subsystems[i]); for (j = i; j < nr_subsystems-1; j++) subsystems[j] = subsystems[j+1]; subsystems[nr_subsystems-1] = NULL; nr_subsystems--; } return true; } static bool collect_subsytems(void) { char *line = NULL; nih_local char **cgm_subsys_list = NULL; size_t sz = 0; FILE *f = NULL; if (subsystems) // already initialized return true; subsystems_inone = malloc(2 * sizeof(char *)); if (!subsystems_inone) return false; subsystems_inone[0] = "all"; subsystems_inone[1] = NULL; if (lxc_list_controllers(&cgm_subsys_list)) { while (cgm_subsys_list[nr_subsystems]) { char **tmp = NIH_MUST( realloc(subsystems, (nr_subsystems+2)*sizeof(char *)) ); tmp[nr_subsystems] = NIH_MUST( strdup(cgm_subsys_list[nr_subsystems++]) ); subsystems = tmp; } if (nr_subsystems) subsystems[nr_subsystems] = NULL; goto collected; } INFO("cgmanager_list_controllers failed, falling back to /proc/self/cgroups"); f = fopen_cloexec("/proc/self/cgroup", "r"); if (!f) { f = fopen_cloexec("/proc/1/cgroup", "r"); if (!f) return false; } while (getline(&line, &sz, f) != -1) { /* file format: hierarchy:subsystems:group, * with multiple subsystems being ,-separated */ char *slist, *end, *p, *saveptr = NULL, **tmp; if (!line[0]) continue; slist = strchr(line, ':'); if (!slist) continue; slist++; end = strchr(slist, ':'); if (!end) continue; *end = '\0'; for (p = strtok_r(slist, ",", &saveptr); p; p = strtok_r(NULL, ",", &saveptr)) { tmp = realloc(subsystems, (nr_subsystems+2)*sizeof(char *)); if (!tmp) goto out_free; subsystems = tmp; tmp[nr_subsystems] = strdup(p); tmp[nr_subsystems+1] = NULL; if (!tmp[nr_subsystems]) goto out_free; nr_subsystems++; } } fclose(f); f = NULL; free(line); line = NULL; collected: if (!nr_subsystems) { ERROR("No cgroup subsystems found"); return false; } /* make sure that cgroup.use can be and is honored */ const char *cgroup_use = lxc_global_config_value("lxc.cgroup.use"); if (!cgroup_use && errno != 0) goto out_good; if (cgroup_use) { if (!verify_and_prune(cgroup_use)) { free_subsystems(); return false; } subsystems_inone[0] = NIH_MUST( strdup(cgroup_use) ); cgm_all_controllers_same = false; } out_good: return true; out_free: free(line); if (f) fclose(f); free_subsystems(); return false; } /* * called during cgroup.c:cgroup_ops_init(), at startup. No threads. * We check whether we can talk to cgmanager, escape to root cgroup if * we are root, then close the connection. */ struct cgroup_ops *cgm_ops_init(void) { if (!collect_subsytems()) return NULL; if (!cgm_dbus_connect()) goto err1; // root; try to escape to root cgroup if (geteuid() == 0 && !lxc_cgmanager_escape()) goto err2; cgm_dbus_disconnect(); return &cgmanager_ops; err2: cgm_dbus_disconnect(); err1: free_subsystems(); return NULL; } /* unfreeze is called by the command api after killing a container. */ static bool cgm_unfreeze(void *hdata) { struct cgm_data *d = hdata; bool ret = true; if (!d || !d->cgroup_path) return false; if (!cgm_dbus_connect()) { ERROR("Error connecting to cgroup manager"); return false; } if (cgmanager_set_value_sync(NULL, cgroup_manager, "freezer", d->cgroup_path, "freezer.state", "THAWED") != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("call to cgmanager_set_value_sync failed: %s", nerr->message); nih_free(nerr); ERROR("Error unfreezing %s", d->cgroup_path); ret = false; } cgm_dbus_disconnect(); return ret; } static bool cgm_setup_limits(void *hdata, struct lxc_list *cgroup_settings, bool do_devices) { struct cgm_data *d = hdata; struct lxc_list *iterator, *sorted_cgroup_settings, *next; struct lxc_cgroup *cg; bool ret = false; if (lxc_list_empty(cgroup_settings)) return true; if (!d || !d->cgroup_path) return false; if (!cgm_dbus_connect()) { ERROR("Error connecting to cgroup manager"); return false; } sorted_cgroup_settings = sort_cgroup_settings(cgroup_settings); if (!sorted_cgroup_settings) { return false; } lxc_list_for_each(iterator, sorted_cgroup_settings) { char controller[100], *p; cg = iterator->elem; if (do_devices != !strncmp("devices", cg->subsystem, 7)) continue; if (strlen(cg->subsystem) > 100) // i smell a rat goto out; strcpy(controller, cg->subsystem); p = strchr(controller, '.'); if (p) *p = '\0'; if (cgmanager_set_value_sync(NULL, cgroup_manager, controller, d->cgroup_path, cg->subsystem, cg->value) != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("call to cgmanager_set_value_sync failed: %s", nerr->message); nih_free(nerr); ERROR("Error setting cgroup %s:%s limit type %s", controller, d->cgroup_path, cg->subsystem); goto out; } DEBUG("cgroup '%s' set to '%s'", cg->subsystem, cg->value); } ret = true; INFO("cgroup limits have been setup"); out: lxc_list_for_each_safe(iterator, sorted_cgroup_settings, next) { lxc_list_del(iterator); free(iterator); } free(sorted_cgroup_settings); cgm_dbus_disconnect(); return ret; } static bool cgm_chown(void *hdata, struct lxc_conf *conf) { struct cgm_data *d = hdata; if (!d || !d->cgroup_path) return false; if (!cgm_dbus_connect()) { ERROR("Error connecting to cgroup manager"); return false; } if (!chown_cgroup(d->cgroup_path, conf)) WARN("Failed to chown %s to container root", d->cgroup_path); cgm_dbus_disconnect(); return true; } /* * TODO: this should be re-written to use the get_config_item("lxc.id_map") * cmd api instead of getting the idmap from c->lxc_conf. The reason is * that the id_maps may be different if the container was started with a * -f or -s argument. * The reason I'm punting on that is because we'll need to parse the * idmap results. */ static bool cgm_attach(const char *name, const char *lxcpath, pid_t pid) { bool pass = true; char *cgroup = NULL; char **slist = subsystems; int i; if (!cgm_dbus_connect()) { ERROR("Error connecting to cgroup manager"); return false; } for (i = 0; slist[i]; i++) { cgroup = try_get_abs_cgroup(name, lxcpath, slist[i]); if (!cgroup) { ERROR("Failed to get cgroup for controller %s", slist[i]); cgm_dbus_disconnect(); return false; } if (!lxc_cgmanager_enter(pid, slist[i], cgroup, abs_cgroup_supported())) { pass = false; break; } } cgm_dbus_disconnect(); if (!pass) ERROR("Failed to enter group %s", cgroup); free_abs_cgroup(cgroup); return pass; } static bool cgm_bind_dir(const char *root, const char *dirname) { nih_local char *cgpath = NULL; /* /sys should have been mounted by now */ cgpath = NIH_MUST( nih_strdup(NULL, root) ); NIH_MUST( nih_strcat(&cgpath, NULL, "/sys/fs/cgroup") ); if (!dir_exists(cgpath)) { ERROR("%s does not exist", cgpath); return false; } /* mount a tmpfs there so we can create subdirs */ if (safe_mount("cgroup", cgpath, "tmpfs", 0, "size=10000,mode=755", root)) { SYSERROR("Failed to mount tmpfs at %s", cgpath); return false; } NIH_MUST( nih_strcat(&cgpath, NULL, "/cgmanager") ); if (mkdir(cgpath, 0755) < 0) { SYSERROR("Failed to create %s", cgpath); return false; } if (safe_mount(dirname, cgpath, "none", MS_BIND, 0, root)) { SYSERROR("Failed to bind mount %s to %s", dirname, cgpath); return false; } return true; } /* * cgm_mount_cgroup: * If /sys/fs/cgroup/cgmanager.lower/ exists, bind mount that to * /sys/fs/cgroup/cgmanager/ in the container. * Otherwise, if /sys/fs/cgroup/cgmanager exists, bind mount that. * Else do nothing */ #define CGMANAGER_LOWER_SOCK "/sys/fs/cgroup/cgmanager.lower" #define CGMANAGER_UPPER_SOCK "/sys/fs/cgroup/cgmanager" static bool cgm_mount_cgroup(void *hdata, const char *root, int type) { if (dir_exists(CGMANAGER_LOWER_SOCK)) return cgm_bind_dir(root, CGMANAGER_LOWER_SOCK); if (dir_exists(CGMANAGER_UPPER_SOCK)) return cgm_bind_dir(root, CGMANAGER_UPPER_SOCK); // Host doesn't have cgmanager running? Then how did we get here? return false; } static struct cgroup_ops cgmanager_ops = { .init = cgm_init, .destroy = cgm_destroy, .create = cgm_create, .enter = cgm_enter, .create_legacy = NULL, .get_cgroup = cgm_get_cgroup, .canonical_path = cgm_canonical_path, .get = cgm_get, .set = cgm_set, .unfreeze = cgm_unfreeze, .setup_limits = cgm_setup_limits, .name = "cgmanager", .chown = cgm_chown, .attach = cgm_attach, .mount_cgroup = cgm_mount_cgroup, .nrtasks = cgm_get_nrtasks, .disconnect = NULL, .driver = CGMANAGER, }; #endif
./CrossVul/dataset_final_sorted/CWE-59/c/good_1471_2
crossvul-cpp_data_good_1506_1
#include <gio/gio.h> #include <stdlib.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include "libabrt.h" #include "abrt-polkit.h" #include "abrt_glib.h" #include <libreport/dump_dir.h> #include "problem_api.h" static GMainLoop *loop; static guint g_timeout_source; /* default, settable with -t: */ static unsigned g_timeout_value = 120; /* ---------------------------------------------------------------------------------------------------- */ static GDBusNodeInfo *introspection_data = NULL; /* Introspection data for the service we are exporting */ static const gchar introspection_xml[] = "<node>" " <interface name='"ABRT_DBUS_IFACE"'>" " <method name='NewProblem'>" " <arg type='a{ss}' name='problem_data' direction='in'/>" " <arg type='s' name='problem_id' direction='out'/>" " </method>" " <method name='GetProblems'>" " <arg type='as' name='response' direction='out'/>" " </method>" " <method name='GetAllProblems'>" " <arg type='as' name='response' direction='out'/>" " </method>" " <method name='GetForeignProblems'>" " <arg type='as' name='response' direction='out'/>" " </method>" " <method name='GetInfo'>" " <arg type='s' name='problem_dir' direction='in'/>" " <arg type='as' name='element_names' direction='in'/>" " <arg type='a{ss}' name='response' direction='out'/>" " </method>" " <method name='SetElement'>" " <arg type='s' name='problem_dir' direction='in'/>" " <arg type='s' name='name' direction='in'/>" " <arg type='s' name='value' direction='in'/>" " </method>" " <method name='DeleteElement'>" " <arg type='s' name='problem_dir' direction='in'/>" " <arg type='s' name='name' direction='in'/>" " </method>" " <method name='ChownProblemDir'>" " <arg type='s' name='problem_dir' direction='in'/>" " </method>" " <method name='DeleteProblem'>" " <arg type='as' name='problem_dir' direction='in'/>" " </method>" " <method name='FindProblemByElementInTimeRange'>" " <arg type='s' name='element' direction='in'/>" " <arg type='s' name='value' direction='in'/>" " <arg type='x' name='timestamp_from' direction='in'/>" " <arg type='x' name='timestamp_to' direction='in'/>" " <arg type='b' name='all_users' direction='in'/>" " <arg type='as' name='response' direction='out'/>" " </method>" " <method name='Quit' />" " </interface>" "</node>"; /* ---------------------------------------------------------------------------------------------------- */ /* forward */ static gboolean on_timeout_cb(gpointer user_data); static void reset_timeout(void) { if (g_timeout_source > 0) { log_info("Removing timeout"); g_source_remove(g_timeout_source); } log_info("Setting a new timeout"); g_timeout_source = g_timeout_add_seconds(g_timeout_value, on_timeout_cb, NULL); } static uid_t get_caller_uid(GDBusConnection *connection, GDBusMethodInvocation *invocation, const char *caller) { GError *error = NULL; guint caller_uid; GDBusProxy * proxy = g_dbus_proxy_new_sync(connection, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", NULL, &error); GVariant *result = g_dbus_proxy_call_sync(proxy, "GetConnectionUnixUser", g_variant_new ("(s)", caller), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (result == NULL) { /* we failed to get the uid, so return (uid_t) -1 to indicate the error */ if (error) { g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidUser", error->message); g_error_free(error); } else { g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidUser", _("Unknown error")); } return (uid_t) -1; } g_variant_get(result, "(u)", &caller_uid); g_variant_unref(result); log_info("Caller uid: %i", caller_uid); return caller_uid; } bool allowed_problem_dir(const char *dir_name) { if (!dir_is_in_dump_location(dir_name)) { error_msg("Bad problem directory name '%s', should start with: '%s'", dir_name, g_settings_dump_location); return false; } /* We cannot test correct permissions yet because we still need to chown * dump directories before reporting and Chowing changes the file owner to * the reporter, which causes this test to fail and prevents users from * getting problem data after reporting it. * * Fortunately, libreport has been hardened against hard link and symbolic * link attacks and refuses to work with such files, so this test isn't * really necessary, however, we will use it once we get rid of the * chowning files. * * abrt-server refuses to run post-create on directories that have * incorrect owner (not "root:(abrt|root)"), incorrect permissions (other * bits are not 0) and are complete (post-create finished). So, there is no * way to run security sensitive event scripts (post-create) on crafted * problem directories. */ #if 0 if (!dir_has_correct_permissions(dir_name)) { error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dir_name); return false; } #endif return true; } static char *handle_new_problem(GVariant *problem_info, uid_t caller_uid, char **error) { char *problem_id = NULL; problem_data_t *pd = problem_data_new(); GVariantIter *iter; g_variant_get(problem_info, "a{ss}", &iter); gchar *key, *value; while (g_variant_iter_loop(iter, "{ss}", &key, &value)) { if (allowed_new_user_problem_entry(caller_uid, key, value) == false) { *error = xasprintf("You are not allowed to create element '%s' containing '%s'", key, value); goto finito; } problem_data_add_text_editable(pd, key, value); } if (caller_uid != 0 || problem_data_get_content_or_NULL(pd, FILENAME_UID) == NULL) { /* set uid field to caller's uid if caller is not root or root doesn't pass own uid */ log_info("Adding UID %d to problem data", caller_uid); char buf[sizeof(uid_t) * 3 + 2]; snprintf(buf, sizeof(buf), "%d", caller_uid); problem_data_add_text_noteditable(pd, FILENAME_UID, buf); } /* At least it should generate local problem identifier UUID */ problem_data_add_basics(pd); problem_id = problem_data_save(pd); if (problem_id) notify_new_path(problem_id); else if (error) *error = xasprintf("Cannot create a new problem"); finito: problem_data_free(pd); return problem_id; } static void return_InvalidProblemDir_error(GDBusMethodInvocation *invocation, const char *dir_name) { char *msg = xasprintf(_("'%s' is not a valid problem directory"), dir_name); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidProblemDir", msg); free(msg); } /* * Checks element's rights and does not open directory if element is protected. * Checks problem's rights and does not open directory if user hasn't got * access to a problem. * * Returns a dump directory opend for writing or NULL. * * If any operation from the above listed fails, immediately returns D-Bus * error to a D-Bus caller. */ static struct dump_dir *open_directory_for_modification_of_element( GDBusMethodInvocation *invocation, uid_t caller_uid, const char *problem_id, const char *element) { static const char *const protected_elements[] = { FILENAME_TIME, FILENAME_UID, NULL, }; for (const char *const *protected = protected_elements; *protected; ++protected) { if (strcmp(*protected, element) == 0) { log_notice("'%s' element of '%s' can't be modified", element, problem_id); char *error = xasprintf(_("'%s' element can't be modified"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.ProtectedElement", error); free(error); return NULL; } } int dir_fd = dd_openfd(problem_id); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_id); return_InvalidProblemDir_error(invocation, problem_id); return NULL; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("'%s' is not a valid problem directory", problem_id); return_InvalidProblemDir_error(invocation, problem_id); } else { log_notice("UID(%d) is not Authorized to access '%s'", caller_uid, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); } close(dir_fd); return NULL; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_id, /* flags : */ 0); if (!dd) { /* This should not happen because of the access check above */ log_notice("Can't access the problem '%s' for modification", problem_id); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", _("Can't access the problem for modification")); return NULL; } return dd; } /* * Lists problems which have given element and were seen in given time interval */ struct field_and_time_range { GList *list; const char *element; const char *value; unsigned long timestamp_from; unsigned long timestamp_to; }; static int add_dirname_to_GList_if_matches(struct dump_dir *dd, void *arg) { struct field_and_time_range *me = arg; char *field_data = dd_load_text(dd, me->element); int brk = (strcmp(field_data, me->value) != 0); free(field_data); if (brk) return 0; field_data = dd_load_text(dd, FILENAME_LAST_OCCURRENCE); long val = atol(field_data); free(field_data); if (val < me->timestamp_from || val > me->timestamp_to) return 0; me->list = g_list_prepend(me->list, xstrdup(dd->dd_dirname)); return 0; } static GList *get_problem_dirs_for_element_in_time(uid_t uid, const char *element, const char *value, unsigned long timestamp_from, unsigned long timestamp_to) { if (timestamp_to == 0) /* not sure this is possible, but... */ timestamp_to = time(NULL); struct field_and_time_range me = { .list = NULL, .element = element, .value = value, .timestamp_from = timestamp_from, .timestamp_to = timestamp_to, }; for_each_problem_in_dir(g_settings_dump_location, uid, add_dirname_to_GList_if_matches, &me); return g_list_reverse(me.list); } static void handle_method_call(GDBusConnection *connection, const gchar *caller, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { reset_timeout(); uid_t caller_uid; GVariant *response; caller_uid = get_caller_uid(connection, invocation, caller); log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name); if (caller_uid == (uid_t) -1) return; if (g_strcmp0(method_name, "NewProblem") == 0) { char *error = NULL; char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error); if (!problem_id) { g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } /* else */ response = g_variant_new("(s)", problem_id); g_dbus_method_invocation_return_value(invocation, response); free(problem_id); return; } if (g_strcmp0(method_name, "GetProblems") == 0) { GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); //I was told that g_dbus_method frees the response //g_variant_unref(response); return; } if (g_strcmp0(method_name, "GetAllProblems") == 0) { /* - so, we have UID, - if it's 0, then we don't have to check anything and just return all directories - if uid != 0 then we want to ask for authorization */ if (caller_uid != 0) { if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; } GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "GetForeignProblems") == 0) { GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "ChownProblemDir") == 0) { const gchar *problem_dir; g_variant_get(parameters, "(&s)", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid); if (ddstat < 0) { if (errno == ENOTDIR) { log_notice("requested directory does not exist '%s'", problem_dir); } else { perror_msg("can't get stat of '%s'", problem_dir); } return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (ddstat & DD_STAT_OWNED_BY_UID) { //caller seems to be in group with access to this dir, so no action needed log_notice("caller has access to the requested directory %s", problem_dir); g_dbus_method_invocation_return_value(invocation, NULL); close(dir_fd); return; } if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int chown_res = dd_chown(dd, caller_uid); if (chown_res != 0) g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.ChownError", _("Chowning directory failed. Check system logs for more details.")); else g_dbus_method_invocation_return_value(invocation, NULL); dd_close(dd); return; } if (g_strcmp0(method_name, "GetInfo") == 0) { /* Parameter tuple is (sas) */ /* Get 1st param - problem dir name */ const gchar *problem_dir; g_variant_get_child(parameters, 0, "&s", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } /* Get 2nd param - vector of element names */ GVariant *array = g_variant_get_child_value(parameters, 1); GList *elements = string_list_from_variant(array); g_variant_unref(array); GVariantBuilder *builder = NULL; for (GList *l = elements; l; l = l->next) { const char *element_name = (const char*)l->data; char *value = dd_load_text_ext(dd, element_name, 0 | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT | DD_FAIL_QUIETLY_EACCES); log_notice("element '%s' %s", element_name, value ? "fetched" : "not found"); if (value) { if (!builder) builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY); /* g_variant_builder_add makes a copy. No need to xstrdup here */ g_variant_builder_add(builder, "{ss}", element_name, value); free(value); } } list_free_with_free(elements); dd_close(dd); /* It is OK to call g_variant_new("(a{ss})", NULL) because */ /* G_VARIANT_TYPE_TUPLE allows NULL value */ GVariant *response = g_variant_new("(a{ss})", builder); if (builder) g_variant_builder_unref(builder); log_info("GetInfo: returning value for '%s'", problem_dir); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "SetElement") == 0) { const char *problem_id; const char *element; const char *value; g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value); if (!str_is_correct_filename(element)) { log_notice("'%s' is not a valid element name of '%s'", element, problem_id); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; /* Is it good idea to make it static? Is it possible to change the max size while a single run? */ const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024); const long item_size = dd_get_item_size(dd, element); if (item_size < 0) { log_notice("Can't get size of '%s/%s'", problem_id, element); char *error = xasprintf(_("Can't get size of '%s'"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); return; } const double requested_size = (double)strlen(value) - item_size; /* Don't want to check the size limit in case of reducing of size */ if (requested_size > 0 && requested_size > (max_dir_size - get_dirsize(g_settings_dump_location))) { log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", _("No problem space left")); } else { dd_save_text(dd, element, value); g_dbus_method_invocation_return_value(invocation, NULL); } dd_close(dd); return; } if (g_strcmp0(method_name, "DeleteElement") == 0) { const char *problem_id; const char *element; g_variant_get(parameters, "(&s&s)", &problem_id, &element); if (!str_is_correct_filename(element)) { log_notice("'%s' is not a valid element name of '%s'", element, problem_id); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; const int res = dd_delete_item(dd, element); dd_close(dd); if (res != 0) { log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id); char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } g_dbus_method_invocation_return_value(invocation, NULL); return; } if (g_strcmp0(method_name, "DeleteProblem") == 0) { /* Dbus parameters are always tuples. * In this case, it's (as) - a tuple of one element (array of strings). * Need to fetch the array: */ GVariant *array = g_variant_get_child_value(parameters, 0); GList *problem_dirs = string_list_from_variant(array); g_variant_unref(array); for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; log_notice("dir_name:'%s'", dir_name); if (!allowed_problem_dir(dir_name)) { return_InvalidProblemDir_error(invocation, dir_name); goto ret; } } for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; int dir_fd = dd_openfd(dir_name); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", dir_name); return_InvalidProblemDir_error(invocation, dir_name); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", dir_name); close(dir_fd); continue; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { // if user didn't provide correct credentials, just move to the next dir close(dir_fd); continue; } } struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg("Failed to delete problem directory '%s'", dir_name); dd_close(dd); } } } g_dbus_method_invocation_return_value(invocation, NULL); ret: list_free_with_free(problem_dirs); return; } if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0) { const gchar *element; const gchar *value; glong timestamp_from; glong timestamp_to; gboolean all; g_variant_get_child(parameters, 0, "&s", &element); g_variant_get_child(parameters, 1, "&s", &value); g_variant_get_child(parameters, 2, "x", &timestamp_from); g_variant_get_child(parameters, 3, "x", &timestamp_to); g_variant_get_child(parameters, 4, "b", &all); if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from, timestamp_to); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "Quit") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); g_main_loop_quit(loop); return; } } static gboolean on_timeout_cb(gpointer user_data) { g_main_loop_quit(loop); return TRUE; } static const GDBusInterfaceVTable interface_vtable = { .method_call = handle_method_call, .get_property = NULL, .set_property = NULL, }; static void on_bus_acquired(GDBusConnection *connection, const gchar *name, gpointer user_data) { guint registration_id; registration_id = g_dbus_connection_register_object(connection, ABRT_DBUS_OBJECT, introspection_data->interfaces[0], &interface_vtable, NULL, /* user_data */ NULL, /* user_data_free_func */ NULL); /* GError** */ g_assert(registration_id > 0); reset_timeout(); } /* not used static void on_name_acquired (GDBusConnection *connection, const gchar *name, gpointer user_data) { } */ static void on_name_lost(GDBusConnection *connection, const gchar *name, gpointer user_data) { g_print(_("The name '%s' has been lost, please check if other " "service owning the name is not running.\n"), name); exit(1); } int main(int argc, char *argv[]) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif guint owner_id; abrt_init(argv); const char *program_usage_string = _( "& [options]" ); enum { OPT_v = 1 << 0, OPT_t = 1 << 1, }; /* Keep enum above and order of options below in sync! */ struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_INTEGER('t', NULL, &g_timeout_value, _("Exit after NUM seconds of inactivity")), OPT_END() }; /*unsigned opts =*/ parse_opts(argc, argv, program_options, program_usage_string); export_abrt_envvars(0); /* When dbus daemon starts us, it doesn't set PATH * (I saw it set only DBUS_STARTER_ADDRESS and DBUS_STARTER_BUS_TYPE). * In this case, set something sane: */ const char *env_path = getenv("PATH"); if (!env_path || !env_path[0]) putenv((char*)"PATH=/usr/sbin:/usr/bin:/sbin:/bin"); msg_prefix = "abrt-dbus"; /* for log(), error_msg() and such */ if (getuid() != 0) error_msg_and_die(_("This program must be run as root.")); glib_init(); /* We are lazy here - we don't want to manually provide * the introspection data structures - so we just build * them from XML. */ introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, NULL); g_assert(introspection_data != NULL); owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM, ABRT_DBUS_NAME, G_BUS_NAME_OWNER_FLAGS_NONE, on_bus_acquired, NULL, on_name_lost, NULL, NULL); /* initialize the g_settings_dump_location */ load_abrt_conf(); loop = g_main_loop_new(NULL, FALSE); g_main_loop_run(loop); log_notice("Cleaning up"); g_bus_unown_name(owner_id); g_dbus_node_info_unref(introspection_data); free_abrt_conf_data(); return 0; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_1506_1
crossvul-cpp_data_bad_1506_3
/* Copyright (C) 2009 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/statvfs.h> #include "internal_libabrt.h" int low_free_space(unsigned setting_MaxCrashReportsSize, const char *dump_location) { struct statvfs vfs; if (statvfs(dump_location, &vfs) != 0) { perror_msg("statvfs('%s')", dump_location); return 0; } /* Check that at least MaxCrashReportsSize/4 MBs are free */ /* fs_free_mb_x4 ~= vfs.f_bfree * vfs.f_bsize * 4, expressed in MBytes. * Need to neither overflow nor round f_bfree down too much. */ unsigned long fs_free_mb_x4 = ((unsigned long long)vfs.f_bfree / (1024/4)) * vfs.f_bsize / 1024; if (fs_free_mb_x4 < setting_MaxCrashReportsSize) { error_msg("Only %luMiB is available on %s", fs_free_mb_x4 / 4, dump_location); return 1; } return 0; } /* rhbz#539551: "abrt going crazy when crashing process is respawned". * Check total size of problem dirs, if it overflows, * delete oldest/biggest dirs. */ void trim_problem_dirs(const char *dirname, double cap_size, const char *exclude_path) { const char *excluded_basename = NULL; if (exclude_path) { unsigned len_dirname = strlen(dirname); /* Trim trailing '/'s, but dont trim name "/" to "" */ while (len_dirname > 1 && dirname[len_dirname-1] == '/') len_dirname--; if (strncmp(dirname, exclude_path, len_dirname) == 0 && exclude_path[len_dirname] == '/' ) { /* exclude_path is "dirname/something" */ excluded_basename = exclude_path + len_dirname + 1; } } log_debug("excluded_basename:'%s'", excluded_basename); int count = 20; while (--count >= 0) { /* We exclude our own dir from candidates for deletion (3rd param): */ char *worst_basename = NULL; double cur_size = get_dirsize_find_largest_dir(dirname, &worst_basename, excluded_basename); if (cur_size <= cap_size || !worst_basename) { log_info("cur_size:%.0f cap_size:%.0f, no (more) trimming", cur_size, cap_size); free(worst_basename); break; } log("%s is %.0f bytes (more than %.0fMiB), deleting '%s'", dirname, cur_size, cap_size / (1024*1024), worst_basename); char *d = concat_path_file(dirname, worst_basename); free(worst_basename); delete_dump_dir(d); free(d); } } /** * * @param[out] status See `man 2 wait` for status information. * @return Malloc'ed string */ static char* exec_vp(char **args, int redirect_stderr, int exec_timeout_sec, int *status) { /* Nuke everything which may make setlocale() switch to non-POSIX locale: * we need to avoid having gdb output in some obscure language. */ static const char *const env_vec[] = { "LANG", "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", /* Workaround for * http://sourceware.org/bugzilla/show_bug.cgi?id=9622 * (gdb emitting ESC sequences even with -batch) */ "TERM", NULL }; int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_SETSID | EXECFLG_QUIET; if (redirect_stderr) flags |= EXECFLG_ERR2OUT; VERB1 flags &= ~EXECFLG_QUIET; int pipeout[2]; pid_t child = fork_execv_on_steroids(flags, args, pipeout, (char**)env_vec, /*dir:*/ NULL, /*uid(unused):*/ 0); /* We use this function to run gdb and unstrip. Bugs in gdb or corrupted * coredumps were observed to cause gdb to enter infinite loop. * Therefore we have a (largish) timeout, after which we kill the child. */ ndelay_on(pipeout[0]); int t = time(NULL); /* int is enough, no need to use time_t */ int endtime = t + exec_timeout_sec; struct strbuf *buf_out = strbuf_new(); while (1) { int timeout = endtime - t; if (timeout < 0) { kill(child, SIGKILL); strbuf_append_strf(buf_out, "\n" "Timeout exceeded: %u seconds, killing %s.\n" "Looks like gdb hung while generating backtrace.\n" "This may be a bug in gdb. Consider submitting a bug report to gdb developers.\n" "Please attach coredump from this crash to the bug report if you do.\n", exec_timeout_sec, args[0] ); break; } /* We don't check poll result - checking read result is enough */ struct pollfd pfd; pfd.fd = pipeout[0]; pfd.events = POLLIN; poll(&pfd, 1, timeout * 1000); char buff[1024]; int r = read(pipeout[0], buff, sizeof(buff) - 1); if (r <= 0) { /* I did see EAGAIN happening here */ if (r < 0 && errno == EAGAIN) goto next; break; } buff[r] = '\0'; strbuf_append_str(buf_out, buff); next: t = time(NULL); } close(pipeout[0]); /* Prevent having zombie child process, and maybe collect status * (note that status == NULL is ok too) */ safe_waitpid(child, status, 0); return strbuf_free_nobuf(buf_out); } char *run_unstrip_n(const char *dump_dir_name, unsigned timeout_sec) { int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_SETSID | EXECFLG_QUIET; VERB1 flags &= ~EXECFLG_QUIET; int pipeout[2]; char* args[4]; args[0] = (char*)"eu-unstrip"; args[1] = xasprintf("--core=%s/"FILENAME_COREDUMP, dump_dir_name); args[2] = (char*)"-n"; args[3] = NULL; pid_t child = fork_execv_on_steroids(flags, args, pipeout, /*env_vec:*/ NULL, /*dir:*/ NULL, /*uid(unused):*/ 0); free(args[1]); /* Bugs in unstrip or corrupted coredumps can cause it to enter infinite loop. * Therefore we have a (largish) timeout, after which we kill the child. */ ndelay_on(pipeout[0]); int t = time(NULL); /* int is enough, no need to use time_t */ int endtime = t + timeout_sec; struct strbuf *buf_out = strbuf_new(); while (1) { int timeout = endtime - t; if (timeout < 0) { kill(child, SIGKILL); strbuf_free(buf_out); buf_out = NULL; break; } /* We don't check poll result - checking read result is enough */ struct pollfd pfd; pfd.fd = pipeout[0]; pfd.events = POLLIN; poll(&pfd, 1, timeout * 1000); char buff[1024]; int r = read(pipeout[0], buff, sizeof(buff) - 1); if (r <= 0) { /* I did see EAGAIN happening here */ if (r < 0 && errno == EAGAIN) goto next; break; } buff[r] = '\0'; strbuf_append_str(buf_out, buff); next: t = time(NULL); } close(pipeout[0]); /* Prevent having zombie child process */ int status; safe_waitpid(child, &status, 0); if (status != 0 || buf_out == NULL) { /* unstrip didnt exit with exit code 0, or we timed out */ strbuf_free(buf_out); return NULL; } return strbuf_free_nobuf(buf_out); } char *get_backtrace(const char *dump_dir_name, unsigned timeout_sec, const char *debuginfo_dirs) { INITIALIZE_LIBABRT(); struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ 0); if (!dd) return NULL; char *executable = dd_load_text(dd, FILENAME_EXECUTABLE); dd_close(dd); /* Let user know what's going on */ log(_("Generating backtrace")); unsigned i = 0; char *args[25]; args[i++] = (char*)"gdb"; args[i++] = (char*)"-batch"; struct strbuf *set_debug_file_directory = strbuf_new(); unsigned auto_load_base_index = 0; if(debuginfo_dirs == NULL) { // set non-existent debug file directory to prevent resolving // function names - we need offsets for core backtrace. strbuf_append_str(set_debug_file_directory, "set debug-file-directory /"); } else { strbuf_append_str(set_debug_file_directory, "set debug-file-directory /usr/lib/debug"); struct strbuf *debug_directories = strbuf_new(); const char *p = debuginfo_dirs; while (1) { while (*p == ':') p++; if (*p == '\0') break; const char *colon_or_nul = strchrnul(p, ':'); strbuf_append_strf(debug_directories, "%s%.*s/usr/lib/debug", (debug_directories->len == 0 ? "" : ":"), (int)(colon_or_nul - p), p); p = colon_or_nul; } strbuf_append_strf(set_debug_file_directory, ":%s", debug_directories->buf); args[i++] = (char*)"-iex"; auto_load_base_index = i; args[i++] = xasprintf("add-auto-load-safe-path %s", debug_directories->buf); args[i++] = (char*)"-iex"; args[i++] = xasprintf("add-auto-load-scripts-directory %s", debug_directories->buf); strbuf_free(debug_directories); } args[i++] = (char*)"-ex"; const unsigned debug_dir_cmd_index = i++; args[debug_dir_cmd_index] = strbuf_free_nobuf(set_debug_file_directory); /* "file BINARY_FILE" is needed, without it gdb cannot properly * unwind the stack. Currently the unwind information is located * in .eh_frame which is stored only in binary, not in coredump * or debuginfo. * * Fedora GDB does not strictly need it, it will find the binary * by its build-id. But for binaries either without build-id * (= built on non-Fedora GCC) or which do not have * their debuginfo rpm installed gdb would not find BINARY_FILE * so it is still makes sense to supply "file BINARY_FILE". * * Unfortunately, "file BINARY_FILE" doesn't work well if BINARY_FILE * was deleted (as often happens during system updates): * gdb uses specified BINARY_FILE * even if it is completely unrelated to the coredump. * See https://bugzilla.redhat.com/show_bug.cgi?id=525721 * * TODO: check mtimes on COREFILE and BINARY_FILE and not supply * BINARY_FILE if it is newer (to at least avoid gdb complaining). */ args[i++] = (char*)"-ex"; const unsigned file_cmd_index = i++; args[file_cmd_index] = xasprintf("file %s", executable); free(executable); args[i++] = (char*)"-ex"; const unsigned core_cmd_index = i++; args[core_cmd_index] = xasprintf("core-file %s/"FILENAME_COREDUMP, dump_dir_name); args[i++] = (char*)"-ex"; const unsigned bt_cmd_index = i++; /*args[9] = ... see below */ args[i++] = (char*)"-ex"; args[i++] = (char*)"info sharedlib"; /* glibc's abort() stores its message in __abort_msg variable */ args[i++] = (char*)"-ex"; args[i++] = (char*)"print (char*)__abort_msg"; args[i++] = (char*)"-ex"; args[i++] = (char*)"print (char*)__glib_assert_msg"; args[i++] = (char*)"-ex"; args[i++] = (char*)"info all-registers"; args[i++] = (char*)"-ex"; const unsigned dis_cmd_index = i++; args[dis_cmd_index] = (char*)"disassemble"; args[i++] = NULL; /* Get the backtrace, but try to cap its size */ /* Limit bt depth. With no limit, gdb sometimes OOMs the machine */ unsigned bt_depth = 1024; const char *thread_apply_all = "thread apply all"; const char *full = " full"; char *bt = NULL; while (1) { args[bt_cmd_index] = xasprintf("%s backtrace %u%s", thread_apply_all, bt_depth, full); bt = exec_vp(args, /*redirect_stderr:*/ 1, timeout_sec, NULL); free(args[bt_cmd_index]); if ((bt && strnlen(bt, 256*1024) < 256*1024) || bt_depth <= 32) { break; } bt_depth /= 2; if (bt) log("Backtrace is too big (%u bytes), reducing depth to %u", (unsigned)strlen(bt), bt_depth); else /* (NB: in fact, current impl. of exec_vp() never returns NULL) */ log("Failed to generate backtrace, reducing depth to %u", bt_depth); free(bt); /* Replace -ex disassemble (which disasms entire function $pc points to) * to a version which analyzes limited, small patch of code around $pc. * (Users reported a case where bare "disassemble" attempted to process * entire .bss). * TODO: what if "$pc-N" underflows? in my test, this happens: * Dump of assembler code from 0xfffffffffffffff0 to 0x30: * End of assembler dump. * (IOW: "empty" dump) */ args[dis_cmd_index] = (char*)"disassemble $pc-20, $pc+64"; if (bt_depth <= 64 && thread_apply_all[0] != '\0') { /* This program likely has gazillion threads, dont try to bt them all */ bt_depth = 128; thread_apply_all = ""; } if (bt_depth <= 64 && full[0] != '\0') { /* Looks like there are gigantic local structures or arrays, disable "full" bt */ bt_depth = 128; full = ""; } } if (auto_load_base_index > 0) { free(args[auto_load_base_index]); free(args[auto_load_base_index + 2]); } free(args[debug_dir_cmd_index]); free(args[file_cmd_index]); free(args[core_cmd_index]); return bt; } char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = NULL; if (g_settings_privatereports) dd = create_dump_dir_from_problem_data_ext(pd, g_settings_dump_location, 0); else dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info("problem id: '%s'", problem_id); return problem_id; } bool dir_is_in_dump_location(const char *dir_name) { unsigned len = strlen(g_settings_dump_location); /* The path must start with "g_settings_dump_location" */ if (strncmp(dir_name, g_settings_dump_location, len) != 0) { log_debug("Bad parent directory: '%s' not in '%s'", g_settings_dump_location, dir_name); return false; } /* and must be a sub-directory of the g_settings_dump_location dir */ const char *base_name = dir_name + len; while (*base_name && *base_name == '/') ++base_name; if (*(base_name - 1) != '/' || !str_is_correct_filename(base_name)) { log_debug("Invalid dump directory name: '%s'", base_name); return false; } /* and we are sure it is a directory */ struct stat sb; if (lstat(dir_name, &sb) < 0) { VERB2 perror_msg("stat('%s')", dir_name); return errno== ENOENT; } return S_ISDIR(sb.st_mode); } bool dir_has_correct_permissions(const char *dir_name) { if (g_settings_privatereports) { struct stat statbuf; if (lstat(dir_name, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode)) { error_msg("Path '%s' isn't directory", dir_name); return false; } /* Get ABRT's group gid */ struct group *gr = getgrnam("abrt"); if (!gr) { error_msg("Group 'abrt' does not exist"); return false; } if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07) return false; } return true; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1506_3
crossvul-cpp_data_good_3576_3
/* * transform.c: support for building and running transformers * * Copyright (C) 2007-2011 David Lutterkort * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Lutterkort <dlutter@redhat.com> */ #include <config.h> #include <fnmatch.h> #include <glob.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <selinux/selinux.h> #include <stdbool.h> #include "internal.h" #include "memory.h" #include "augeas.h" #include "syntax.h" #include "transform.h" #include "errcode.h" static const int fnm_flags = FNM_PATHNAME; static const int glob_flags = GLOB_NOSORT; /* Extension for newly created files */ #define EXT_AUGNEW ".augnew" /* Extension for backup files */ #define EXT_AUGSAVE ".augsave" /* Loaded files are tracked underneath METATREE. When a file with name * FNAME is loaded, certain entries are made under METATREE / FNAME: * path : path where tree for FNAME is put * mtime : time of last modification of the file as reported by stat(2) * lens/info : information about where the applied lens was loaded from * lens/id : unique hexadecimal id of the lens * error : indication of errors during processing FNAME, or NULL * if processing succeeded * error/pos : position in file where error occured (for get errors) * error/path: path to tree node where error occurred (for put errors) * error/message : human-readable error message */ static const char *const s_path = "path"; static const char *const s_lens = "lens"; static const char *const s_info = "info"; static const char *const s_mtime = "mtime"; static const char *const s_error = "error"; /* These are all put underneath "error" */ static const char *const s_pos = "pos"; static const char *const s_message = "message"; static const char *const s_line = "line"; static const char *const s_char = "char"; /* * Filters */ struct filter *make_filter(struct string *glb, unsigned int include) { struct filter *f; make_ref(f); f->glob = glb; f->include = include; return f; } void free_filter(struct filter *f) { if (f == NULL) return; assert(f->ref == 0); unref(f->next, filter); unref(f->glob, string); free(f); } static const char *pathbase(const char *path) { const char *p = strrchr(path, SEP); return (p == NULL) ? path : p + 1; } static bool is_excl(struct tree *f) { return streqv(f->label, "excl") && f->value != NULL; } static bool is_incl(struct tree *f) { return streqv(f->label, "incl") && f->value != NULL; } static bool is_regular_file(const char *path) { int r; struct stat st; r = stat(path, &st); if (r < 0) return false; return S_ISREG(st.st_mode); } static char *mtime_as_string(struct augeas *aug, const char *fname) { int r; struct stat st; char *result = NULL; if (fname == NULL) { result = strdup("0"); ERR_NOMEM(result == NULL, aug); goto done; } r = stat(fname, &st); if (r < 0) { /* If we fail to stat, silently ignore the error * and report an impossible mtime */ result = strdup("0"); ERR_NOMEM(result == NULL, aug); } else { r = xasprintf(&result, "%ld", (long) st.st_mtime); ERR_NOMEM(r < 0, aug); } done: return result; error: FREE(result); return NULL; } static bool file_current(struct augeas *aug, const char *fname, struct tree *finfo) { struct tree *mtime = tree_child(finfo, s_mtime); struct tree *file = NULL, *path = NULL; int r; struct stat st; int64_t mtime_i; if (mtime == NULL || mtime->value == NULL) return false; r = xstrtoint64(mtime->value, 10, &mtime_i); if (r < 0) { /* Ignore silently and err on the side of caution */ return false; } r = stat(fname, &st); if (r < 0) return false; if (mtime_i != (int64_t) st.st_mtime) return false; path = tree_child(finfo, s_path); if (path == NULL) return false; file = tree_find(aug, path->value); return (file != NULL && ! file->dirty); } static int filter_generate(struct tree *xfm, const char *root, int *nmatches, char ***matches) { glob_t globbuf; int gl_flags = glob_flags; int r; int ret = 0; char **pathv = NULL; int pathc = 0; int root_prefix = strlen(root) - 1; *nmatches = 0; *matches = NULL; MEMZERO(&globbuf, 1); list_for_each(f, xfm->children) { char *globpat = NULL; if (! is_incl(f)) continue; pathjoin(&globpat, 2, root, f->value); r = glob(globpat, gl_flags, NULL, &globbuf); free(globpat); if (r != 0 && r != GLOB_NOMATCH) { ret = -1; goto error; } gl_flags |= GLOB_APPEND; } pathc = globbuf.gl_pathc; int pathind = 0; if (ALLOC_N(pathv, pathc) < 0) goto error; for (int i=0; i < pathc; i++) { const char *path = globbuf.gl_pathv[i] + root_prefix; bool include = true; list_for_each(e, xfm->children) { if (! is_excl(e)) continue; if (strchr(e->value, SEP) == NULL) path = pathbase(path); if ((r = fnmatch(e->value, path, fnm_flags)) == 0) { include = false; } } if (include) include = is_regular_file(globbuf.gl_pathv[i]); if (include) { pathv[pathind] = strdup(globbuf.gl_pathv[i]); if (pathv[pathind] == NULL) goto error; pathind += 1; } } pathc = pathind; if (REALLOC_N(pathv, pathc) == -1) goto error; *matches = pathv; *nmatches = pathc; done: globfree(&globbuf); return ret; error: if (pathv != NULL) for (int i=0; i < pathc; i++) free(pathv[i]); free(pathv); ret = -1; goto done; } static int filter_matches(struct tree *xfm, const char *path) { int found = 0; list_for_each(f, xfm->children) { if (is_incl(f) && fnmatch(f->value, path, fnm_flags) == 0) { found = 1; break; } } if (! found) return 0; list_for_each(f, xfm->children) { if (is_excl(f) && (fnmatch(f->value, path, fnm_flags) == 0)) return 0; } return 1; } /* * Transformers */ struct transform *make_transform(struct lens *lens, struct filter *filter) { struct transform *xform; make_ref(xform); xform->lens = lens; xform->filter = filter; return xform; } void free_transform(struct transform *xform) { if (xform == NULL) return; assert(xform->ref == 0); unref(xform->lens, lens); unref(xform->filter, filter); free(xform); } static char *err_path(const char *filename) { char *result = NULL; if (filename == NULL) pathjoin(&result, 2, AUGEAS_META_FILES, s_error); else pathjoin(&result, 3, AUGEAS_META_FILES, filename, s_error); return result; } ATTRIBUTE_FORMAT(printf, 4, 5) static void err_set(struct augeas *aug, struct tree *err_info, const char *sub, const char *format, ...) { int r; va_list ap; char *value = NULL; struct tree *tree = NULL; va_start(ap, format); r = vasprintf(&value, format, ap); va_end(ap); if (r < 0) value = NULL; ERR_NOMEM(r < 0, aug); tree = tree_child_cr(err_info, sub); ERR_NOMEM(tree == NULL, aug); r = tree_set_value(tree, value); ERR_NOMEM(r < 0, aug); error: free(value); } /* Record an error in the tree. The error will show up underneath * /augeas/FILENAME/error if filename is not NULL, and underneath * /augeas/text/PATH otherwise. PATH is the path to the toplevel node in * the tree where the lens application happened. When STATUS is NULL, just * clear any error associated with FILENAME in the tree. */ static int store_error(struct augeas *aug, const char *filename, const char *path, const char *status, int errnum, const struct lns_error *err, const char *text) { struct tree *err_info = NULL, *finfo = NULL; char *fip = NULL; int r; int result = -1; if (filename != NULL) { r = pathjoin(&fip, 2, AUGEAS_META_FILES, filename); } else { r = pathjoin(&fip, 2, AUGEAS_META_TEXT, path); } ERR_NOMEM(r < 0, aug); finfo = tree_find_cr(aug, fip); ERR_BAIL(aug); if (status != NULL) { err_info = tree_child_cr(finfo, s_error); ERR_NOMEM(err_info == NULL, aug); r = tree_set_value(err_info, status); ERR_NOMEM(r < 0, aug); /* Errors from err_set are ignored on purpose. We try * to report as much as we can */ if (err != NULL) { if (err->pos >= 0) { size_t line, ofs; err_set(aug, err_info, s_pos, "%d", err->pos); if (text != NULL) { calc_line_ofs(text, err->pos, &line, &ofs); err_set(aug, err_info, s_line, "%zd", line); err_set(aug, err_info, s_char, "%zd", ofs); } } if (err->path != NULL) { err_set(aug, err_info, s_path, "%s%s", path, err->path); } if (err->lens != NULL) { char *fi = format_info(err->lens->info); if (fi != NULL) { err_set(aug, err_info, s_lens, "%s", fi); free(fi); } } err_set(aug, err_info, s_message, "%s", err->message); } else if (errnum != 0) { const char *msg = strerror(errnum); err_set(aug, err_info, s_message, "%s", msg); } } else { /* No error, nuke the error node if it exists */ err_info = tree_child(finfo, s_error); if (err_info != NULL) { tree_unlink_children(aug, err_info); pathx_symtab_remove_descendants(aug->symtab, err_info); tree_unlink(err_info); } } tree_clean(finfo); result = 0; error: free(fip); return result; } /* Set up the file information in the /augeas tree. * * NODE must be the path to the file contents, and start with /files. * LENS is the lens used to transform the file. * Create entries under /augeas/NODE with some metadata about the file. * * Returns 0 on success, -1 on error */ static int add_file_info(struct augeas *aug, const char *node, struct lens *lens, const char *lens_name, const char *filename, bool force_reload) { struct tree *file, *tree; char *tmp = NULL; int r; char *path = NULL; int result = -1; if (lens == NULL) return -1; r = pathjoin(&path, 2, AUGEAS_META_TREE, node); ERR_NOMEM(r < 0, aug); file = tree_find_cr(aug, path); ERR_BAIL(aug); /* Set 'path' */ tree = tree_child_cr(file, s_path); ERR_NOMEM(tree == NULL, aug); r = tree_set_value(tree, node); ERR_NOMEM(r < 0, aug); /* Set 'mtime' */ if (force_reload) { tmp = strdup("0"); ERR_NOMEM(tmp == NULL, aug); } else { tmp = mtime_as_string(aug, filename); ERR_BAIL(aug); } tree = tree_child_cr(file, s_mtime); ERR_NOMEM(tree == NULL, aug); tree_store_value(tree, &tmp); /* Set 'lens/info' */ tmp = format_info(lens->info); ERR_NOMEM(tmp == NULL, aug); tree = tree_path_cr(file, 2, s_lens, s_info); ERR_NOMEM(tree == NULL, aug); r = tree_set_value(tree, tmp); ERR_NOMEM(r < 0, aug); FREE(tmp); /* Set 'lens' */ tree = tree->parent; r = tree_set_value(tree, lens_name); ERR_NOMEM(r < 0, aug); tree_clean(file); result = 0; error: free(path); free(tmp); return result; } static char *append_newline(char *text, size_t len) { /* Try to append a newline; this is a big hack to work */ /* around the fact that lenses generally break if the */ /* file does not end with a newline. */ if (len == 0 || text[len-1] != '\n') { if (REALLOC_N(text, len+2) == 0) { text[len] = '\n'; text[len+1] = '\0'; } } return text; } /* Turn the file name FNAME, which starts with aug->root, into * a path in the tree underneath /files */ static char *file_name_path(struct augeas *aug, const char *fname) { char *path = NULL; pathjoin(&path, 2, AUGEAS_FILES_TREE, fname + strlen(aug->root) - 1); return path; } static int load_file(struct augeas *aug, struct lens *lens, const char *lens_name, char *filename) { char *text = NULL; const char *err_status = NULL; struct tree *tree = NULL; char *path = NULL; struct lns_error *err = NULL; struct span *span = NULL; int result = -1, r, text_len = 0; path = file_name_path(aug, filename); ERR_NOMEM(path == NULL, aug); r = add_file_info(aug, path, lens, lens_name, filename, false); if (r < 0) goto done; text = xread_file(filename); if (text == NULL) { err_status = "read_failed"; goto done; } text_len = strlen(text); text = append_newline(text, text_len); struct info *info; make_ref(info); make_ref(info->filename); info->filename->str = strdup(filename); info->error = aug->error; info->flags = aug->flags; info->first_line = 1; if (aug->flags & AUG_ENABLE_SPAN) { span = make_span(info); ERR_NOMEM(span == NULL, info); } tree = lns_get(info, lens, text, &err); unref(info, info); if (err != NULL) { err_status = "parse_failed"; goto done; } tree_replace(aug, path, tree); /* top level node span entire file length */ if (span != NULL && tree != NULL) { tree->parent->span = span; tree->parent->span->span_start = 0; tree->parent->span->span_end = text_len; } tree = NULL; result = 0; done: store_error(aug, filename + strlen(aug->root) - 1, path, err_status, errno, err, text); error: free_lns_error(err); free(path); free_tree(tree); free(text); return result; } /* The lens for a transform can be referred to in one of two ways: * either by a fully qualified name "Module.lens" or by the special * syntax "@Module"; the latter means we should take the lens from the * autoload transform for Module */ static struct lens *lens_from_name(struct augeas *aug, const char *name) { struct lens *result = NULL; if (name[0] == '@') { struct module *modl = NULL; for (modl = aug->modules; modl != NULL && !streqv(modl->name, name + 1); modl = modl->next); ERR_THROW(modl == NULL, aug, AUG_ENOLENS, "Could not find module %s", name + 1); ERR_THROW(modl->autoload == NULL, aug, AUG_ENOLENS, "No autoloaded lens in module %s", name + 1); result = modl->autoload->lens; } else { result = lens_lookup(aug, name); } ERR_THROW(result == NULL, aug, AUG_ENOLENS, "Can not find lens %s", name); return result; error: return NULL; } int text_store(struct augeas *aug, const char *lens_path, const char *path, const char *text) { struct info *info = NULL; struct lns_error *err = NULL; struct tree *tree = NULL; struct span *span = NULL; int result = -1; const char *err_status = NULL; struct lens *lens = NULL; lens = lens_from_name(aug, lens_path); if (lens == NULL) { goto done; } make_ref(info); info->first_line = 1; info->last_line = 1; info->first_column = 1; info->last_column = strlen(text); tree = lns_get(info, lens, text, &err); if (err != NULL) { err_status = "parse_failed"; goto done; } unref(info, info); tree_replace(aug, path, tree); /* top level node span entire file length */ if (span != NULL && tree != NULL) { tree->parent->span = span; tree->parent->span->span_start = 0; tree->parent->span->span_end = strlen(text); } tree = NULL; result = 0; done: store_error(aug, NULL, path, err_status, errno, err, text); free_tree(tree); free_lns_error(err); return result; } const char *xfm_lens_name(struct tree *xfm) { struct tree *l = tree_child(xfm, s_lens); if (l == NULL) return "(unknown)"; if (l->value == NULL) return "(noname)"; return l->value; } static struct lens *xfm_lens(struct augeas *aug, struct tree *xfm, const char **lens_name) { struct tree *l = NULL; for (l = xfm->children; l != NULL && !streqv("lens", l->label); l = l->next); if (l == NULL || l->value == NULL) return NULL; *lens_name = l->value; return lens_from_name(aug, l->value); } static void xfm_error(struct tree *xfm, const char *msg) { char *v = strdup(msg); char *l = strdup("error"); if (l == NULL || v == NULL) return; tree_append(xfm, l, v); } int transform_validate(struct augeas *aug, struct tree *xfm) { struct tree *l = NULL; for (struct tree *t = xfm->children; t != NULL; ) { if (streqv(t->label, "lens")) { l = t; } else if ((is_incl(t) || (is_excl(t) && strchr(t->value, SEP) != NULL)) && t->value[0] != SEP) { /* Normalize relative paths to absolute ones */ int r; r = REALLOC_N(t->value, strlen(t->value) + 2); ERR_NOMEM(r < 0, aug); memmove(t->value + 1, t->value, strlen(t->value) + 1); t->value[0] = SEP; } if (streqv(t->label, "error")) { struct tree *del = t; t = del->next; tree_unlink(del); } else { t = t->next; } } if (l == NULL) { xfm_error(xfm, "missing a child with label 'lens'"); return -1; } if (l->value == NULL) { xfm_error(xfm, "the 'lens' node does not contain a lens name"); return -1; } lens_from_name(aug, l->value); ERR_BAIL(aug); return 0; error: xfm_error(xfm, aug->error->details); return -1; } void transform_file_error(struct augeas *aug, const char *status, const char *filename, const char *format, ...) { char *ep = err_path(filename); struct tree *err; char *msg; va_list ap; int r; err = tree_find_cr(aug, ep); if (err == NULL) return; tree_unlink_children(aug, err); tree_set_value(err, status); err = tree_child_cr(err, s_message); if (err == NULL) return; va_start(ap, format); r = vasprintf(&msg, format, ap); va_end(ap); if (r < 0) return; tree_set_value(err, msg); free(msg); } static struct tree *file_info(struct augeas *aug, const char *fname) { char *path = NULL; struct tree *result = NULL; int r; r = pathjoin(&path, 2, AUGEAS_META_FILES, fname); ERR_NOMEM(r < 0, aug); result = tree_find(aug, path); ERR_BAIL(aug); error: free(path); return result; } int transform_load(struct augeas *aug, struct tree *xfm) { int nmatches = 0; char **matches; const char *lens_name; struct lens *lens = xfm_lens(aug, xfm, &lens_name); int r; if (lens == NULL) { // FIXME: Record an error and return 0 return -1; } r = filter_generate(xfm, aug->root, &nmatches, &matches); if (r == -1) return -1; for (int i=0; i < nmatches; i++) { const char *filename = matches[i] + strlen(aug->root) - 1; struct tree *finfo = file_info(aug, filename); if (finfo != NULL && !finfo->dirty && tree_child(finfo, s_lens) != NULL) { const char *s = xfm_lens_name(finfo); char *fpath = file_name_path(aug, matches[i]); transform_file_error(aug, "mxfm_load", filename, "Lenses %s and %s could be used to load this file", s, lens_name); aug_rm(aug, fpath); free(fpath); } else if (!file_current(aug, matches[i], finfo)) { load_file(aug, lens, lens_name, matches[i]); } if (finfo != NULL) finfo->dirty = 0; FREE(matches[i]); } lens_release(lens); free(matches); return 0; } int transform_applies(struct tree *xfm, const char *path) { if (STRNEQLEN(path, AUGEAS_FILES_TREE, strlen(AUGEAS_FILES_TREE)) || path[strlen(AUGEAS_FILES_TREE)] != SEP) return 0; return filter_matches(xfm, path + strlen(AUGEAS_FILES_TREE)); } static int transfer_file_attrs(FILE *from, FILE *to, const char **err_status) { struct stat st; int ret = 0; int selinux_enabled = (is_selinux_enabled() > 0); security_context_t con = NULL; int from_fd = fileno(from); int to_fd = fileno(to); ret = fstat(from_fd, &st); if (ret < 0) { *err_status = "replace_stat"; return -1; } if (selinux_enabled) { if (fgetfilecon(from_fd, &con) < 0 && errno != ENOTSUP) { *err_status = "replace_getfilecon"; return -1; } } if (fchown(to_fd, st.st_uid, st.st_gid) < 0) { *err_status = "replace_chown"; return -1; } if (fchmod(to_fd, st.st_mode) < 0) { *err_status = "replace_chmod"; return -1; } if (selinux_enabled && con != NULL) { if (fsetfilecon(to_fd, con) < 0 && errno != ENOTSUP) { *err_status = "replace_setfilecon"; return -1; } freecon(con); } return 0; } /* Try to rename FROM to TO. If that fails with an error other than EXDEV * or EBUSY, return -1. If the failure is EXDEV or EBUSY (which we assume * means that FROM or TO is a bindmounted file), and COPY_IF_RENAME_FAILS * is true, copy the contents of FROM into TO and delete FROM. * * Return 0 on success (either rename succeeded or we copied the contents * over successfully), -1 on failure. */ static int clone_file(const char *from, const char *to, const char **err_status, int copy_if_rename_fails) { FILE *from_fp = NULL, *to_fp = NULL; char buf[BUFSIZ]; size_t len; int result = -1; if (rename(from, to) == 0) return 0; if ((errno != EXDEV && errno != EBUSY) || !copy_if_rename_fails) { *err_status = "rename"; return -1; } /* rename not possible, copy file contents */ if (!(from_fp = fopen(from, "r"))) { *err_status = "clone_open_src"; goto done; } if (!(to_fp = fopen(to, "w"))) { *err_status = "clone_open_dst"; goto done; } if (transfer_file_attrs(from_fp, to_fp, err_status) < 0) goto done; while ((len = fread(buf, 1, BUFSIZ, from_fp)) > 0) { if (fwrite(buf, 1, len, to_fp) != len) { *err_status = "clone_write"; goto done; } } if (ferror(from_fp)) { *err_status = "clone_read"; goto done; } if (fflush(to_fp) != 0) { *err_status = "clone_flush"; goto done; } if (fsync(fileno(to_fp)) < 0) { *err_status = "clone_sync"; goto done; } result = 0; done: if (from_fp != NULL) fclose(from_fp); if (to_fp != NULL && fclose(to_fp) != 0) result = -1; if (result != 0) unlink(to); if (result == 0) unlink(from); return result; } static char *strappend(const char *s1, const char *s2) { size_t len = strlen(s1) + strlen(s2); char *result = NULL, *p; if (ALLOC_N(result, len + 1) < 0) return NULL; p = stpcpy(result, s1); stpcpy(p, s2); return result; } static int file_saved_event(struct augeas *aug, const char *path) { const char *saved = strrchr(AUGEAS_EVENTS_SAVED, SEP) + 1; struct pathx *px; struct tree *dummy; int r; px = pathx_aug_parse(aug, aug->origin, NULL, AUGEAS_EVENTS_SAVED "[last()]", true); ERR_BAIL(aug); if (pathx_find_one(px, &dummy) == 1) { r = tree_insert(px, saved, 0); if (r < 0) goto error; } if (! tree_set(px, path)) goto error; free_pathx(px); return 0; error: free_pathx(px); return -1; } /* * Save TREE->CHILDREN into the file PATH using the lens from XFORM. Errors * are noted in the /augeas/files hierarchy in AUG->ORIGIN under * PATH/error. * * Writing the file happens by first writing into a temp file, transferring all * file attributes of PATH to the temp file, and then renaming the temp file * back to PATH. * * Temp files are created alongside the destination file to enable the rename, * which may be the canonical path (PATH_canon) if PATH is a symlink. * * If the AUG_SAVE_NEWFILE flag is set, instead rename to PATH.augnew rather * than PATH. If AUG_SAVE_BACKUP is set, move the original to PATH.augsave. * (Always PATH.aug{new,save} irrespective of whether PATH is a symlink.) * * If the rename fails, and the entry AUGEAS_COPY_IF_FAILURE exists in * AUG->ORIGIN, PATH is instead overwritten by copying file contents. * * The table below shows the locations for each permutation. * * PATH save flag temp file dest file backup? * regular - PATH.augnew.XXXX PATH - * regular BACKUP PATH.augnew.XXXX PATH PATH.augsave * regular NEWFILE PATH.augnew.XXXX PATH.augnew - * symlink - PATH_canon.XXXX PATH_canon - * symlink BACKUP PATH_canon.XXXX PATH_canon PATH.augsave * symlink NEWFILE PATH.augnew.XXXX PATH.augnew - * * Return 0 on success, -1 on failure. */ int transform_save(struct augeas *aug, struct tree *xfm, const char *path, struct tree *tree) { int fd; FILE *fp = NULL, *augorig_canon_fp = NULL; char *augtemp = NULL, *augnew = NULL, *augorig = NULL, *augsave = NULL; char *augorig_canon = NULL, *augdest = NULL; int augorig_exists; int copy_if_rename_fails = 0; char *text = NULL; const char *filename = path + strlen(AUGEAS_FILES_TREE) + 1; const char *err_status = NULL; char *dyn_err_status = NULL; struct lns_error *err = NULL; const char *lens_name; struct lens *lens = xfm_lens(aug, xfm, &lens_name); int result = -1, r; bool force_reload; errno = 0; if (lens == NULL) { err_status = "lens_name"; goto done; } copy_if_rename_fails = aug_get(aug, AUGEAS_COPY_IF_RENAME_FAILS, NULL) == 1; if (asprintf(&augorig, "%s%s", aug->root, filename) == -1) { augorig = NULL; goto done; } augorig_canon = canonicalize_file_name(augorig); augorig_exists = 1; if (augorig_canon == NULL) { if (errno == ENOENT) { augorig_canon = augorig; augorig_exists = 0; } else { err_status = "canon_augorig"; goto done; } } if (access(augorig_canon, R_OK) == 0) { augorig_canon_fp = fopen(augorig_canon, "r"); text = xfread_file(augorig_canon_fp); } else { text = strdup(""); } if (text == NULL) { err_status = "put_read"; goto done; } text = append_newline(text, strlen(text)); /* Figure out where to put the .augnew and temp file. If no .augnew file then put the temp file next to augorig_canon, else next to .augnew. */ if (aug->flags & AUG_SAVE_NEWFILE) { if (xasprintf(&augnew, "%s" EXT_AUGNEW, augorig) < 0) { err_status = "augnew_oom"; goto done; } augdest = augnew; } else { augdest = augorig_canon; } if (xasprintf(&augtemp, "%s.XXXXXX", augdest) < 0) { err_status = "augtemp_oom"; goto done; } // FIXME: We might have to create intermediate directories // to be able to write augnew, but we have no idea what permissions // etc. they should get. Just the process default ? fd = mkstemp(augtemp); if (fd < 0) { err_status = "mk_augtemp"; goto done; } fp = fdopen(fd, "w"); if (fp == NULL) { err_status = "open_augtemp"; goto done; } if (augorig_exists) { if (transfer_file_attrs(augorig_canon_fp, fp, &err_status) != 0) { err_status = "xfer_attrs"; goto done; } } if (tree != NULL) lns_put(fp, lens, tree->children, text, &err); if (ferror(fp)) { err_status = "error_augtemp"; goto done; } if (fflush(fp) != 0) { err_status = "flush_augtemp"; goto done; } if (fsync(fileno(fp)) < 0) { err_status = "sync_augtemp"; goto done; } if (fclose(fp) != 0) { err_status = "close_augtemp"; fp = NULL; goto done; } fp = NULL; if (err != NULL) { err_status = err->pos >= 0 ? "parse_skel_failed" : "put_failed"; unlink(augtemp); goto done; } { char *new_text = xread_file(augtemp); int same = 0; if (new_text == NULL) { err_status = "read_augtemp"; goto done; } same = STREQ(text, new_text); FREE(new_text); if (same) { result = 0; unlink(augtemp); goto done; } else if (aug->flags & AUG_SAVE_NOOP) { result = 1; unlink(augtemp); goto done; } } if (!(aug->flags & AUG_SAVE_NEWFILE)) { if (augorig_exists && (aug->flags & AUG_SAVE_BACKUP)) { r = xasprintf(&augsave, "%s" EXT_AUGSAVE, augorig); if (r == -1) { augsave = NULL; goto done; } r = clone_file(augorig_canon, augsave, &err_status, 1); if (r != 0) { dyn_err_status = strappend(err_status, "_augsave"); goto done; } } } r = clone_file(augtemp, augdest, &err_status, copy_if_rename_fails); if (r != 0) { dyn_err_status = strappend(err_status, "_augtemp"); goto done; } result = 1; done: force_reload = aug->flags & AUG_SAVE_NEWFILE; r = add_file_info(aug, path, lens, lens_name, augorig, force_reload); if (r < 0) { err_status = "file_info"; result = -1; } if (result > 0) { r = file_saved_event(aug, path); if (r < 0) { err_status = "saved_event"; result = -1; } } { const char *emsg = dyn_err_status == NULL ? err_status : dyn_err_status; store_error(aug, filename, path, emsg, errno, err, text); } free(dyn_err_status); lens_release(lens); free(text); free(augtemp); free(augnew); if (augorig_canon != augorig) free(augorig_canon); free(augorig); free(augsave); free_lns_error(err); if (fp != NULL) fclose(fp); if (augorig_canon_fp != NULL) fclose(augorig_canon_fp); return result; } int text_retrieve(struct augeas *aug, const char *lens_name, const char *path, struct tree *tree, const char *text_in, char **text_out) { struct memstream ms; bool ms_open; const char *err_status = NULL; char *dyn_err_status = NULL; struct lns_error *err = NULL; struct lens *lens = NULL; int result = -1, r; MEMZERO(&ms, 1); errno = 0; lens = lens_from_name(aug, lens_name); if (lens == NULL) { err_status = "lens_name"; goto done; } r = init_memstream(&ms); if (r < 0) { err_status = "init_memstream"; goto done; } ms_open = true; if (tree != NULL) lns_put(ms.stream, lens, tree->children, text_in, &err); r = close_memstream(&ms); ms_open = false; if (r < 0) { err_status = "close_memstream"; goto done; } *text_out = ms.buf; ms.buf = NULL; if (err != NULL) { err_status = err->pos >= 0 ? "parse_skel_failed" : "put_failed"; goto done; } result = 0; done: { const char *emsg = dyn_err_status == NULL ? err_status : dyn_err_status; store_error(aug, NULL, path, emsg, errno, err, text_in); } free(dyn_err_status); lens_release(lens); if (result < 0) { free(*text_out); *text_out = NULL; } free_lns_error(err); if (ms_open) close_memstream(&ms); return result; } int remove_file(struct augeas *aug, struct tree *tree) { char *path = NULL; const char *filename = NULL; const char *err_status = NULL; char *dyn_err_status = NULL; char *augsave = NULL, *augorig = NULL, *augorig_canon = NULL; int r; path = path_of_tree(tree); if (path == NULL) { err_status = "path_of_tree"; goto error; } filename = path + strlen(AUGEAS_META_FILES); if ((augorig = strappend(aug->root, filename + 1)) == NULL) { err_status = "root_file"; goto error; } augorig_canon = canonicalize_file_name(augorig); if (augorig_canon == NULL) { if (errno == ENOENT) { goto done; } else { err_status = "canon_augorig"; goto error; } } r = file_saved_event(aug, path + strlen(AUGEAS_META_TREE)); if (r < 0) { err_status = "saved_event"; goto error; } if (aug->flags & AUG_SAVE_NOOP) goto done; if (aug->flags & AUG_SAVE_BACKUP) { /* Move file to one with extension .augsave */ r = asprintf(&augsave, "%s" EXT_AUGSAVE, augorig_canon); if (r == -1) { augsave = NULL; goto error; } r = clone_file(augorig_canon, augsave, &err_status, 1); if (r != 0) { dyn_err_status = strappend(err_status, "_augsave"); goto error; } } else { /* Unlink file */ r = unlink(augorig_canon); if (r < 0) { err_status = "unlink_orig"; goto error; } } tree_unlink(tree); done: free(path); free(augorig); free(augorig_canon); free(augsave); return 0; error: { const char *emsg = dyn_err_status == NULL ? err_status : dyn_err_status; store_error(aug, filename, path, emsg, errno, NULL, NULL); } free(path); free(augorig); free(augorig_canon); free(augsave); free(dyn_err_status); return -1; } /* * Local variables: * indent-tabs-mode: nil * c-indent-level: 4 * c-basic-offset: 4 * tab-width: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-59/c/good_3576_3
crossvul-cpp_data_bad_1673_0
/* abrt-hook-ccpp.cpp - the hook for C/C++ crashing program Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com) Copyright (C) 2009 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/utsname.h> #include "libabrt.h" #include <selinux/selinux.h> #ifdef ENABLE_DUMP_TIME_UNWIND #include <satyr/abrt.h> #include <satyr/utils.h> #endif /* ENABLE_DUMP_TIME_UNWIND */ static int g_user_core_flags; static int g_need_nonrelative; /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) /* Custom version of copyfd_xyz, * one which is able to write into two descriptors at once. */ #define CONFIG_FEATURE_COPYBUF_KB 4 static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; // truncate to 0 or even delete the second file? // No, kernel does not delete nor truncate core files. } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } /* Global data */ static char *user_pwd; static DIR *proc_cwd; static struct dump_dir *dd; /* * %s - signal number * %c - ulimit -c value * %p - pid * %u - uid * %g - gid * %t - UNIX time of dump * %e - executable filename * %i - crash thread tid * %P - global pid * %% - output one "%" */ /* Hook must be installed with exactly the same sequence of %c specifiers. * Last one, %h, may be omitted (we can find it out). */ static const char percent_specifiers[] = "%scpugtePi"; static char *core_basename = (char*) "core"; static DIR *open_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); DIR *cwd = opendir(buf); if (cwd == NULL) perror_msg("Can't open process's CWD for CompatCore"); return cwd; } /* Computes a security context of new file created by the given process with * pid in the given directory represented by file descriptor. * * On errors returns negative number. Returns 0 if the function succeeds and * computes the context and returns positive number and assigns NULL to newcon * if the security context is not needed (SELinux disabled). */ static int compute_selinux_con_for_new_file(pid_t pid, int dir_fd, security_context_t *newcon) { security_context_t srccon; security_context_t dstcon; const int r = is_selinux_enabled(); if (r == 0) { *newcon = NULL; return 1; } else if (r == -1) { perror_msg("Couldn't get state of SELinux"); return -1; } else if (r != 1) error_msg_and_die("Unexpected SELinux return value: %d", r); if (getpidcon_raw(pid, &srccon) < 0) { perror_msg("getpidcon_raw(%d)", pid); return -1; } if (fgetfilecon_raw(dir_fd, &dstcon) < 0) { perror_msg("getfilecon_raw(%s)", user_pwd); return -1; } if (security_compute_create_raw(srccon, dstcon, string_to_security_class("file"), newcon) < 0) { perror_msg("security_compute_create_raw(%s, %s, 'file')", srccon, dstcon); return -1; } return 0; } static int open_user_core(uid_t uid, uid_t fsuid, gid_t fsgid, pid_t pid, char **percent_values) { proc_cwd = open_cwd(pid); if (proc_cwd == NULL) return -1; /* http://article.gmane.org/gmane.comp.security.selinux/21842 */ security_context_t newcon; if (compute_selinux_con_for_new_file(pid, dirfd(proc_cwd), &newcon) < 0) { log_notice("Not going to create a user core due to SELinux errors"); return -1; } if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } if (g_need_nonrelative && core_basename[0] != '/') { error_msg("Current suid_dumpable policy prevents from saving core dumps according to relative core_pattern"); return -1; } /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ int user_core_fd = -1; int selinux_fail = 1; /* * These calls must be reverted as soon as possible. */ xsetegid(fsgid); xseteuid(fsuid); /* Set SELinux context like kernel when creating core dump file. * This condition is TRUE if */ if (/* SELinux is disabled */ newcon == NULL || /* or the call succeeds */ setfscreatecon_raw(newcon) >= 0) { /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ user_core_fd = openat(dirfd(proc_cwd), core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW | g_user_core_flags, 0600); /* kernel makes 0600 too */ /* Do the error check here and print the error message in order to * avoid interference in 'errno' usage caused by SELinux functions */ if (user_core_fd < 0) perror_msg("Can't open '%s' at '%s'", core_basename, user_pwd); /* Fail if SELinux is enabled and the call fails */ if (newcon != NULL && setfscreatecon_raw(NULL) < 0) perror_msg("setfscreatecon_raw(NULL)"); else selinux_fail = 0; } else perror_msg("setfscreatecon_raw(%s)", newcon); /* * DON'T JUMP OVER THIS REVERT OF THE UID/GID CHANGES */ xsetegid(0); xseteuid(0); if (user_core_fd < 0 || selinux_fail) goto user_core_fail; struct stat sb; if (fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 || sb.st_uid != fsuid ) { perror_msg("'%s' at '%s' is not a regular file with link count 1 owned by UID(%d)", core_basename, user_pwd, fsuid); goto user_core_fail; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' at '%s' to size 0", core_basename, user_pwd); goto user_core_fail; } return user_core_fd; user_core_fail: if (user_core_fd >= 0) close(user_core_fd); return -1; } static int close_user_core(int user_core_fd, off_t core_size) { if (user_core_fd >= 0 && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0)) { perror_msg("Error writing '%s' at '%s'", core_basename, user_pwd); return -1; } return 0; } /* Like xopen, but on error, unlocks and deletes dd and user core */ static int create_or_die(const char *filename, int user_core_fd) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, DEFAULT_DUMP_DIR_MODE); if (fd >= 0) { IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid)); return fd; } int sv_errno = errno; if (dd) dd_delete(dd); if (user_core_fd >= 0) close(user_core_fd); errno = sv_errno; perror_msg_and_die("Can't open '%s'", filename); } static void create_core_backtrace(pid_t tid, const char *executable, int signal_no, struct dump_dir *dd) { #ifdef ENABLE_DUMP_TIME_UNWIND if (g_verbose > 1) sr_debug_parser = true; char *error_message = NULL; char *core_bt = sr_abrt_get_core_stacktrace_from_core_hook(tid, executable, signal_no, &error_message); if (core_bt == NULL) { log("Failed to create core_backtrace: %s", error_message); free(error_message); return; } dd_save_text(dd, FILENAME_CORE_BACKTRACE, core_bt); free(core_bt); #endif /* ENABLE_DUMP_TIME_UNWIND */ } static int create_user_core(int user_core_fd, pid_t pid, off_t ulimit_c) { int err = 1; if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (close_user_core(user_core_fd, core_size) != 0) goto finito; log_notice("Saved core dump of pid %lu to '%s' at '%s' (%llu bytes)", (long)pid, core_basename, user_pwd, (long long)core_size); } err = 0; finito: if (proc_cwd != NULL) { closedir(proc_cwd); proc_cwd = NULL; } return err; } static int test_configuration(bool setting_SaveFullCore, bool setting_CreateCoreBacktrace) { if (!setting_SaveFullCore && !setting_CreateCoreBacktrace) { fprintf(stderr, "Both SaveFullCore and CreateCoreBacktrace are disabled - " "at least one of them is needed for useful report.\n"); return 1; } return 0; } static int save_crashing_binary(pid_t pid, struct dump_dir *dd) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); int src_fd_binary = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ if (src_fd_binary < 0) { log_notice("Failed to open an image of crashing binary"); return 0; } int dst_fd = openat(dd->dd_fd, FILENAME_BINARY, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, DEFAULT_DUMP_DIR_MODE); if (dst_fd < 0) { log_notice("Failed to create file '"FILENAME_BINARY"' at '%s'", dd->dd_dirname); close(src_fd_binary); return -1; } IGNORE_RESULT(fchown(dst_fd, dd->dd_uid, dd->dd_gid)); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); close(src_fd_binary); return fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0; } int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); int err = 1; logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; bool setting_SaveFullCore; bool setting_CreateCoreBacktrace; bool setting_SaveContainerizedPackageData; bool setting_StandaloneHook; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveFullCore"); setting_SaveFullCore = value ? string_to_bool(value) : true; value = get_map_string_item_or_NULL(settings, "CreateCoreBacktrace"); setting_CreateCoreBacktrace = value ? string_to_bool(value) : true; value = get_map_string_item_or_NULL(settings, "SaveContainerizedPackageData"); setting_SaveContainerizedPackageData = value && string_to_bool(value); /* Do not call abrt-action-save-package-data with process's root, if ExploreChroots is disabled. */ if (!g_settings_explorechroots) { if (setting_SaveContainerizedPackageData) log_warning("Ignoring SaveContainerizedPackageData because ExploreChroots is disabled"); setting_SaveContainerizedPackageData = false; } value = get_map_string_item_or_NULL(settings, "StandaloneHook"); setting_StandaloneHook = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } if (argc == 2 && strcmp(argv[1], "--config-test")) return test_configuration(setting_SaveFullCore, setting_CreateCoreBacktrace); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %P %i*/ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME GLOBAL_PID [TID]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t local_pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || local_pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } const char *global_pid_str = argv[8]; pid_t pid = xatoi_positive(argv[8]); pid_t tid = -1; const char *tid_str = argv[9]; if (tid_str) { tid = xatoi_positive(tid_str); } char path[PATH_MAX]; char *executable = get_executable(pid); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); char *proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(proc_pid_status); if (tmp_fsuid < 0) perror_msg_and_die("Can't parse 'Uid: line' in /proc/%lu/status", (long)pid); const int fsgid = get_fsgid(proc_pid_status); if (fsgid < 0) error_msg_and_die("Can't parse 'Gid: line' in /proc/%lu/status", (long)pid); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) fsuid = tmp_fsuid; else { g_user_core_flags = O_EXCL; g_need_nonrelative = 1; } } /* Open a fd to compat coredump, if requested and is possible */ int user_core_fd = -1; if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, fsgid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); return create_user_core(user_core_fd, pid, ulimit_c); } const char *signame = NULL; if (!signal_is_fatal(signal_no, &signame)) return create_user_core(user_core_fd, pid, ulimit_c); // not a signal we care about const int abrtd_running = daemon_is_ok(); if (!setting_StandaloneHook && !abrtd_running) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); return create_user_core(user_core_fd, pid, ulimit_c); } if (setting_StandaloneHook) ensure_writable_dir(g_settings_dump_location, DEFAULT_DUMP_LOCATION_MODE, "abrt"); if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) return create_user_core(user_core_fd, pid, ulimit_c); } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ return create_user_core(user_core_fd, pid, ulimit_c); } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { if (g_settings_debug_level == 0) { log_warning("Ignoring crash of %s (SIG%s).", executable, signame ? signame : signal_str); goto cleanup_and_exit; } /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ if (snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash) >= sizeof(path)) error_msg_and_die("Error saving '%s': truncated long file path", path); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log_notice("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); err = 0; goto cleanup_and_exit; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { return create_user_core(user_core_fd, pid, ulimit_c); } /* If you don't want to have fs owner as root then: * * - use fsuid instead of uid for fs owner, so we don't expose any * sensitive information of suided app in /var/(tmp|spool)/abrt * * - use dd_create_skeleton() and dd_reset_ownership(), when you finish * creating the new dump directory, to prevent the real owner to write to * the directory until the hook is done (avoid race conditions and defend * hard and symbolic link attacs) */ dd = dd_create(path, /*fs owner*/0, DEFAULT_DUMP_DIR_MODE); if (dd) { char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/root", (long)pid); source_base_ofs -= strlen("root"); /* What's wrong on using /proc/[pid]/root every time ?*/ /* It creates os_info_in_root_dir for all crashes. */ char *rootdir = process_has_own_root(pid) ? get_rootdir(pid) : NULL; /* Reading data from an arbitrary root directory is not secure. */ if (g_settings_explorechroots) { /* Yes, test 'rootdir' but use 'source_filename' because 'rootdir' can * be '/' for a process with own namespace. 'source_filename' is /proc/[pid]/root. */ dd_create_basic_files(dd, fsuid, (rootdir != NULL) ? source_filename : NULL); } else { dd_create_basic_files(dd, fsuid, NULL); } char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: // dd_copy_file(dd, FILENAME_SMAPS, source_filename); strcpy(source_filename + source_base_ofs, "maps"); dd_copy_file(dd, FILENAME_MAPS, source_filename); strcpy(source_filename + source_base_ofs, "limits"); dd_copy_file(dd, FILENAME_LIMITS, source_filename); strcpy(source_filename + source_base_ofs, "cgroup"); dd_copy_file(dd, FILENAME_CGROUP, source_filename); strcpy(source_filename + source_base_ofs, "mountinfo"); dd_copy_file(dd, FILENAME_MOUNTINFO, source_filename); strcpy(dest_base, FILENAME_OPEN_FDS); strcpy(source_filename + source_base_ofs, "fd"); dump_fd_info_ext(dest_filename, source_filename, dd->dd_uid, dd->dd_gid); strcpy(dest_base, FILENAME_NAMESPACES); dump_namespace_diff_ext(dest_filename, 1, pid, dd->dd_uid, dd->dd_gid); free(dest_filename); char *tmp = NULL; get_env_variable(pid, "container", &tmp); if (tmp != NULL) { dd_save_text(dd, FILENAME_CONTAINER, tmp); free(tmp); tmp = NULL; } get_env_variable(pid, "container_uuid", &tmp); if (tmp != NULL) { dd_save_text(dd, FILENAME_CONTAINER_UUID, tmp); free(tmp); } /* There's no need to compare mount namespaces and search for '/' in * mountifo. Comparison of inodes of '/proc/[pid]/root' and '/' works * fine. If those inodes do not equal each other, we have to verify * that '/proc/[pid]/root' is not a symlink to a chroot. */ const int containerized = (rootdir != NULL && strcmp(rootdir, "/") == 0); if (containerized) { log_debug("Process %d is considered to be containerized", pid); pid_t container_pid; if (get_pid_of_container(pid, &container_pid) == 0) { char *container_cmdline = get_cmdline(container_pid); dd_save_text(dd, FILENAME_CONTAINER_CMDLINE, container_cmdline); free(container_cmdline); } } dd_save_text(dd, FILENAME_ANALYZER, "abrt-ccpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_GLOBAL_PID, global_pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (tid_str) dd_save_text(dd, FILENAME_TID, tid_str); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } free(rootdir); char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); /* In case of errors, treat the process as if it has locked memory */ long unsigned lck_bytes = ULONG_MAX; const char *vmlck = strstr(proc_pid_status, "VmLck:"); if (vmlck == NULL) error_msg("/proc/%s/status does not contain 'VmLck:' line", pid_str); else if (1 != sscanf(vmlck + 6, "%lu kB\n", &lck_bytes)) error_msg("Failed to parse 'VmLck:' line in /proc/%s/status", pid_str); if (lck_bytes) { log_notice("Process %s of user %lu has locked memory", pid_str, (long unsigned)uid); dd_mark_as_notreportable(dd, "The process had locked memory " "which usually indicates efforts to protect sensitive " "data (passwords) from being written to disk.\n" "In order to avoid sensitive information leakages, " "ABRT will not allow you to report this problem to " "bug tracking tools"); } if (setting_SaveBinaryImage) { if (save_crashing_binary(pid, dd)) { error_msg("Error saving '%s'", path); goto cleanup_and_exit; } } off_t core_size = 0; if (setting_SaveFullCore) { strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path, user_core_fd); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); close_user_core(user_core_fd, core_size); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg("Error writing '%s'", path); goto cleanup_and_exit; } } else { /* User core is created even if WriteFullCore is off. */ create_user_core(user_core_fd, pid, ulimit_c); } /* User core is either written or closed */ user_core_fd = -1; /* * ! No other errors should cause removal of the user core ! */ /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path, user_core_fd); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { error_msg("Error saving '%s'", path); goto cleanup_and_exit; } close(src_fd); } } #endif /* Perform crash-time unwind of the guilty thread. */ if (tid > 0 && setting_CreateCoreBacktrace) create_core_backtrace(tid, executable, signal_no, dd); /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); dd = NULL; path[path_len] = '\0'; /* path now contains only directory name */ if (abrtd_running && setting_SaveContainerizedPackageData && containerized) { /* Do we really need to run rpm from core_pattern hook? */ sprintf(source_filename, "/proc/%lu/root", (long)pid); const char *cmd_args[6]; cmd_args[0] = BIN_DIR"/abrt-action-save-package-data"; cmd_args[1] = "-d"; cmd_args[2] = path; cmd_args[3] = "-r"; cmd_args[4] = source_filename; cmd_args[5] = NULL; pid_t pid = fork_execv_on_steroids(0, (char **)cmd_args, NULL, NULL, path, 0); int stat; safe_waitpid(pid, &stat, 0); } char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); if (core_size > 0) log_notice("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); if (abrtd_running) notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } err = 0; } else { /* We didn't create abrt dump, but may need to create compat coredump */ return create_user_core(user_core_fd, pid, ulimit_c); } cleanup_and_exit: if (dd) dd_delete(dd); if (user_core_fd >= 0) unlinkat(dirfd(proc_cwd), core_basename, /*only files*/0); if (proc_cwd != NULL) closedir(proc_cwd); return err; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1673_0
crossvul-cpp_data_good_1471_3
/* * lxc: linux Container library * * (C) Copyright IBM Corp. 2007, 2008 * * Authors: * Daniel Lezcano <daniel.lezcano at free.fr> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <errno.h> #include <string.h> #include <dirent.h> #include <unistd.h> #include <inttypes.h> #include <sys/wait.h> #include <sys/syscall.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <time.h> #ifdef HAVE_STATVFS #include <sys/statvfs.h> #endif #if HAVE_PTY_H #include <pty.h> #else #include <../include/openpty.h> #endif #include <linux/loop.h> #include <sys/types.h> #include <sys/utsname.h> #include <sys/param.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/mount.h> #include <sys/mman.h> #include <sys/prctl.h> #include <arpa/inet.h> #include <fcntl.h> #include <netinet/in.h> #include <net/if.h> #include <libgen.h> #include "network.h" #include "error.h" #include "af_unix.h" #include "parse.h" #include "utils.h" #include "conf.h" #include "log.h" #include "caps.h" /* for lxc_caps_last_cap() */ #include "bdev.h" #include "cgroup.h" #include "lxclock.h" #include "namespace.h" #include "lsm/lsm.h" #if HAVE_SYS_CAPABILITY_H #include <sys/capability.h> #endif #if HAVE_SYS_PERSONALITY_H #include <sys/personality.h> #endif #if IS_BIONIC #include <../include/lxcmntent.h> #else #include <mntent.h> #endif #include "lxcseccomp.h" lxc_log_define(lxc_conf, lxc); #define LINELEN 4096 #if HAVE_SYS_CAPABILITY_H #ifndef CAP_SETFCAP #define CAP_SETFCAP 31 #endif #ifndef CAP_MAC_OVERRIDE #define CAP_MAC_OVERRIDE 32 #endif #ifndef CAP_MAC_ADMIN #define CAP_MAC_ADMIN 33 #endif #endif #ifndef PR_CAPBSET_DROP #define PR_CAPBSET_DROP 24 #endif #ifndef LO_FLAGS_AUTOCLEAR #define LO_FLAGS_AUTOCLEAR 4 #endif /* needed for cgroup automount checks, regardless of whether we * have included linux/capability.h or not */ #ifndef CAP_SYS_ADMIN #define CAP_SYS_ADMIN 21 #endif /* Define pivot_root() if missing from the C library */ #ifndef HAVE_PIVOT_ROOT static int pivot_root(const char * new_root, const char * put_old) { #ifdef __NR_pivot_root return syscall(__NR_pivot_root, new_root, put_old); #else errno = ENOSYS; return -1; #endif } #else extern int pivot_root(const char * new_root, const char * put_old); #endif /* Define sethostname() if missing from the C library */ #ifndef HAVE_SETHOSTNAME static int sethostname(const char * name, size_t len) { #ifdef __NR_sethostname return syscall(__NR_sethostname, name, len); #else errno = ENOSYS; return -1; #endif } #endif /* Define __S_ISTYPE if missing from the C library */ #ifndef __S_ISTYPE #define __S_ISTYPE(mode, mask) (((mode) & S_IFMT) == (mask)) #endif #ifndef MS_PRIVATE #define MS_PRIVATE (1<<18) #endif char *lxchook_names[NUM_LXC_HOOKS] = { "pre-start", "pre-mount", "mount", "autodev", "start", "post-stop", "clone", "destroy" }; typedef int (*instantiate_cb)(struct lxc_handler *, struct lxc_netdev *); struct mount_opt { char *name; int clear; int flag; }; struct caps_opt { char *name; int value; }; /* * The lxc_conf of the container currently being worked on in an * API call * This is used in the error calls */ #ifdef HAVE_TLS __thread struct lxc_conf *current_config; #else struct lxc_conf *current_config; #endif /* Declare this here, since we don't want to reshuffle the whole file. */ static int in_caplist(int cap, struct lxc_list *caps); static int instantiate_veth(struct lxc_handler *, struct lxc_netdev *); static int instantiate_macvlan(struct lxc_handler *, struct lxc_netdev *); static int instantiate_vlan(struct lxc_handler *, struct lxc_netdev *); static int instantiate_phys(struct lxc_handler *, struct lxc_netdev *); static int instantiate_empty(struct lxc_handler *, struct lxc_netdev *); static int instantiate_none(struct lxc_handler *, struct lxc_netdev *); static instantiate_cb netdev_conf[LXC_NET_MAXCONFTYPE + 1] = { [LXC_NET_VETH] = instantiate_veth, [LXC_NET_MACVLAN] = instantiate_macvlan, [LXC_NET_VLAN] = instantiate_vlan, [LXC_NET_PHYS] = instantiate_phys, [LXC_NET_EMPTY] = instantiate_empty, [LXC_NET_NONE] = instantiate_none, }; static int shutdown_veth(struct lxc_handler *, struct lxc_netdev *); static int shutdown_macvlan(struct lxc_handler *, struct lxc_netdev *); static int shutdown_vlan(struct lxc_handler *, struct lxc_netdev *); static int shutdown_phys(struct lxc_handler *, struct lxc_netdev *); static int shutdown_empty(struct lxc_handler *, struct lxc_netdev *); static int shutdown_none(struct lxc_handler *, struct lxc_netdev *); static instantiate_cb netdev_deconf[LXC_NET_MAXCONFTYPE + 1] = { [LXC_NET_VETH] = shutdown_veth, [LXC_NET_MACVLAN] = shutdown_macvlan, [LXC_NET_VLAN] = shutdown_vlan, [LXC_NET_PHYS] = shutdown_phys, [LXC_NET_EMPTY] = shutdown_empty, [LXC_NET_NONE] = shutdown_none, }; static struct mount_opt mount_opt[] = { { "defaults", 0, 0 }, { "ro", 0, MS_RDONLY }, { "rw", 1, MS_RDONLY }, { "suid", 1, MS_NOSUID }, { "nosuid", 0, MS_NOSUID }, { "dev", 1, MS_NODEV }, { "nodev", 0, MS_NODEV }, { "exec", 1, MS_NOEXEC }, { "noexec", 0, MS_NOEXEC }, { "sync", 0, MS_SYNCHRONOUS }, { "async", 1, MS_SYNCHRONOUS }, { "dirsync", 0, MS_DIRSYNC }, { "remount", 0, MS_REMOUNT }, { "mand", 0, MS_MANDLOCK }, { "nomand", 1, MS_MANDLOCK }, { "atime", 1, MS_NOATIME }, { "noatime", 0, MS_NOATIME }, { "diratime", 1, MS_NODIRATIME }, { "nodiratime", 0, MS_NODIRATIME }, { "bind", 0, MS_BIND }, { "rbind", 0, MS_BIND|MS_REC }, { "relatime", 0, MS_RELATIME }, { "norelatime", 1, MS_RELATIME }, { "strictatime", 0, MS_STRICTATIME }, { "nostrictatime", 1, MS_STRICTATIME }, { NULL, 0, 0 }, }; #if HAVE_SYS_CAPABILITY_H static struct caps_opt caps_opt[] = { { "chown", CAP_CHOWN }, { "dac_override", CAP_DAC_OVERRIDE }, { "dac_read_search", CAP_DAC_READ_SEARCH }, { "fowner", CAP_FOWNER }, { "fsetid", CAP_FSETID }, { "kill", CAP_KILL }, { "setgid", CAP_SETGID }, { "setuid", CAP_SETUID }, { "setpcap", CAP_SETPCAP }, { "linux_immutable", CAP_LINUX_IMMUTABLE }, { "net_bind_service", CAP_NET_BIND_SERVICE }, { "net_broadcast", CAP_NET_BROADCAST }, { "net_admin", CAP_NET_ADMIN }, { "net_raw", CAP_NET_RAW }, { "ipc_lock", CAP_IPC_LOCK }, { "ipc_owner", CAP_IPC_OWNER }, { "sys_module", CAP_SYS_MODULE }, { "sys_rawio", CAP_SYS_RAWIO }, { "sys_chroot", CAP_SYS_CHROOT }, { "sys_ptrace", CAP_SYS_PTRACE }, { "sys_pacct", CAP_SYS_PACCT }, { "sys_admin", CAP_SYS_ADMIN }, { "sys_boot", CAP_SYS_BOOT }, { "sys_nice", CAP_SYS_NICE }, { "sys_resource", CAP_SYS_RESOURCE }, { "sys_time", CAP_SYS_TIME }, { "sys_tty_config", CAP_SYS_TTY_CONFIG }, { "mknod", CAP_MKNOD }, { "lease", CAP_LEASE }, #ifdef CAP_AUDIT_READ { "audit_read", CAP_AUDIT_READ }, #endif #ifdef CAP_AUDIT_WRITE { "audit_write", CAP_AUDIT_WRITE }, #endif #ifdef CAP_AUDIT_CONTROL { "audit_control", CAP_AUDIT_CONTROL }, #endif { "setfcap", CAP_SETFCAP }, { "mac_override", CAP_MAC_OVERRIDE }, { "mac_admin", CAP_MAC_ADMIN }, #ifdef CAP_SYSLOG { "syslog", CAP_SYSLOG }, #endif #ifdef CAP_WAKE_ALARM { "wake_alarm", CAP_WAKE_ALARM }, #endif #ifdef CAP_BLOCK_SUSPEND { "block_suspend", CAP_BLOCK_SUSPEND }, #endif }; #else static struct caps_opt caps_opt[] = {}; #endif static int run_buffer(char *buffer) { struct lxc_popen_FILE *f; char *output; int ret; f = lxc_popen(buffer); if (!f) { SYSERROR("popen failed"); return -1; } output = malloc(LXC_LOG_BUFFER_SIZE); if (!output) { ERROR("failed to allocate memory for script output"); lxc_pclose(f); return -1; } while(fgets(output, LXC_LOG_BUFFER_SIZE, f->f)) DEBUG("script output: %s", output); free(output); ret = lxc_pclose(f); if (ret == -1) { SYSERROR("Script exited on error"); return -1; } else if (WIFEXITED(ret) && WEXITSTATUS(ret) != 0) { ERROR("Script exited with status %d", WEXITSTATUS(ret)); return -1; } else if (WIFSIGNALED(ret)) { ERROR("Script terminated by signal %d (%s)", WTERMSIG(ret), strsignal(WTERMSIG(ret))); return -1; } return 0; } static int run_script_argv(const char *name, const char *section, const char *script, const char *hook, const char *lxcpath, char **argsin) { int ret, i; char *buffer; size_t size = 0; INFO("Executing script '%s' for container '%s', config section '%s'", script, name, section); for (i=0; argsin && argsin[i]; i++) size += strlen(argsin[i]) + 1; size += strlen(hook) + 1; size += strlen(script); size += strlen(name); size += strlen(section); size += 3; if (size > INT_MAX) return -1; buffer = alloca(size); if (!buffer) { ERROR("failed to allocate memory"); return -1; } ret = snprintf(buffer, size, "%s %s %s %s", script, name, section, hook); if (ret < 0 || ret >= size) { ERROR("Script name too long"); return -1; } for (i=0; argsin && argsin[i]; i++) { int len = size-ret; int rc; rc = snprintf(buffer + ret, len, " %s", argsin[i]); if (rc < 0 || rc >= len) { ERROR("Script args too long"); return -1; } ret += rc; } return run_buffer(buffer); } static int run_script(const char *name, const char *section, const char *script, ...) { int ret; char *buffer, *p; size_t size = 0; va_list ap; INFO("Executing script '%s' for container '%s', config section '%s'", script, name, section); va_start(ap, script); while ((p = va_arg(ap, char *))) size += strlen(p) + 1; va_end(ap); size += strlen(script); size += strlen(name); size += strlen(section); size += 3; if (size > INT_MAX) return -1; buffer = alloca(size); if (!buffer) { ERROR("failed to allocate memory"); return -1; } ret = snprintf(buffer, size, "%s %s %s", script, name, section); if (ret < 0 || ret >= size) { ERROR("Script name too long"); return -1; } va_start(ap, script); while ((p = va_arg(ap, char *))) { int len = size-ret; int rc; rc = snprintf(buffer + ret, len, " %s", p); if (rc < 0 || rc >= len) { ERROR("Script args too long"); return -1; } ret += rc; } va_end(ap); return run_buffer(buffer); } static int find_fstype_cb(char* buffer, void *data) { struct cbarg { const char *rootfs; const char *target; const char *options; } *cbarg = data; unsigned long mntflags; char *mntdata; char *fstype; /* we don't try 'nodev' entries */ if (strstr(buffer, "nodev")) return 0; fstype = buffer; fstype += lxc_char_left_gc(fstype, strlen(fstype)); fstype[lxc_char_right_gc(fstype, strlen(fstype))] = '\0'; /* ignore blank line and comment */ if (fstype[0] == '\0' || fstype[0] == '#') return 0; DEBUG("trying to mount '%s'->'%s' with fstype '%s'", cbarg->rootfs, cbarg->target, fstype); if (parse_mntopts(cbarg->options, &mntflags, &mntdata) < 0) { free(mntdata); return -1; } if (mount(cbarg->rootfs, cbarg->target, fstype, mntflags, mntdata)) { DEBUG("mount failed with error: %s", strerror(errno)); free(mntdata); return 0; } free(mntdata); INFO("mounted '%s' on '%s', with fstype '%s'", cbarg->rootfs, cbarg->target, fstype); return 1; } static int mount_unknown_fs(const char *rootfs, const char *target, const char *options) { int i; struct cbarg { const char *rootfs; const char *target; const char *options; } cbarg = { .rootfs = rootfs, .target = target, .options = options, }; /* * find the filesystem type with brute force: * first we check with /etc/filesystems, in case the modules * are auto-loaded and fall back to the supported kernel fs */ char *fsfile[] = { "/etc/filesystems", "/proc/filesystems", }; for (i = 0; i < sizeof(fsfile)/sizeof(fsfile[0]); i++) { int ret; if (access(fsfile[i], F_OK)) continue; ret = lxc_file_for_each_line(fsfile[i], find_fstype_cb, &cbarg); if (ret < 0) { ERROR("failed to parse '%s'", fsfile[i]); return -1; } if (ret) return 0; } ERROR("failed to determine fs type for '%s'", rootfs); return -1; } static int mount_rootfs_dir(const char *rootfs, const char *target, const char *options) { unsigned long mntflags; char *mntdata; int ret; if (parse_mntopts(options, &mntflags, &mntdata) < 0) { free(mntdata); return -1; } ret = mount(rootfs, target, "none", MS_BIND | MS_REC | mntflags, mntdata); free(mntdata); return ret; } static int setup_lodev(const char *rootfs, int fd, struct loop_info64 *loinfo) { int rfd; int ret = -1; rfd = open(rootfs, O_RDWR); if (rfd < 0) { SYSERROR("failed to open '%s'", rootfs); return -1; } memset(loinfo, 0, sizeof(*loinfo)); loinfo->lo_flags = LO_FLAGS_AUTOCLEAR; if (ioctl(fd, LOOP_SET_FD, rfd)) { SYSERROR("failed to LOOP_SET_FD"); goto out; } if (ioctl(fd, LOOP_SET_STATUS64, loinfo)) { SYSERROR("failed to LOOP_SET_STATUS64"); goto out; } ret = 0; out: close(rfd); return ret; } static int mount_rootfs_file(const char *rootfs, const char *target, const char *options) { struct dirent dirent, *direntp; struct loop_info64 loinfo; int ret = -1, fd = -1, rc; DIR *dir; char path[MAXPATHLEN]; dir = opendir("/dev"); if (!dir) { SYSERROR("failed to open '/dev'"); return -1; } while (!readdir_r(dir, &dirent, &direntp)) { if (!direntp) break; if (!strcmp(direntp->d_name, ".")) continue; if (!strcmp(direntp->d_name, "..")) continue; if (strncmp(direntp->d_name, "loop", 4)) continue; rc = snprintf(path, MAXPATHLEN, "/dev/%s", direntp->d_name); if (rc < 0 || rc >= MAXPATHLEN) continue; fd = open(path, O_RDWR); if (fd < 0) continue; if (ioctl(fd, LOOP_GET_STATUS64, &loinfo) == 0) { close(fd); continue; } if (errno != ENXIO) { WARN("unexpected error for ioctl on '%s': %m", direntp->d_name); close(fd); continue; } DEBUG("found '%s' free lodev", path); ret = setup_lodev(rootfs, fd, &loinfo); if (!ret) ret = mount_unknown_fs(path, target, options); close(fd); break; } if (closedir(dir)) WARN("failed to close directory"); return ret; } static int mount_rootfs_block(const char *rootfs, const char *target, const char *options) { return mount_unknown_fs(rootfs, target, options); } /* * pin_rootfs * if rootfs is a directory, then open ${rootfs}/lxc.hold for writing for * the duration of the container run, to prevent the container from marking * the underlying fs readonly on shutdown. unlink the file immediately so * no name pollution is happens * return -1 on error. * return -2 if nothing needed to be pinned. * return an open fd (>=0) if we pinned it. */ int pin_rootfs(const char *rootfs) { char absrootfs[MAXPATHLEN]; char absrootfspin[MAXPATHLEN]; struct stat s; int ret, fd; if (rootfs == NULL || strlen(rootfs) == 0) return -2; if (!realpath(rootfs, absrootfs)) return -2; if (access(absrootfs, F_OK)) return -1; if (stat(absrootfs, &s)) return -1; if (!S_ISDIR(s.st_mode)) return -2; ret = snprintf(absrootfspin, MAXPATHLEN, "%s/lxc.hold", absrootfs); if (ret >= MAXPATHLEN) return -1; fd = open(absrootfspin, O_CREAT | O_RDWR, S_IWUSR|S_IRUSR); if (fd < 0) return fd; (void)unlink(absrootfspin); return fd; } /* * If we are asking to remount something, make sure that any * NOEXEC etc are honored. */ static unsigned long add_required_remount_flags(const char *s, const char *d, unsigned long flags) { #ifdef HAVE_STATVFS struct statvfs sb; unsigned long required_flags = 0; if (!(flags & MS_REMOUNT)) return flags; if (!s) s = d; if (!s) return flags; if (statvfs(s, &sb) < 0) return flags; if (sb.f_flag & MS_NOSUID) required_flags |= MS_NOSUID; if (sb.f_flag & MS_NODEV) required_flags |= MS_NODEV; if (sb.f_flag & MS_RDONLY) required_flags |= MS_RDONLY; if (sb.f_flag & MS_NOEXEC) required_flags |= MS_NOEXEC; return flags | required_flags; #else return flags; #endif } static int lxc_mount_auto_mounts(struct lxc_conf *conf, int flags, struct lxc_handler *handler) { int r; size_t i; static struct { int match_mask; int match_flag; const char *source; const char *destination; const char *fstype; unsigned long flags; const char *options; } default_mounts[] = { /* Read-only bind-mounting... In older kernels, doing that required * to do one MS_BIND mount and then MS_REMOUNT|MS_RDONLY the same * one. According to mount(2) manpage, MS_BIND honors MS_RDONLY from * kernel 2.6.26 onwards. However, this apparently does not work on * kernel 3.8. Unfortunately, on that very same kernel, doing the * same trick as above doesn't seem to work either, there one needs * to ALSO specify MS_BIND for the remount, otherwise the entire * fs is remounted read-only or the mount fails because it's busy... * MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for kernels as low as * 2.6.32... */ { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL }, /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */ { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys/net", "%r/proc/tty", NULL, MS_BIND, NULL }, { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sys", "%r/proc/sys", NULL, MS_BIND, NULL }, { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sys", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL }, { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/tty", "%r/proc/sys/net", NULL, MS_MOVE, NULL }, { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL, MS_BIND, NULL }, { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, "%r/proc/sysrq-trigger", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL }, { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_RW, "proc", "%r/proc", "proc", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL }, { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RW, "sysfs", "%r/sys", "sysfs", 0, NULL }, { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_RO, "sysfs", "%r/sys", "sysfs", MS_RDONLY, NULL }, { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "sysfs", "%r/sys", "sysfs", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL }, { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "%r/sys", "%r/sys", NULL, MS_BIND, NULL }, { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, NULL, "%r/sys", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL }, { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL }, { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, "%r/sys/devices/virtual/net/devices/virtual/net", "%r/sys/devices/virtual/net", NULL, MS_BIND, NULL }, { LXC_AUTO_SYS_MASK, LXC_AUTO_SYS_MIXED, NULL, "%r/sys/devices/virtual/net", NULL, MS_REMOUNT|MS_BIND|MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL }, { 0, 0, NULL, NULL, NULL, 0, NULL } }; for (i = 0; default_mounts[i].match_mask; i++) { if ((flags & default_mounts[i].match_mask) == default_mounts[i].match_flag) { char *source = NULL; char *destination = NULL; int saved_errno; unsigned long mflags; if (default_mounts[i].source) { /* will act like strdup if %r is not present */ source = lxc_string_replace("%r", conf->rootfs.path ? conf->rootfs.mount : "", default_mounts[i].source); if (!source) { SYSERROR("memory allocation error"); return -1; } } if (default_mounts[i].destination) { /* will act like strdup if %r is not present */ destination = lxc_string_replace("%r", conf->rootfs.path ? conf->rootfs.mount : "", default_mounts[i].destination); if (!destination) { saved_errno = errno; SYSERROR("memory allocation error"); free(source); errno = saved_errno; return -1; } } mflags = add_required_remount_flags(source, destination, default_mounts[i].flags); r = safe_mount(source, destination, default_mounts[i].fstype, mflags, default_mounts[i].options, conf->rootfs.path ? conf->rootfs.mount : NULL); saved_errno = errno; if (r < 0 && errno == ENOENT) { INFO("Mount source or target for %s on %s doesn't exist. Skipping.", source, destination); r = 0; } else if (r < 0) SYSERROR("error mounting %s on %s flags %lu", source, destination, mflags); free(source); free(destination); if (r < 0) { errno = saved_errno; return -1; } } } if (flags & LXC_AUTO_CGROUP_MASK) { int cg_flags; cg_flags = flags & LXC_AUTO_CGROUP_MASK; /* If the type of cgroup mount was not specified, it depends on the * container's capabilities as to what makes sense: if we have * CAP_SYS_ADMIN, the read-only part can be remounted read-write * anyway, so we may as well default to read-write; then the admin * will not be given a false sense of security. (And if they really * want mixed r/o r/w, then they can explicitly specify :mixed.) * OTOH, if the container lacks CAP_SYS_ADMIN, do only default to * :mixed, because then the container can't remount it read-write. */ if (cg_flags == LXC_AUTO_CGROUP_NOSPEC || cg_flags == LXC_AUTO_CGROUP_FULL_NOSPEC) { int has_sys_admin = 0; if (!lxc_list_empty(&conf->keepcaps)) { has_sys_admin = in_caplist(CAP_SYS_ADMIN, &conf->keepcaps); } else { has_sys_admin = !in_caplist(CAP_SYS_ADMIN, &conf->caps); } if (cg_flags == LXC_AUTO_CGROUP_NOSPEC) { cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_RW : LXC_AUTO_CGROUP_MIXED; } else { cg_flags = has_sys_admin ? LXC_AUTO_CGROUP_FULL_RW : LXC_AUTO_CGROUP_FULL_MIXED; } } if (!cgroup_mount(conf->rootfs.path ? conf->rootfs.mount : "", handler, cg_flags)) { SYSERROR("error mounting /sys/fs/cgroup"); return -1; } } return 0; } static int mount_rootfs(const char *rootfs, const char *target, const char *options) { char absrootfs[MAXPATHLEN]; struct stat s; int i; typedef int (*rootfs_cb)(const char *, const char *, const char *); struct rootfs_type { int type; rootfs_cb cb; } rtfs_type[] = { { S_IFDIR, mount_rootfs_dir }, { S_IFBLK, mount_rootfs_block }, { S_IFREG, mount_rootfs_file }, }; if (!realpath(rootfs, absrootfs)) { SYSERROR("failed to get real path for '%s'", rootfs); return -1; } if (access(absrootfs, F_OK)) { SYSERROR("'%s' is not accessible", absrootfs); return -1; } if (stat(absrootfs, &s)) { SYSERROR("failed to stat '%s'", absrootfs); return -1; } for (i = 0; i < sizeof(rtfs_type)/sizeof(rtfs_type[0]); i++) { if (!__S_ISTYPE(s.st_mode, rtfs_type[i].type)) continue; return rtfs_type[i].cb(absrootfs, target, options); } ERROR("unsupported rootfs type for '%s'", absrootfs); return -1; } static int setup_utsname(struct utsname *utsname) { if (!utsname) return 0; if (sethostname(utsname->nodename, strlen(utsname->nodename))) { SYSERROR("failed to set the hostname to '%s'", utsname->nodename); return -1; } INFO("'%s' hostname has been setup", utsname->nodename); return 0; } struct dev_symlinks { const char *oldpath; const char *name; }; static const struct dev_symlinks dev_symlinks[] = { {"/proc/self/fd", "fd"}, {"/proc/self/fd/0", "stdin"}, {"/proc/self/fd/1", "stdout"}, {"/proc/self/fd/2", "stderr"}, }; static int setup_dev_symlinks(const struct lxc_rootfs *rootfs) { char path[MAXPATHLEN]; int ret,i; struct stat s; for (i = 0; i < sizeof(dev_symlinks) / sizeof(dev_symlinks[0]); i++) { const struct dev_symlinks *d = &dev_symlinks[i]; ret = snprintf(path, sizeof(path), "%s/dev/%s", rootfs->path ? rootfs->mount : "", d->name); if (ret < 0 || ret >= MAXPATHLEN) return -1; /* * Stat the path first. If we don't get an error * accept it as is and don't try to create it */ if (!stat(path, &s)) { continue; } ret = symlink(d->oldpath, path); if (ret && errno != EEXIST) { if ( errno == EROFS ) { WARN("Warning: Read Only file system while creating %s", path); } else { SYSERROR("Error creating %s", path); return -1; } } } return 0; } /* * Build a space-separate list of ptys to pass to systemd. */ static bool append_ptyname(char **pp, char *name) { char *p; if (!*pp) { *pp = malloc(strlen(name) + strlen("container_ttys=") + 1); if (!*pp) return false; sprintf(*pp, "container_ttys=%s", name); return true; } p = realloc(*pp, strlen(*pp) + strlen(name) + 2); if (!p) return false; *pp = p; strcat(p, " "); strcat(p, name); return true; } static int setup_tty(struct lxc_conf *conf) { const struct lxc_tty_info *tty_info = &conf->tty_info; char *ttydir = conf->ttydir; char path[MAXPATHLEN], lxcpath[MAXPATHLEN]; int i, ret; if (!conf->rootfs.path) return 0; for (i = 0; i < tty_info->nbtty; i++) { struct lxc_pty_info *pty_info = &tty_info->pty_info[i]; ret = snprintf(path, sizeof(path), "/dev/tty%d", i + 1); if (ret >= sizeof(path)) { ERROR("pathname too long for ttys"); return -1; } if (ttydir) { /* create dev/lxc/tty%d" */ ret = snprintf(lxcpath, sizeof(lxcpath), "/dev/%s/tty%d", ttydir, i + 1); if (ret >= sizeof(lxcpath)) { ERROR("pathname too long for ttys"); return -1; } ret = creat(lxcpath, 0660); if (ret==-1 && errno != EEXIST) { SYSERROR("error creating %s", lxcpath); return -1; } if (ret >= 0) close(ret); ret = unlink(path); if (ret && errno != ENOENT) { SYSERROR("error unlinking %s", path); return -1; } if (mount(pty_info->name, lxcpath, "none", MS_BIND, 0)) { WARN("failed to mount '%s'->'%s'", pty_info->name, path); continue; } ret = snprintf(lxcpath, sizeof(lxcpath), "%s/tty%d", ttydir, i+1); if (ret >= sizeof(lxcpath)) { ERROR("tty pathname too long"); return -1; } ret = symlink(lxcpath, path); if (ret) { SYSERROR("failed to create symlink for tty %d", i+1); return -1; } } else { /* If we populated /dev, then we need to create /dev/ttyN */ if (access(path, F_OK)) { ret = creat(path, 0660); if (ret==-1) { SYSERROR("error creating %s", path); /* this isn't fatal, continue */ } else { close(ret); } } if (mount(pty_info->name, path, "none", MS_BIND, 0)) { SYSERROR("failed to mount '%s'->'%s'", pty_info->name, path); continue; } } if (!append_ptyname(&conf->pty_names, pty_info->name)) { ERROR("Error setting up container_ttys string"); return -1; } } INFO("%d tty(s) has been setup", tty_info->nbtty); return 0; } static int setup_rootfs_pivot_root(const char *rootfs, const char *pivotdir) { int oldroot = -1, newroot = -1; oldroot = open("/", O_DIRECTORY | O_RDONLY); if (oldroot < 0) { SYSERROR("Error opening old-/ for fchdir"); return -1; } newroot = open(rootfs, O_DIRECTORY | O_RDONLY); if (newroot < 0) { SYSERROR("Error opening new-/ for fchdir"); goto fail; } /* change into new root fs */ if (fchdir(newroot)) { SYSERROR("can't chdir to new rootfs '%s'", rootfs); goto fail; } /* pivot_root into our new root fs */ if (pivot_root(".", ".")) { SYSERROR("pivot_root syscall failed"); goto fail; } /* * at this point the old-root is mounted on top of our new-root * To unmounted it we must not be chdir'd into it, so escape back * to old-root */ if (fchdir(oldroot) < 0) { SYSERROR("Error entering oldroot"); goto fail; } if (umount2(".", MNT_DETACH) < 0) { SYSERROR("Error detaching old root"); goto fail; } if (fchdir(newroot) < 0) { SYSERROR("Error re-entering newroot"); goto fail; } close(oldroot); close(newroot); DEBUG("pivot_root syscall to '%s' successful", rootfs); return 0; fail: if (oldroot != -1) close(oldroot); if (newroot != -1) close(newroot); return -1; } /* * Just create a path for /dev under $lxcpath/$name and in rootfs * If we hit an error, log it but don't fail yet. */ static int mount_autodev(const char *name, const struct lxc_rootfs *rootfs, const char *lxcpath) { int ret; size_t clen; char *path; INFO("Mounting container /dev"); /* $(rootfs->mount) + "/dev/pts" + '\0' */ clen = (rootfs->path ? strlen(rootfs->mount) : 0) + 9; path = alloca(clen); ret = snprintf(path, clen, "%s/dev", rootfs->path ? rootfs->mount : ""); if (ret < 0 || ret >= clen) return -1; if (!dir_exists(path)) { WARN("No /dev in container."); WARN("Proceeding without autodev setup"); return 0; } if (safe_mount("none", path, "tmpfs", 0, "size=100000,mode=755", rootfs->path ? rootfs->mount : NULL)) { SYSERROR("Failed mounting tmpfs onto %s\n", path); return false; } INFO("Mounted tmpfs onto %s", path); ret = snprintf(path, clen, "%s/dev/pts", rootfs->path ? rootfs->mount : ""); if (ret < 0 || ret >= clen) return -1; /* * If we are running on a devtmpfs mapping, dev/pts may already exist. * If not, then create it and exit if that fails... */ if (!dir_exists(path)) { ret = mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); if (ret) { SYSERROR("Failed to create /dev/pts in container"); return -1; } } INFO("Mounted container /dev"); return 0; } struct lxc_devs { const char *name; mode_t mode; int maj; int min; }; static const struct lxc_devs lxc_devs[] = { { "null", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 3 }, { "zero", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 5 }, { "full", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 7 }, { "urandom", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 9 }, { "random", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 1, 8 }, { "tty", S_IFCHR | S_IRWXU | S_IRWXG | S_IRWXO, 5, 0 }, { "console", S_IFCHR | S_IRUSR | S_IWUSR, 5, 1 }, }; static int fill_autodev(const struct lxc_rootfs *rootfs) { int ret; char path[MAXPATHLEN]; int i; mode_t cmask; INFO("Creating initial consoles under container /dev"); ret = snprintf(path, MAXPATHLEN, "%s/dev", rootfs->path ? rootfs->mount : ""); if (ret < 0 || ret >= MAXPATHLEN) { ERROR("Error calculating container /dev location"); return -1; } if (!dir_exists(path)) // ignore, just don't try to fill in return 0; INFO("Populating container /dev"); cmask = umask(S_IXUSR | S_IXGRP | S_IXOTH); for (i = 0; i < sizeof(lxc_devs) / sizeof(lxc_devs[0]); i++) { const struct lxc_devs *d = &lxc_devs[i]; ret = snprintf(path, MAXPATHLEN, "%s/dev/%s", rootfs->path ? rootfs->mount : "", d->name); if (ret < 0 || ret >= MAXPATHLEN) return -1; ret = mknod(path, d->mode, makedev(d->maj, d->min)); if (ret && errno != EEXIST) { char hostpath[MAXPATHLEN]; FILE *pathfile; // Unprivileged containers cannot create devices, so // bind mount the device from the host ret = snprintf(hostpath, MAXPATHLEN, "/dev/%s", d->name); if (ret < 0 || ret >= MAXPATHLEN) return -1; pathfile = fopen(path, "wb"); if (!pathfile) { SYSERROR("Failed to create device mount target '%s'", path); return -1; } fclose(pathfile); if (safe_mount(hostpath, path, 0, MS_BIND, NULL, rootfs->path ? rootfs->mount : NULL) != 0) { SYSERROR("Failed bind mounting device %s from host into container", d->name); return -1; } } } umask(cmask); INFO("Populated container /dev"); return 0; } static int setup_rootfs(struct lxc_conf *conf) { const struct lxc_rootfs *rootfs = &conf->rootfs; if (!rootfs->path) { if (mount("", "/", NULL, MS_SLAVE|MS_REC, 0)) { SYSERROR("Failed to make / rslave"); return -1; } return 0; } if (access(rootfs->mount, F_OK)) { SYSERROR("failed to access to '%s', check it is present", rootfs->mount); return -1; } // First try mounting rootfs using a bdev struct bdev *bdev = bdev_init(conf, rootfs->path, rootfs->mount, rootfs->options); if (bdev && bdev->ops->mount(bdev) == 0) { bdev_put(bdev); DEBUG("mounted '%s' on '%s'", rootfs->path, rootfs->mount); return 0; } if (bdev) bdev_put(bdev); if (mount_rootfs(rootfs->path, rootfs->mount, rootfs->options)) { ERROR("failed to mount rootfs"); return -1; } DEBUG("mounted '%s' on '%s'", rootfs->path, rootfs->mount); return 0; } int prepare_ramfs_root(char *root) { char buf[LINELEN], *p; char nroot[PATH_MAX]; FILE *f; int i; char *p2; if (realpath(root, nroot) == NULL) return -1; if (chdir("/") == -1) return -1; /* * We could use here MS_MOVE, but in userns this mount is * locked and can't be moved. */ if (mount(root, "/", NULL, MS_REC | MS_BIND, NULL)) { SYSERROR("Failed to move %s into /", root); return -1; } if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL)) { SYSERROR("Failed to make . rprivate"); return -1; } /* * The following code cleans up inhereted mounts which are not * required for CT. * * The mountinfo file shows not all mounts, if a few points have been * unmounted between read operations from the mountinfo. So we need to * read mountinfo a few times. * * This loop can be skipped if a container uses unserns, because all * inherited mounts are locked and we should live with all this trash. */ while (1) { int progress = 0; f = fopen("./proc/self/mountinfo", "r"); if (!f) { SYSERROR("Unable to open /proc/self/mountinfo"); return -1; } while (fgets(buf, LINELEN, f)) { for (p = buf, i=0; p && i < 4; i++) p = strchr(p+1, ' '); if (!p) continue; p2 = strchr(p+1, ' '); if (!p2) continue; *p2 = '\0'; *p = '.'; if (strcmp(p + 1, "/") == 0) continue; if (strcmp(p + 1, "/proc") == 0) continue; if (umount2(p, MNT_DETACH) == 0) progress++; } fclose(f); if (!progress) break; } /* This also can be skipped if a container uses unserns */ umount2("./proc", MNT_DETACH); /* It is weird, but chdir("..") moves us in a new root */ if (chdir("..") == -1) { SYSERROR("Unable to change working directory"); return -1; } if (chroot(".") == -1) { SYSERROR("Unable to chroot"); return -1; } return 0; } static int setup_pivot_root(const struct lxc_rootfs *rootfs) { if (!rootfs->path) return 0; if (detect_ramfs_rootfs()) { if (prepare_ramfs_root(rootfs->mount)) return -1; } else if (setup_rootfs_pivot_root(rootfs->mount, rootfs->pivot)) { ERROR("failed to setup pivot root"); return -1; } return 0; } static int setup_pts(int pts) { char target[PATH_MAX]; if (!pts) return 0; if (!access("/dev/pts/ptmx", F_OK) && umount("/dev/pts")) { SYSERROR("failed to umount 'dev/pts'"); return -1; } if (mkdir("/dev/pts", 0755)) { if ( errno != EEXIST ) { SYSERROR("failed to create '/dev/pts'"); return -1; } } if (mount("devpts", "/dev/pts", "devpts", MS_MGC_VAL, "newinstance,ptmxmode=0666,mode=0620,gid=5")) { SYSERROR("failed to mount a new instance of '/dev/pts'"); return -1; } if (access("/dev/ptmx", F_OK)) { if (!symlink("/dev/pts/ptmx", "/dev/ptmx")) goto out; SYSERROR("failed to symlink '/dev/pts/ptmx'->'/dev/ptmx'"); return -1; } if (realpath("/dev/ptmx", target) && !strcmp(target, "/dev/pts/ptmx")) goto out; /* fallback here, /dev/pts/ptmx exists just mount bind */ if (mount("/dev/pts/ptmx", "/dev/ptmx", "none", MS_BIND, 0)) { SYSERROR("mount failed '/dev/pts/ptmx'->'/dev/ptmx'"); return -1; } INFO("created new pts instance"); out: return 0; } static int setup_personality(int persona) { #if HAVE_SYS_PERSONALITY_H if (persona == -1) return 0; if (personality(persona) < 0) { SYSERROR("failed to set personality to '0x%x'", persona); return -1; } INFO("set personality to '0x%x'", persona); #endif return 0; } static int setup_dev_console(const struct lxc_rootfs *rootfs, const struct lxc_console *console) { char path[MAXPATHLEN]; struct stat s; int ret; ret = snprintf(path, sizeof(path), "%s/dev/console", rootfs->mount); if (ret >= sizeof(path)) { ERROR("console path too long"); return -1; } if (access(path, F_OK)) { WARN("rootfs specified but no console found at '%s'", path); return 0; } if (console->master < 0) { INFO("no console"); return 0; } if (stat(path, &s)) { SYSERROR("failed to stat '%s'", path); return -1; } if (chmod(console->name, s.st_mode)) { SYSERROR("failed to set mode '0%o' to '%s'", s.st_mode, console->name); return -1; } if (safe_mount(console->name, path, "none", MS_BIND, 0, rootfs->mount)) { ERROR("failed to mount '%s' on '%s'", console->name, path); return -1; } INFO("console has been setup"); return 0; } static int setup_ttydir_console(const struct lxc_rootfs *rootfs, const struct lxc_console *console, char *ttydir) { char path[MAXPATHLEN], lxcpath[MAXPATHLEN]; int ret; /* create rootfs/dev/<ttydir> directory */ ret = snprintf(path, sizeof(path), "%s/dev/%s", rootfs->mount, ttydir); if (ret >= sizeof(path)) return -1; ret = mkdir(path, 0755); if (ret && errno != EEXIST) { SYSERROR("failed with errno %d to create %s", errno, path); return -1; } INFO("created %s", path); ret = snprintf(lxcpath, sizeof(lxcpath), "%s/dev/%s/console", rootfs->mount, ttydir); if (ret >= sizeof(lxcpath)) { ERROR("console path too long"); return -1; } snprintf(path, sizeof(path), "%s/dev/console", rootfs->mount); ret = unlink(path); if (ret && errno != ENOENT) { SYSERROR("error unlinking %s", path); return -1; } ret = creat(lxcpath, 0660); if (ret==-1 && errno != EEXIST) { SYSERROR("error %d creating %s", errno, lxcpath); return -1; } if (ret >= 0) close(ret); if (console->master < 0) { INFO("no console"); return 0; } if (safe_mount(console->name, lxcpath, "none", MS_BIND, 0, rootfs->mount)) { ERROR("failed to mount '%s' on '%s'", console->name, lxcpath); return -1; } /* create symlink from rootfs/dev/console to 'lxc/console' */ ret = snprintf(lxcpath, sizeof(lxcpath), "%s/console", ttydir); if (ret >= sizeof(lxcpath)) { ERROR("lxc/console path too long"); return -1; } ret = symlink(lxcpath, path); if (ret) { SYSERROR("failed to create symlink for console"); return -1; } INFO("console has been setup on %s", lxcpath); return 0; } static int setup_console(const struct lxc_rootfs *rootfs, const struct lxc_console *console, char *ttydir) { /* We don't have a rootfs, /dev/console will be shared */ if (!rootfs->path) return 0; if (!ttydir) return setup_dev_console(rootfs, console); return setup_ttydir_console(rootfs, console, ttydir); } static int setup_kmsg(const struct lxc_rootfs *rootfs, const struct lxc_console *console) { char kpath[MAXPATHLEN]; int ret; if (!rootfs->path) return 0; ret = snprintf(kpath, sizeof(kpath), "%s/dev/kmsg", rootfs->mount); if (ret < 0 || ret >= sizeof(kpath)) return -1; ret = unlink(kpath); if (ret && errno != ENOENT) { SYSERROR("error unlinking %s", kpath); return -1; } ret = symlink("console", kpath); if (ret) { SYSERROR("failed to create symlink for kmsg"); return -1; } return 0; } static void parse_mntopt(char *opt, unsigned long *flags, char **data) { struct mount_opt *mo; /* If opt is found in mount_opt, set or clear flags. * Otherwise append it to data. */ for (mo = &mount_opt[0]; mo->name != NULL; mo++) { if (!strncmp(opt, mo->name, strlen(mo->name))) { if (mo->clear) *flags &= ~mo->flag; else *flags |= mo->flag; return; } } if (strlen(*data)) strcat(*data, ","); strcat(*data, opt); } int parse_mntopts(const char *mntopts, unsigned long *mntflags, char **mntdata) { char *s, *data; char *p, *saveptr = NULL; *mntdata = NULL; *mntflags = 0L; if (!mntopts) return 0; s = strdup(mntopts); if (!s) { SYSERROR("failed to allocate memory"); return -1; } data = malloc(strlen(s) + 1); if (!data) { SYSERROR("failed to allocate memory"); free(s); return -1; } *data = 0; for (p = strtok_r(s, ",", &saveptr); p != NULL; p = strtok_r(NULL, ",", &saveptr)) parse_mntopt(p, mntflags, &data); if (*data) *mntdata = data; else free(data); free(s); return 0; } static void null_endofword(char *word) { while (*word && *word != ' ' && *word != '\t') word++; *word = '\0'; } /* * skip @nfields spaces in @src */ static char *get_field(char *src, int nfields) { char *p = src; int i; for (i = 0; i < nfields; i++) { while (*p && *p != ' ' && *p != '\t') p++; if (!*p) break; p++; } return p; } static int mount_entry(const char *fsname, const char *target, const char *fstype, unsigned long mountflags, const char *data, int optional, const char *rootfs) { #ifdef HAVE_STATVFS struct statvfs sb; #endif if (safe_mount(fsname, target, fstype, mountflags & ~MS_REMOUNT, data, rootfs)) { if (optional) { INFO("failed to mount '%s' on '%s' (optional): %s", fsname, target, strerror(errno)); return 0; } else { SYSERROR("failed to mount '%s' on '%s'", fsname, target); return -1; } } if ((mountflags & MS_REMOUNT) || (mountflags & MS_BIND)) { DEBUG("remounting %s on %s to respect bind or remount options", fsname ? fsname : "(none)", target ? target : "(none)"); unsigned long rqd_flags = 0; if (mountflags & MS_RDONLY) rqd_flags |= MS_RDONLY; #ifdef HAVE_STATVFS if (statvfs(fsname, &sb) == 0) { unsigned long required_flags = rqd_flags; if (sb.f_flag & MS_NOSUID) required_flags |= MS_NOSUID; if (sb.f_flag & MS_NODEV) required_flags |= MS_NODEV; if (sb.f_flag & MS_RDONLY) required_flags |= MS_RDONLY; if (sb.f_flag & MS_NOEXEC) required_flags |= MS_NOEXEC; DEBUG("(at remount) flags for %s was %lu, required extra flags are %lu", fsname, sb.f_flag, required_flags); /* * If this was a bind mount request, and required_flags * does not have any flags which are not already in * mountflags, then skip the remount */ if (!(mountflags & MS_REMOUNT)) { if (!(required_flags & ~mountflags) && rqd_flags == 0) { DEBUG("mountflags already was %lu, skipping remount", mountflags); goto skipremount; } } mountflags |= required_flags; } #endif if (mount(fsname, target, fstype, mountflags | MS_REMOUNT, data) < 0) { if (optional) { INFO("failed to mount '%s' on '%s' (optional): %s", fsname, target, strerror(errno)); return 0; } else { SYSERROR("failed to mount '%s' on '%s'", fsname, target); return -1; } } } #ifdef HAVE_STATVFS skipremount: #endif DEBUG("mounted '%s' on '%s', type '%s'", fsname, target, fstype); return 0; } /* * Remove 'optional', 'create=dir', and 'create=file' from mntopt */ static void cull_mntent_opt(struct mntent *mntent) { int i; char *p, *p2; char *list[] = {"create=dir", "create=file", "optional", NULL }; for (i=0; list[i]; i++) { if (!(p = strstr(mntent->mnt_opts, list[i]))) continue; p2 = strchr(p, ','); if (!p2) { /* no more mntopts, so just chop it here */ *p = '\0'; continue; } memmove(p, p2+1, strlen(p2+1)+1); } } static int mount_entry_create_dir_file(const struct mntent *mntent, const char* path) { char *pathdirname = NULL; int ret = 0; FILE *pathfile = NULL; if (hasmntopt(mntent, "create=dir")) { if (mkdir_p(path, 0755) < 0) { WARN("Failed to create mount target '%s'", path); ret = -1; } } if (hasmntopt(mntent, "create=file") && access(path, F_OK)) { pathdirname = strdup(path); pathdirname = dirname(pathdirname); if (mkdir_p(pathdirname, 0755) < 0) { WARN("Failed to create target directory"); } pathfile = fopen(path, "wb"); if (!pathfile) { WARN("Failed to create mount target '%s'", path); ret = -1; } else fclose(pathfile); } free(pathdirname); return ret; } static inline int mount_entry_on_generic(struct mntent *mntent, const char* path, const char *rootfs) { unsigned long mntflags; char *mntdata; int ret; bool optional = hasmntopt(mntent, "optional") != NULL; ret = mount_entry_create_dir_file(mntent, path); if (ret < 0) return optional ? 0 : -1; cull_mntent_opt(mntent); if (parse_mntopts(mntent->mnt_opts, &mntflags, &mntdata) < 0) { free(mntdata); return -1; } ret = mount_entry(mntent->mnt_fsname, path, mntent->mnt_type, mntflags, mntdata, optional, rootfs); free(mntdata); return ret; } static inline int mount_entry_on_systemfs(struct mntent *mntent) { return mount_entry_on_generic(mntent, mntent->mnt_dir, NULL); } static int mount_entry_on_absolute_rootfs(struct mntent *mntent, const struct lxc_rootfs *rootfs, const char *lxc_name) { char *aux; char path[MAXPATHLEN]; int r, ret = 0, offset; const char *lxcpath; lxcpath = lxc_global_config_value("lxc.lxcpath"); if (!lxcpath) { ERROR("Out of memory"); return -1; } /* if rootfs->path is a blockdev path, allow container fstab to * use $lxcpath/CN/rootfs as the target prefix */ r = snprintf(path, MAXPATHLEN, "%s/%s/rootfs", lxcpath, lxc_name); if (r < 0 || r >= MAXPATHLEN) goto skipvarlib; aux = strstr(mntent->mnt_dir, path); if (aux) { offset = strlen(path); goto skipabs; } skipvarlib: aux = strstr(mntent->mnt_dir, rootfs->path); if (!aux) { WARN("ignoring mount point '%s'", mntent->mnt_dir); return ret; } offset = strlen(rootfs->path); skipabs: r = snprintf(path, MAXPATHLEN, "%s/%s", rootfs->mount, aux + offset); if (r < 0 || r >= MAXPATHLEN) { WARN("pathnme too long for '%s'", mntent->mnt_dir); return -1; } return mount_entry_on_generic(mntent, path, rootfs->mount); } static int mount_entry_on_relative_rootfs(struct mntent *mntent, const char *rootfs) { char path[MAXPATHLEN]; int ret; /* relative to root mount point */ ret = snprintf(path, sizeof(path), "%s/%s", rootfs, mntent->mnt_dir); if (ret >= sizeof(path)) { ERROR("path name too long"); return -1; } return mount_entry_on_generic(mntent, path, rootfs); } static int mount_file_entries(const struct lxc_rootfs *rootfs, FILE *file, const char *lxc_name) { struct mntent mntent; char buf[4096]; int ret = -1; while (getmntent_r(file, &mntent, buf, sizeof(buf))) { if (!rootfs->path) { if (mount_entry_on_systemfs(&mntent)) goto out; continue; } /* We have a separate root, mounts are relative to it */ if (mntent.mnt_dir[0] != '/') { if (mount_entry_on_relative_rootfs(&mntent, rootfs->mount)) goto out; continue; } if (mount_entry_on_absolute_rootfs(&mntent, rootfs, lxc_name)) goto out; } ret = 0; INFO("mount points have been setup"); out: return ret; } static int setup_mount(const struct lxc_rootfs *rootfs, const char *fstab, const char *lxc_name) { FILE *file; int ret; if (!fstab) return 0; file = setmntent(fstab, "r"); if (!file) { SYSERROR("failed to use '%s'", fstab); return -1; } ret = mount_file_entries(rootfs, file, lxc_name); endmntent(file); return ret; } FILE *write_mount_file(struct lxc_list *mount) { FILE *file; struct lxc_list *iterator; char *mount_entry; file = tmpfile(); if (!file) { ERROR("tmpfile error: %m"); return NULL; } lxc_list_for_each(iterator, mount) { mount_entry = iterator->elem; fprintf(file, "%s\n", mount_entry); } rewind(file); return file; } static int setup_mount_entries(const struct lxc_rootfs *rootfs, struct lxc_list *mount, const char *lxc_name) { FILE *file; int ret; file = write_mount_file(mount); if (!file) return -1; ret = mount_file_entries(rootfs, file, lxc_name); fclose(file); return ret; } static int parse_cap(const char *cap) { char *ptr = NULL; int i, capid = -1; if (!strcmp(cap, "none")) return -2; for (i = 0; i < sizeof(caps_opt)/sizeof(caps_opt[0]); i++) { if (strcmp(cap, caps_opt[i].name)) continue; capid = caps_opt[i].value; break; } if (capid < 0) { /* try to see if it's numeric, so the user may specify * capabilities that the running kernel knows about but * we don't */ errno = 0; capid = strtol(cap, &ptr, 10); if (!ptr || *ptr != '\0' || errno != 0) /* not a valid number */ capid = -1; else if (capid > lxc_caps_last_cap()) /* we have a number but it's not a valid * capability */ capid = -1; } return capid; } int in_caplist(int cap, struct lxc_list *caps) { struct lxc_list *iterator; int capid; lxc_list_for_each(iterator, caps) { capid = parse_cap(iterator->elem); if (capid == cap) return 1; } return 0; } static int setup_caps(struct lxc_list *caps) { struct lxc_list *iterator; char *drop_entry; int capid; lxc_list_for_each(iterator, caps) { drop_entry = iterator->elem; capid = parse_cap(drop_entry); if (capid < 0) { ERROR("unknown capability %s", drop_entry); return -1; } DEBUG("drop capability '%s' (%d)", drop_entry, capid); if (prctl(PR_CAPBSET_DROP, capid, 0, 0, 0)) { SYSERROR("failed to remove %s capability", drop_entry); return -1; } } DEBUG("capabilities have been setup"); return 0; } static int dropcaps_except(struct lxc_list *caps) { struct lxc_list *iterator; char *keep_entry; int i, capid; int numcaps = lxc_caps_last_cap() + 1; INFO("found %d capabilities", numcaps); if (numcaps <= 0 || numcaps > 200) return -1; // caplist[i] is 1 if we keep capability i int *caplist = alloca(numcaps * sizeof(int)); memset(caplist, 0, numcaps * sizeof(int)); lxc_list_for_each(iterator, caps) { keep_entry = iterator->elem; capid = parse_cap(keep_entry); if (capid == -2) continue; if (capid < 0) { ERROR("unknown capability %s", keep_entry); return -1; } DEBUG("keep capability '%s' (%d)", keep_entry, capid); caplist[capid] = 1; } for (i=0; i<numcaps; i++) { if (caplist[i]) continue; if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0)) { SYSERROR("failed to remove capability %d", i); return -1; } } DEBUG("capabilities have been setup"); return 0; } static int setup_hw_addr(char *hwaddr, const char *ifname) { struct sockaddr sockaddr; struct ifreq ifr; int ret, fd; ret = lxc_convert_mac(hwaddr, &sockaddr); if (ret) { ERROR("mac address '%s' conversion failed : %s", hwaddr, strerror(-ret)); return -1; } memcpy(ifr.ifr_name, ifname, IFNAMSIZ); ifr.ifr_name[IFNAMSIZ-1] = '\0'; memcpy((char *) &ifr.ifr_hwaddr, (char *) &sockaddr, sizeof(sockaddr)); fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { ERROR("socket failure : %s", strerror(errno)); return -1; } ret = ioctl(fd, SIOCSIFHWADDR, &ifr); close(fd); if (ret) ERROR("ioctl failure : %s", strerror(errno)); DEBUG("mac address '%s' on '%s' has been setup", hwaddr, ifr.ifr_name); return ret; } static int setup_ipv4_addr(struct lxc_list *ip, int ifindex) { struct lxc_list *iterator; struct lxc_inetdev *inetdev; int err; lxc_list_for_each(iterator, ip) { inetdev = iterator->elem; err = lxc_ipv4_addr_add(ifindex, &inetdev->addr, &inetdev->bcast, inetdev->prefix); if (err) { ERROR("failed to setup_ipv4_addr ifindex %d : %s", ifindex, strerror(-err)); return -1; } } return 0; } static int setup_ipv6_addr(struct lxc_list *ip, int ifindex) { struct lxc_list *iterator; struct lxc_inet6dev *inet6dev; int err; lxc_list_for_each(iterator, ip) { inet6dev = iterator->elem; err = lxc_ipv6_addr_add(ifindex, &inet6dev->addr, &inet6dev->mcast, &inet6dev->acast, inet6dev->prefix); if (err) { ERROR("failed to setup_ipv6_addr ifindex %d : %s", ifindex, strerror(-err)); return -1; } } return 0; } static int setup_netdev(struct lxc_netdev *netdev) { char ifname[IFNAMSIZ]; char *current_ifname = ifname; int err; /* empty network namespace */ if (!netdev->ifindex) { if (netdev->flags & IFF_UP) { err = lxc_netdev_up("lo"); if (err) { ERROR("failed to set the loopback up : %s", strerror(-err)); return -1; } } if (netdev->type != LXC_NET_VETH) return 0; netdev->ifindex = if_nametoindex(netdev->name); } /* get the new ifindex in case of physical netdev */ if (netdev->type == LXC_NET_PHYS) { if (!(netdev->ifindex = if_nametoindex(netdev->link))) { ERROR("failed to get ifindex for %s", netdev->link); return -1; } } /* retrieve the name of the interface */ if (!if_indextoname(netdev->ifindex, current_ifname)) { ERROR("no interface corresponding to index '%d'", netdev->ifindex); return -1; } /* default: let the system to choose one interface name */ if (!netdev->name) netdev->name = netdev->type == LXC_NET_PHYS ? netdev->link : "eth%d"; /* rename the interface name */ if (strcmp(ifname, netdev->name) != 0) { err = lxc_netdev_rename_by_name(ifname, netdev->name); if (err) { ERROR("failed to rename %s->%s : %s", ifname, netdev->name, strerror(-err)); return -1; } } /* Re-read the name of the interface because its name has changed * and would be automatically allocated by the system */ if (!if_indextoname(netdev->ifindex, current_ifname)) { ERROR("no interface corresponding to index '%d'", netdev->ifindex); return -1; } /* set a mac address */ if (netdev->hwaddr) { if (setup_hw_addr(netdev->hwaddr, current_ifname)) { ERROR("failed to setup hw address for '%s'", current_ifname); return -1; } } /* setup ipv4 addresses on the interface */ if (setup_ipv4_addr(&netdev->ipv4, netdev->ifindex)) { ERROR("failed to setup ip addresses for '%s'", ifname); return -1; } /* setup ipv6 addresses on the interface */ if (setup_ipv6_addr(&netdev->ipv6, netdev->ifindex)) { ERROR("failed to setup ipv6 addresses for '%s'", ifname); return -1; } /* set the network device up */ if (netdev->flags & IFF_UP) { int err; err = lxc_netdev_up(current_ifname); if (err) { ERROR("failed to set '%s' up : %s", current_ifname, strerror(-err)); return -1; } /* the network is up, make the loopback up too */ err = lxc_netdev_up("lo"); if (err) { ERROR("failed to set the loopback up : %s", strerror(-err)); return -1; } } /* We can only set up the default routes after bringing * up the interface, sine bringing up the interface adds * the link-local routes and we can't add a default * route if the gateway is not reachable. */ /* setup ipv4 gateway on the interface */ if (netdev->ipv4_gateway) { if (!(netdev->flags & IFF_UP)) { ERROR("Cannot add ipv4 gateway for %s when not bringing up the interface", ifname); return -1; } if (lxc_list_empty(&netdev->ipv4)) { ERROR("Cannot add ipv4 gateway for %s when not assigning an address", ifname); return -1; } err = lxc_ipv4_gateway_add(netdev->ifindex, netdev->ipv4_gateway); if (err) { err = lxc_ipv4_dest_add(netdev->ifindex, netdev->ipv4_gateway); if (err) { ERROR("failed to add ipv4 dest for '%s': %s", ifname, strerror(-err)); } err = lxc_ipv4_gateway_add(netdev->ifindex, netdev->ipv4_gateway); if (err) { ERROR("failed to setup ipv4 gateway for '%s': %s", ifname, strerror(-err)); if (netdev->ipv4_gateway_auto) { char buf[INET_ADDRSTRLEN]; inet_ntop(AF_INET, netdev->ipv4_gateway, buf, sizeof(buf)); ERROR("tried to set autodetected ipv4 gateway '%s'", buf); } return -1; } } } /* setup ipv6 gateway on the interface */ if (netdev->ipv6_gateway) { if (!(netdev->flags & IFF_UP)) { ERROR("Cannot add ipv6 gateway for %s when not bringing up the interface", ifname); return -1; } if (lxc_list_empty(&netdev->ipv6) && !IN6_IS_ADDR_LINKLOCAL(netdev->ipv6_gateway)) { ERROR("Cannot add ipv6 gateway for %s when not assigning an address", ifname); return -1; } err = lxc_ipv6_gateway_add(netdev->ifindex, netdev->ipv6_gateway); if (err) { err = lxc_ipv6_dest_add(netdev->ifindex, netdev->ipv6_gateway); if (err) { ERROR("failed to add ipv6 dest for '%s': %s", ifname, strerror(-err)); } err = lxc_ipv6_gateway_add(netdev->ifindex, netdev->ipv6_gateway); if (err) { ERROR("failed to setup ipv6 gateway for '%s': %s", ifname, strerror(-err)); if (netdev->ipv6_gateway_auto) { char buf[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, netdev->ipv6_gateway, buf, sizeof(buf)); ERROR("tried to set autodetected ipv6 gateway '%s'", buf); } return -1; } } } DEBUG("'%s' has been setup", current_ifname); return 0; } static int setup_network(struct lxc_list *network) { struct lxc_list *iterator; struct lxc_netdev *netdev; lxc_list_for_each(iterator, network) { netdev = iterator->elem; if (setup_netdev(netdev)) { ERROR("failed to setup netdev"); return -1; } } if (!lxc_list_empty(network)) INFO("network has been setup"); return 0; } /* try to move physical nics to the init netns */ void restore_phys_nics_to_netns(int netnsfd, struct lxc_conf *conf) { int i, ret, oldfd; char path[MAXPATHLEN]; if (netnsfd < 0) return; ret = snprintf(path, MAXPATHLEN, "/proc/self/ns/net"); if (ret < 0 || ret >= MAXPATHLEN) { WARN("Failed to open monitor netns fd"); return; } if ((oldfd = open(path, O_RDONLY)) < 0) { SYSERROR("Failed to open monitor netns fd"); return; } if (setns(netnsfd, 0) != 0) { SYSERROR("Failed to enter container netns to reset nics"); close(oldfd); return; } for (i=0; i<conf->num_savednics; i++) { struct saved_nic *s = &conf->saved_nics[i]; if (lxc_netdev_move_by_index(s->ifindex, 1, NULL)) WARN("Error moving nic index:%d back to host netns", s->ifindex); } if (setns(oldfd, 0) != 0) SYSERROR("Failed to re-enter monitor's netns"); close(oldfd); } void lxc_rename_phys_nics_on_shutdown(int netnsfd, struct lxc_conf *conf) { int i; if (conf->num_savednics == 0) return; INFO("running to reset %d nic names", conf->num_savednics); restore_phys_nics_to_netns(netnsfd, conf); for (i=0; i<conf->num_savednics; i++) { struct saved_nic *s = &conf->saved_nics[i]; INFO("resetting nic %d to %s", s->ifindex, s->orig_name); lxc_netdev_rename_by_index(s->ifindex, s->orig_name); free(s->orig_name); } conf->num_savednics = 0; } static char *default_rootfs_mount = LXCROOTFSMOUNT; struct lxc_conf *lxc_conf_init(void) { struct lxc_conf *new; int i; new = malloc(sizeof(*new)); if (!new) { ERROR("lxc_conf_init : %m"); return NULL; } memset(new, 0, sizeof(*new)); new->loglevel = LXC_LOG_PRIORITY_NOTSET; new->personality = -1; new->autodev = 1; new->console.log_path = NULL; new->console.log_fd = -1; new->console.path = NULL; new->console.peer = -1; new->console.peerpty.busy = -1; new->console.peerpty.master = -1; new->console.peerpty.slave = -1; new->console.master = -1; new->console.slave = -1; new->console.name[0] = '\0'; new->maincmd_fd = -1; new->nbd_idx = -1; new->rootfs.mount = strdup(default_rootfs_mount); if (!new->rootfs.mount) { ERROR("lxc_conf_init : %m"); free(new); return NULL; } new->kmsg = 0; new->logfd = -1; lxc_list_init(&new->cgroup); lxc_list_init(&new->network); lxc_list_init(&new->mount_list); lxc_list_init(&new->caps); lxc_list_init(&new->keepcaps); lxc_list_init(&new->id_map); lxc_list_init(&new->includes); lxc_list_init(&new->aliens); lxc_list_init(&new->environment); for (i=0; i<NUM_LXC_HOOKS; i++) lxc_list_init(&new->hooks[i]); lxc_list_init(&new->groups); new->lsm_aa_profile = NULL; new->lsm_se_context = NULL; new->tmp_umount_proc = 0; for (i = 0; i < LXC_NS_MAX; i++) new->inherit_ns_fd[i] = -1; /* if running in a new user namespace, init and COMMAND * default to running as UID/GID 0 when using lxc-execute */ new->init_uid = 0; new->init_gid = 0; return new; } static int instantiate_veth(struct lxc_handler *handler, struct lxc_netdev *netdev) { char veth1buf[IFNAMSIZ], *veth1; char veth2buf[IFNAMSIZ], *veth2; int err, mtu = 0; if (netdev->priv.veth_attr.pair) { veth1 = netdev->priv.veth_attr.pair; if (handler->conf->reboot) lxc_netdev_delete_by_name(veth1); } else { err = snprintf(veth1buf, sizeof(veth1buf), "vethXXXXXX"); if (err >= sizeof(veth1buf)) { /* can't *really* happen, but... */ ERROR("veth1 name too long"); return -1; } veth1 = lxc_mkifname(veth1buf); if (!veth1) { ERROR("failed to allocate a temporary name"); return -1; } /* store away for deconf */ memcpy(netdev->priv.veth_attr.veth1, veth1, IFNAMSIZ); } snprintf(veth2buf, sizeof(veth2buf), "vethXXXXXX"); veth2 = lxc_mkifname(veth2buf); if (!veth2) { ERROR("failed to allocate a temporary name"); goto out_delete; } err = lxc_veth_create(veth1, veth2); if (err) { ERROR("failed to create veth pair (%s and %s): %s", veth1, veth2, strerror(-err)); goto out_delete; } /* changing the high byte of the mac address to 0xfe, the bridge interface * will always keep the host's mac address and not take the mac address * of a container */ err = setup_private_host_hw_addr(veth1); if (err) { ERROR("failed to change mac address of host interface '%s': %s", veth1, strerror(-err)); goto out_delete; } netdev->ifindex = if_nametoindex(veth2); if (!netdev->ifindex) { ERROR("failed to retrieve the index for %s", veth2); goto out_delete; } if (netdev->mtu) { mtu = atoi(netdev->mtu); } else if (netdev->link) { mtu = netdev_get_mtu(netdev->ifindex); } if (mtu) { err = lxc_netdev_set_mtu(veth1, mtu); if (!err) err = lxc_netdev_set_mtu(veth2, mtu); if (err) { ERROR("failed to set mtu '%i' for veth pair (%s and %s): %s", mtu, veth1, veth2, strerror(-err)); goto out_delete; } } if (netdev->link) { err = lxc_bridge_attach(netdev->link, veth1); if (err) { ERROR("failed to attach '%s' to the bridge '%s': %s", veth1, netdev->link, strerror(-err)); goto out_delete; } } err = lxc_netdev_up(veth1); if (err) { ERROR("failed to set %s up : %s", veth1, strerror(-err)); goto out_delete; } if (netdev->upscript) { err = run_script(handler->name, "net", netdev->upscript, "up", "veth", veth1, (char*) NULL); if (err) goto out_delete; } DEBUG("instantiated veth '%s/%s', index is '%d'", veth1, veth2, netdev->ifindex); return 0; out_delete: lxc_netdev_delete_by_name(veth1); if (!netdev->priv.veth_attr.pair) free(veth1); free(veth2); return -1; } static int shutdown_veth(struct lxc_handler *handler, struct lxc_netdev *netdev) { char *veth1; int err; if (netdev->priv.veth_attr.pair) veth1 = netdev->priv.veth_attr.pair; else veth1 = netdev->priv.veth_attr.veth1; if (netdev->downscript) { err = run_script(handler->name, "net", netdev->downscript, "down", "veth", veth1, (char*) NULL); if (err) return -1; } return 0; } static int instantiate_macvlan(struct lxc_handler *handler, struct lxc_netdev *netdev) { char peerbuf[IFNAMSIZ], *peer; int err; if (!netdev->link) { ERROR("no link specified for macvlan netdev"); return -1; } err = snprintf(peerbuf, sizeof(peerbuf), "mcXXXXXX"); if (err >= sizeof(peerbuf)) return -1; peer = lxc_mkifname(peerbuf); if (!peer) { ERROR("failed to make a temporary name"); return -1; } err = lxc_macvlan_create(netdev->link, peer, netdev->priv.macvlan_attr.mode); if (err) { ERROR("failed to create macvlan interface '%s' on '%s' : %s", peer, netdev->link, strerror(-err)); goto out; } netdev->ifindex = if_nametoindex(peer); if (!netdev->ifindex) { ERROR("failed to retrieve the index for %s", peer); goto out; } if (netdev->upscript) { err = run_script(handler->name, "net", netdev->upscript, "up", "macvlan", netdev->link, (char*) NULL); if (err) goto out; } DEBUG("instantiated macvlan '%s', index is '%d' and mode '%d'", peer, netdev->ifindex, netdev->priv.macvlan_attr.mode); return 0; out: lxc_netdev_delete_by_name(peer); free(peer); return -1; } static int shutdown_macvlan(struct lxc_handler *handler, struct lxc_netdev *netdev) { int err; if (netdev->downscript) { err = run_script(handler->name, "net", netdev->downscript, "down", "macvlan", netdev->link, (char*) NULL); if (err) return -1; } return 0; } /* XXX: merge with instantiate_macvlan */ static int instantiate_vlan(struct lxc_handler *handler, struct lxc_netdev *netdev) { char peer[IFNAMSIZ]; int err; static uint16_t vlan_cntr = 0; if (!netdev->link) { ERROR("no link specified for vlan netdev"); return -1; } err = snprintf(peer, sizeof(peer), "vlan%d-%d", netdev->priv.vlan_attr.vid, vlan_cntr++); if (err >= sizeof(peer)) { ERROR("peer name too long"); return -1; } err = lxc_vlan_create(netdev->link, peer, netdev->priv.vlan_attr.vid); if (err) { ERROR("failed to create vlan interface '%s' on '%s' : %s", peer, netdev->link, strerror(-err)); return -1; } netdev->ifindex = if_nametoindex(peer); if (!netdev->ifindex) { ERROR("failed to retrieve the ifindex for %s", peer); lxc_netdev_delete_by_name(peer); return -1; } DEBUG("instantiated vlan '%s', ifindex is '%d'", " vlan1000", netdev->ifindex); return 0; } static int shutdown_vlan(struct lxc_handler *handler, struct lxc_netdev *netdev) { return 0; } static int instantiate_phys(struct lxc_handler *handler, struct lxc_netdev *netdev) { if (!netdev->link) { ERROR("no link specified for the physical interface"); return -1; } netdev->ifindex = if_nametoindex(netdev->link); if (!netdev->ifindex) { ERROR("failed to retrieve the index for %s", netdev->link); return -1; } if (netdev->upscript) { int err; err = run_script(handler->name, "net", netdev->upscript, "up", "phys", netdev->link, (char*) NULL); if (err) return -1; } return 0; } static int shutdown_phys(struct lxc_handler *handler, struct lxc_netdev *netdev) { int err; if (netdev->downscript) { err = run_script(handler->name, "net", netdev->downscript, "down", "phys", netdev->link, (char*) NULL); if (err) return -1; } return 0; } static int instantiate_none(struct lxc_handler *handler, struct lxc_netdev *netdev) { netdev->ifindex = 0; return 0; } static int instantiate_empty(struct lxc_handler *handler, struct lxc_netdev *netdev) { netdev->ifindex = 0; if (netdev->upscript) { int err; err = run_script(handler->name, "net", netdev->upscript, "up", "empty", (char*) NULL); if (err) return -1; } return 0; } static int shutdown_empty(struct lxc_handler *handler, struct lxc_netdev *netdev) { int err; if (netdev->downscript) { err = run_script(handler->name, "net", netdev->downscript, "down", "empty", (char*) NULL); if (err) return -1; } return 0; } static int shutdown_none(struct lxc_handler *handler, struct lxc_netdev *netdev) { return 0; } int lxc_requests_empty_network(struct lxc_handler *handler) { struct lxc_list *network = &handler->conf->network; struct lxc_list *iterator; struct lxc_netdev *netdev; bool found_none = false, found_nic = false; if (lxc_list_empty(network)) return 0; lxc_list_for_each(iterator, network) { netdev = iterator->elem; if (netdev->type == LXC_NET_NONE) found_none = true; else found_nic = true; } if (found_none && !found_nic) return 1; return 0; } int lxc_create_network(struct lxc_handler *handler) { struct lxc_list *network = &handler->conf->network; struct lxc_list *iterator; struct lxc_netdev *netdev; int am_root = (getuid() == 0); if (!am_root) return 0; lxc_list_for_each(iterator, network) { netdev = iterator->elem; if (netdev->type < 0 || netdev->type > LXC_NET_MAXCONFTYPE) { ERROR("invalid network configuration type '%d'", netdev->type); return -1; } if (netdev_conf[netdev->type](handler, netdev)) { ERROR("failed to create netdev"); return -1; } } return 0; } void lxc_delete_network(struct lxc_handler *handler) { struct lxc_list *network = &handler->conf->network; struct lxc_list *iterator; struct lxc_netdev *netdev; lxc_list_for_each(iterator, network) { netdev = iterator->elem; if (netdev->ifindex != 0 && netdev->type == LXC_NET_PHYS) { if (lxc_netdev_rename_by_index(netdev->ifindex, netdev->link)) WARN("failed to rename to the initial name the " \ "netdev '%s'", netdev->link); continue; } if (netdev_deconf[netdev->type](handler, netdev)) { WARN("failed to destroy netdev"); } /* Recent kernel remove the virtual interfaces when the network * namespace is destroyed but in case we did not moved the * interface to the network namespace, we have to destroy it */ if (netdev->ifindex != 0 && lxc_netdev_delete_by_index(netdev->ifindex)) WARN("failed to remove interface '%s'", netdev->name); } } #define LXC_USERNIC_PATH LIBEXECDIR "/lxc/lxc-user-nic" /* lxc-user-nic returns "interface_name:interface_name\n" */ #define MAX_BUFFER_SIZE IFNAMSIZ*2 + 2 static int unpriv_assign_nic(struct lxc_netdev *netdev, pid_t pid) { pid_t child; int bytes, pipefd[2]; char *token, *saveptr = NULL; char buffer[MAX_BUFFER_SIZE]; char netdev_link[IFNAMSIZ+1]; if (netdev->type != LXC_NET_VETH) { ERROR("nic type %d not support for unprivileged use", netdev->type); return -1; } if(pipe(pipefd) < 0) { SYSERROR("pipe failed"); return -1; } if ((child = fork()) < 0) { SYSERROR("fork"); close(pipefd[0]); close(pipefd[1]); return -1; } if (child == 0) { // child /* close the read-end of the pipe */ close(pipefd[0]); /* redirect the stdout to write-end of the pipe */ dup2(pipefd[1], STDOUT_FILENO); /* close the write-end of the pipe */ close(pipefd[1]); // Call lxc-user-nic pid type bridge char pidstr[20]; if (netdev->link) { strncpy(netdev_link, netdev->link, IFNAMSIZ); } else { strncpy(netdev_link, "none", IFNAMSIZ); } char *args[] = {LXC_USERNIC_PATH, pidstr, "veth", netdev_link, netdev->name, NULL }; snprintf(pidstr, 19, "%lu", (unsigned long) pid); pidstr[19] = '\0'; execvp(args[0], args); SYSERROR("execvp lxc-user-nic"); exit(1); } /* close the write-end of the pipe */ close(pipefd[1]); bytes = read(pipefd[0], &buffer, MAX_BUFFER_SIZE); if (bytes < 0) { SYSERROR("read failed"); } buffer[bytes - 1] = '\0'; if (wait_for_pid(child) != 0) { close(pipefd[0]); return -1; } /* close the read-end of the pipe */ close(pipefd[0]); /* fill netdev->name field */ token = strtok_r(buffer, ":", &saveptr); if (!token) return -1; netdev->name = malloc(IFNAMSIZ+1); if (!netdev->name) { ERROR("Out of memory"); return -1; } memset(netdev->name, 0, IFNAMSIZ+1); strncpy(netdev->name, token, IFNAMSIZ); /* fill netdev->veth_attr.pair field */ token = strtok_r(NULL, ":", &saveptr); if (!token) return -1; netdev->priv.veth_attr.pair = strdup(token); if (!netdev->priv.veth_attr.pair) { ERROR("Out of memory"); return -1; } return 0; } int lxc_assign_network(struct lxc_list *network, pid_t pid) { struct lxc_list *iterator; struct lxc_netdev *netdev; int am_root = (getuid() == 0); int err; lxc_list_for_each(iterator, network) { netdev = iterator->elem; if (netdev->type == LXC_NET_VETH && !am_root) { if (unpriv_assign_nic(netdev, pid)) return -1; // lxc-user-nic has moved the nic to the new ns. // unpriv_assign_nic() fills in netdev->name. // netdev->ifindex will be filed in at setup_netdev. continue; } /* empty network namespace, nothing to move */ if (!netdev->ifindex) continue; err = lxc_netdev_move_by_index(netdev->ifindex, pid, NULL); if (err) { ERROR("failed to move '%s' to the container : %s", netdev->link, strerror(-err)); return -1; } DEBUG("move '%s' to '%d'", netdev->name, pid); } return 0; } static int write_id_mapping(enum idtype idtype, pid_t pid, const char *buf, size_t buf_size) { char path[PATH_MAX]; int ret, closeret; FILE *f; ret = snprintf(path, PATH_MAX, "/proc/%d/%cid_map", pid, idtype == ID_TYPE_UID ? 'u' : 'g'); if (ret < 0 || ret >= PATH_MAX) { fprintf(stderr, "%s: path name too long\n", __func__); return -E2BIG; } f = fopen(path, "w"); if (!f) { perror("open"); return -EINVAL; } ret = fwrite(buf, buf_size, 1, f); if (ret < 0) SYSERROR("writing id mapping"); closeret = fclose(f); if (closeret) SYSERROR("writing id mapping"); return ret < 0 ? ret : closeret; } int lxc_map_ids(struct lxc_list *idmap, pid_t pid) { struct lxc_list *iterator; struct id_map *map; int ret = 0, use_shadow = 0; enum idtype type; char *buf = NULL, *pos, *cmdpath = NULL; /* * If newuidmap exists, that is, if shadow is handing out subuid * ranges, then insist that root also reserve ranges in subuid. This * will protected it by preventing another user from being handed the * range by shadow. */ cmdpath = on_path("newuidmap", NULL); if (cmdpath) { use_shadow = 1; free(cmdpath); } if (!use_shadow && geteuid()) { ERROR("Missing newuidmap/newgidmap"); return -1; } for(type = ID_TYPE_UID; type <= ID_TYPE_GID; type++) { int left, fill; int had_entry = 0; if (!buf) { buf = pos = malloc(4096); if (!buf) return -ENOMEM; } pos = buf; if (use_shadow) pos += sprintf(buf, "new%cidmap %d", type == ID_TYPE_UID ? 'u' : 'g', pid); lxc_list_for_each(iterator, idmap) { /* The kernel only takes <= 4k for writes to /proc/<nr>/[ug]id_map */ map = iterator->elem; if (map->idtype != type) continue; had_entry = 1; left = 4096 - (pos - buf); fill = snprintf(pos, left, "%s%lu %lu %lu%s", use_shadow ? " " : "", map->nsid, map->hostid, map->range, use_shadow ? "" : "\n"); if (fill <= 0 || fill >= left) SYSERROR("snprintf failed, too many mappings"); pos += fill; } if (!had_entry) continue; if (!use_shadow) { ret = write_id_mapping(type, pid, buf, pos-buf); } else { left = 4096 - (pos - buf); fill = snprintf(pos, left, "\n"); if (fill <= 0 || fill >= left) SYSERROR("snprintf failed, too many mappings"); pos += fill; ret = system(buf); } if (ret) break; } free(buf); return ret; } /* * return the host uid/gid to which the container root is mapped in * *val. * Return true if id was found, false otherwise. */ bool get_mapped_rootid(struct lxc_conf *conf, enum idtype idtype, unsigned long *val) { struct lxc_list *it; struct id_map *map; lxc_list_for_each(it, &conf->id_map) { map = it->elem; if (map->idtype != idtype) continue; if (map->nsid != 0) continue; *val = map->hostid; return true; } return false; } int mapped_hostid(unsigned id, struct lxc_conf *conf, enum idtype idtype) { struct lxc_list *it; struct id_map *map; lxc_list_for_each(it, &conf->id_map) { map = it->elem; if (map->idtype != idtype) continue; if (id >= map->hostid && id < map->hostid + map->range) return (id - map->hostid) + map->nsid; } return -1; } int find_unmapped_nsuid(struct lxc_conf *conf, enum idtype idtype) { struct lxc_list *it; struct id_map *map; unsigned int freeid = 0; again: lxc_list_for_each(it, &conf->id_map) { map = it->elem; if (map->idtype != idtype) continue; if (freeid >= map->nsid && freeid < map->nsid + map->range) { freeid = map->nsid + map->range; goto again; } } return freeid; } int lxc_find_gateway_addresses(struct lxc_handler *handler) { struct lxc_list *network = &handler->conf->network; struct lxc_list *iterator; struct lxc_netdev *netdev; int link_index; lxc_list_for_each(iterator, network) { netdev = iterator->elem; if (!netdev->ipv4_gateway_auto && !netdev->ipv6_gateway_auto) continue; if (netdev->type != LXC_NET_VETH && netdev->type != LXC_NET_MACVLAN) { ERROR("gateway = auto only supported for " "veth and macvlan"); return -1; } if (!netdev->link) { ERROR("gateway = auto needs a link interface"); return -1; } link_index = if_nametoindex(netdev->link); if (!link_index) return -EINVAL; if (netdev->ipv4_gateway_auto) { if (lxc_ipv4_addr_get(link_index, &netdev->ipv4_gateway)) { ERROR("failed to automatically find ipv4 gateway " "address from link interface '%s'", netdev->link); return -1; } } if (netdev->ipv6_gateway_auto) { if (lxc_ipv6_addr_get(link_index, &netdev->ipv6_gateway)) { ERROR("failed to automatically find ipv6 gateway " "address from link interface '%s'", netdev->link); return -1; } } } return 0; } int lxc_create_tty(const char *name, struct lxc_conf *conf) { struct lxc_tty_info *tty_info = &conf->tty_info; int i, ret; /* no tty in the configuration */ if (!conf->tty) return 0; tty_info->pty_info = malloc(sizeof(*tty_info->pty_info)*conf->tty); if (!tty_info->pty_info) { SYSERROR("failed to allocate pty_info"); return -1; } for (i = 0; i < conf->tty; i++) { struct lxc_pty_info *pty_info = &tty_info->pty_info[i]; process_lock(); ret = openpty(&pty_info->master, &pty_info->slave, pty_info->name, NULL, NULL); process_unlock(); if (ret) { SYSERROR("failed to create pty #%d", i); tty_info->nbtty = i; lxc_delete_tty(tty_info); return -1; } DEBUG("allocated pty '%s' (%d/%d)", pty_info->name, pty_info->master, pty_info->slave); /* Prevent leaking the file descriptors to the container */ fcntl(pty_info->master, F_SETFD, FD_CLOEXEC); fcntl(pty_info->slave, F_SETFD, FD_CLOEXEC); pty_info->busy = 0; } tty_info->nbtty = conf->tty; INFO("tty's configured"); return 0; } void lxc_delete_tty(struct lxc_tty_info *tty_info) { int i; for (i = 0; i < tty_info->nbtty; i++) { struct lxc_pty_info *pty_info = &tty_info->pty_info[i]; close(pty_info->master); close(pty_info->slave); } free(tty_info->pty_info); tty_info->nbtty = 0; } /* * chown_mapped_root: for an unprivileged user with uid/gid X to * chown a dir to subuid/subgid Y, he needs to run chown as root * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and * nsid Y is mapped to hostuid/hostgid X. That way, the container * root is privileged with respect to hostuid/hostgid X, allowing * him to do the chown. */ int chown_mapped_root(char *path, struct lxc_conf *conf) { uid_t rootuid; gid_t rootgid; pid_t pid; unsigned long val; char *chownpath = path; if (!get_mapped_rootid(conf, ID_TYPE_UID, &val)) { ERROR("No mapping for container root"); return -1; } rootuid = (uid_t) val; if (!get_mapped_rootid(conf, ID_TYPE_GID, &val)) { ERROR("No mapping for container root"); return -1; } rootgid = (gid_t) val; /* * In case of overlay, we want only the writeable layer * to be chowned */ if (strncmp(path, "overlayfs:", 10) == 0 || strncmp(path, "aufs:", 5) == 0) { chownpath = strchr(path, ':'); if (!chownpath) { ERROR("Bad overlay path: %s", path); return -1; } chownpath = strchr(chownpath+1, ':'); if (!chownpath) { ERROR("Bad overlay path: %s", path); return -1; } chownpath++; } path = chownpath; if (geteuid() == 0) { if (chown(path, rootuid, rootgid) < 0) { ERROR("Error chowning %s", path); return -1; } return 0; } if (rootuid == geteuid()) { // nothing to do INFO("%s: container root is our uid; no need to chown" ,__func__); return 0; } pid = fork(); if (pid < 0) { SYSERROR("Failed forking"); return -1; } if (!pid) { int hostuid = geteuid(), hostgid = getegid(), ret; struct stat sb; char map1[100], map2[100], map3[100], map4[100], map5[100]; char ugid[100]; char *args1[] = { "lxc-usernsexec", "-m", map1, "-m", map2, "-m", map3, "-m", map5, "--", "chown", ugid, path, NULL }; char *args2[] = { "lxc-usernsexec", "-m", map1, "-m", map2, "-m", map3, "-m", map4, "-m", map5, "--", "chown", ugid, path, NULL }; // save the current gid of "path" if (stat(path, &sb) < 0) { ERROR("Error stat %s", path); return -1; } /* * A file has to be group-owned by a gid mapped into the * container, or the container won't be privileged over it. */ if (sb.st_uid == geteuid() && mapped_hostid(sb.st_gid, conf, ID_TYPE_GID) < 0 && chown(path, -1, hostgid) < 0) { ERROR("Failed chgrping %s", path); return -1; } // "u:0:rootuid:1" ret = snprintf(map1, 100, "u:0:%d:1", rootuid); if (ret < 0 || ret >= 100) { ERROR("Error uid printing map string"); return -1; } // "u:hostuid:hostuid:1" ret = snprintf(map2, 100, "u:%d:%d:1", hostuid, hostuid); if (ret < 0 || ret >= 100) { ERROR("Error uid printing map string"); return -1; } // "g:0:rootgid:1" ret = snprintf(map3, 100, "g:0:%d:1", rootgid); if (ret < 0 || ret >= 100) { ERROR("Error gid printing map string"); return -1; } // "g:pathgid:rootgid+pathgid:1" ret = snprintf(map4, 100, "g:%d:%d:1", (gid_t)sb.st_gid, rootgid + (gid_t)sb.st_gid); if (ret < 0 || ret >= 100) { ERROR("Error gid printing map string"); return -1; } // "g:hostgid:hostgid:1" ret = snprintf(map5, 100, "g:%d:%d:1", hostgid, hostgid); if (ret < 0 || ret >= 100) { ERROR("Error gid printing map string"); return -1; } // "0:pathgid" (chown) ret = snprintf(ugid, 100, "0:%d", (gid_t)sb.st_gid); if (ret < 0 || ret >= 100) { ERROR("Error owner printing format string for chown"); return -1; } if (hostgid == sb.st_gid) ret = execvp("lxc-usernsexec", args1); else ret = execvp("lxc-usernsexec", args2); SYSERROR("Failed executing usernsexec"); exit(1); } return wait_for_pid(pid); } int ttys_shift_ids(struct lxc_conf *c) { if (lxc_list_empty(&c->id_map)) return 0; if (strcmp(c->console.name, "") !=0 && chown_mapped_root(c->console.name, c) < 0) { ERROR("Failed to chown %s", c->console.name); return -1; } return 0; } int tmp_proc_mount(struct lxc_conf *lxc_conf) { int mounted; mounted = mount_proc_if_needed(lxc_conf->rootfs.path ? lxc_conf->rootfs.mount : ""); if (mounted == -1) { SYSERROR("failed to mount /proc in the container."); /* continue only if there is no rootfs */ if (lxc_conf->rootfs.path) return -1; } else if (mounted == 1) { lxc_conf->tmp_umount_proc = 1; } return 0; } void tmp_proc_unmount(struct lxc_conf *lxc_conf) { if (lxc_conf->tmp_umount_proc == 1) { umount("/proc"); lxc_conf->tmp_umount_proc = 0; } } void remount_all_slave(void) { /* walk /proc/mounts and change any shared entries to slave */ FILE *f = fopen("/proc/self/mountinfo", "r"); char *line = NULL; size_t len = 0; if (!f) { SYSERROR("Failed to open /proc/self/mountinfo to mark all shared"); ERROR("Continuing container startup..."); return; } while (getline(&line, &len, f) != -1) { char *target, *opts; target = get_field(line, 4); if (!target) continue; opts = get_field(target, 2); if (!opts) continue; null_endofword(opts); if (!strstr(opts, "shared")) continue; null_endofword(target); if (mount(NULL, target, NULL, MS_SLAVE, NULL)) { SYSERROR("Failed to make %s rslave", target); ERROR("Continuing..."); } } fclose(f); free(line); } void lxc_execute_bind_init(struct lxc_conf *conf) { int ret; char path[PATH_MAX], destpath[PATH_MAX], *p; /* If init exists in the container, don't bind mount a static one */ p = choose_init(conf->rootfs.mount); if (p) { free(p); return; } ret = snprintf(path, PATH_MAX, SBINDIR "/init.lxc.static"); if (ret < 0 || ret >= PATH_MAX) { WARN("Path name too long searching for lxc.init.static"); return; } if (!file_exists(path)) { INFO("%s does not exist on host", path); return; } ret = snprintf(destpath, PATH_MAX, "%s%s", conf->rootfs.mount, "/init.lxc.static"); if (ret < 0 || ret >= PATH_MAX) { WARN("Path name too long for container's lxc.init.static"); return; } if (!file_exists(destpath)) { FILE * pathfile = fopen(destpath, "wb"); if (!pathfile) { SYSERROR("Failed to create mount target '%s'", destpath); return; } fclose(pathfile); } ret = safe_mount(path, destpath, "none", MS_BIND, NULL, conf->rootfs.mount); if (ret < 0) SYSERROR("Failed to bind lxc.init.static into container"); INFO("lxc.init.static bound into container at %s", path); } /* * This does the work of remounting / if it is shared, calling the * container pre-mount hooks, and mounting the rootfs. */ int do_rootfs_setup(struct lxc_conf *conf, const char *name, const char *lxcpath) { if (conf->rootfs_setup) { /* * rootfs was set up in another namespace. bind-mount it * to give us a mount in our own ns so we can pivot_root to it */ const char *path = conf->rootfs.mount; if (mount(path, path, "rootfs", MS_BIND, NULL) < 0) { ERROR("Failed to bind-mount container / onto itself"); return -1; } return 0; } remount_all_slave(); if (run_lxc_hooks(name, "pre-mount", conf, lxcpath, NULL)) { ERROR("failed to run pre-mount hooks for container '%s'.", name); return -1; } if (setup_rootfs(conf)) { ERROR("failed to setup rootfs for '%s'", name); return -1; } conf->rootfs_setup = true; return 0; } static bool verify_start_hooks(struct lxc_conf *conf) { struct lxc_list *it; char path[MAXPATHLEN]; lxc_list_for_each(it, &conf->hooks[LXCHOOK_START]) { char *hookname = it->elem; struct stat st; int ret; ret = snprintf(path, MAXPATHLEN, "%s%s", conf->rootfs.path ? conf->rootfs.mount : "", hookname); if (ret < 0 || ret >= MAXPATHLEN) return false; ret = stat(path, &st); if (ret) { SYSERROR("Start hook %s not found in container", hookname); return false; } return true; } return true; } static int send_fd(int sock, int fd) { int ret = lxc_abstract_unix_send_fd(sock, fd, NULL, 0); if (ret < 0) { SYSERROR("Error sending tty fd to parent"); return -1; } return 0; } static int send_ttys_to_parent(struct lxc_handler *handler) { struct lxc_conf *conf = handler->conf; const struct lxc_tty_info *tty_info = &conf->tty_info; int i; int sock = handler->ttysock[0]; for (i = 0; i < tty_info->nbtty; i++) { struct lxc_pty_info *pty_info = &tty_info->pty_info[i]; if (send_fd(sock, pty_info->slave) < 0) goto bad; close(pty_info->slave); pty_info->slave = -1; if (send_fd(sock, pty_info->master) < 0) goto bad; close(pty_info->master); pty_info->master = -1; } close(handler->ttysock[0]); close(handler->ttysock[1]); return 0; bad: ERROR("Error writing tty fd to parent"); return -1; } int lxc_setup(struct lxc_handler *handler) { const char *name = handler->name; struct lxc_conf *lxc_conf = handler->conf; const char *lxcpath = handler->lxcpath; if (do_rootfs_setup(lxc_conf, name, lxcpath) < 0) { ERROR("Error setting up rootfs mount after spawn"); return -1; } if (lxc_conf->inherit_ns_fd[LXC_NS_UTS] == -1) { if (setup_utsname(lxc_conf->utsname)) { ERROR("failed to setup the utsname for '%s'", name); return -1; } } if (setup_network(&lxc_conf->network)) { ERROR("failed to setup the network for '%s'", name); return -1; } if (lxc_conf->autodev > 0) { if (mount_autodev(name, &lxc_conf->rootfs, lxcpath)) { ERROR("failed to mount /dev in the container"); return -1; } } /* do automatic mounts (mainly /proc and /sys), but exclude * those that need to wait until other stuff has finished */ if (lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & ~LXC_AUTO_CGROUP_MASK, handler) < 0) { ERROR("failed to setup the automatic mounts for '%s'", name); return -1; } if (setup_mount(&lxc_conf->rootfs, lxc_conf->fstab, name)) { ERROR("failed to setup the mounts for '%s'", name); return -1; } if (!lxc_list_empty(&lxc_conf->mount_list) && setup_mount_entries(&lxc_conf->rootfs, &lxc_conf->mount_list, name)) { ERROR("failed to setup the mount entries for '%s'", name); return -1; } /* Make sure any start hooks are in the container */ if (!verify_start_hooks(lxc_conf)) return -1; if (lxc_conf->is_execute) lxc_execute_bind_init(lxc_conf); /* now mount only cgroup, if wanted; * before, /sys could not have been mounted * (is either mounted automatically or via fstab entries) */ if (lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & LXC_AUTO_CGROUP_MASK, handler) < 0) { ERROR("failed to setup the automatic mounts for '%s'", name); return -1; } if (run_lxc_hooks(name, "mount", lxc_conf, lxcpath, NULL)) { ERROR("failed to run mount hooks for container '%s'.", name); return -1; } if (lxc_conf->autodev > 0) { if (run_lxc_hooks(name, "autodev", lxc_conf, lxcpath, NULL)) { ERROR("failed to run autodev hooks for container '%s'.", name); return -1; } if (fill_autodev(&lxc_conf->rootfs)) { ERROR("failed to populate /dev in the container"); return -1; } } if (!lxc_conf->is_execute && setup_console(&lxc_conf->rootfs, &lxc_conf->console, lxc_conf->ttydir)) { ERROR("failed to setup the console for '%s'", name); return -1; } if (lxc_conf->kmsg) { if (setup_kmsg(&lxc_conf->rootfs, &lxc_conf->console)) // don't fail ERROR("failed to setup kmsg for '%s'", name); } if (!lxc_conf->is_execute && setup_dev_symlinks(&lxc_conf->rootfs)) { ERROR("failed to setup /dev symlinks for '%s'", name); return -1; } /* mount /proc if it's not already there */ if (tmp_proc_mount(lxc_conf) < 0) { ERROR("failed to LSM mount proc for '%s'", name); return -1; } if (setup_pivot_root(&lxc_conf->rootfs)) { ERROR("failed to set rootfs for '%s'", name); return -1; } if (setup_pts(lxc_conf->pts)) { ERROR("failed to setup the new pts instance"); return -1; } if (lxc_create_tty(name, lxc_conf)) { ERROR("failed to create the ttys"); return -1; } if (send_ttys_to_parent(handler) < 0) { ERROR("failure sending console info to parent"); return -1; } if (!lxc_conf->is_execute && setup_tty(lxc_conf)) { ERROR("failed to setup the ttys for '%s'", name); return -1; } if (lxc_conf->pty_names && setenv("container_ttys", lxc_conf->pty_names, 1)) SYSERROR("failed to set environment variable for container ptys"); if (setup_personality(lxc_conf->personality)) { ERROR("failed to setup personality"); return -1; } if (!lxc_list_empty(&lxc_conf->keepcaps)) { if (!lxc_list_empty(&lxc_conf->caps)) { ERROR("Simultaneously requested dropping and keeping caps"); return -1; } if (dropcaps_except(&lxc_conf->keepcaps)) { ERROR("failed to keep requested caps"); return -1; } } else if (setup_caps(&lxc_conf->caps)) { ERROR("failed to drop capabilities"); return -1; } NOTICE("'%s' is setup.", name); return 0; } int run_lxc_hooks(const char *name, char *hook, struct lxc_conf *conf, const char *lxcpath, char *argv[]) { int which = -1; struct lxc_list *it; if (strcmp(hook, "pre-start") == 0) which = LXCHOOK_PRESTART; else if (strcmp(hook, "pre-mount") == 0) which = LXCHOOK_PREMOUNT; else if (strcmp(hook, "mount") == 0) which = LXCHOOK_MOUNT; else if (strcmp(hook, "autodev") == 0) which = LXCHOOK_AUTODEV; else if (strcmp(hook, "start") == 0) which = LXCHOOK_START; else if (strcmp(hook, "post-stop") == 0) which = LXCHOOK_POSTSTOP; else if (strcmp(hook, "clone") == 0) which = LXCHOOK_CLONE; else if (strcmp(hook, "destroy") == 0) which = LXCHOOK_DESTROY; else return -1; lxc_list_for_each(it, &conf->hooks[which]) { int ret; char *hookname = it->elem; ret = run_script_argv(name, "lxc", hookname, hook, lxcpath, argv); if (ret) return ret; } return 0; } static void lxc_remove_nic(struct lxc_list *it) { struct lxc_netdev *netdev = it->elem; struct lxc_list *it2,*next; lxc_list_del(it); free(netdev->link); free(netdev->name); if (netdev->type == LXC_NET_VETH) free(netdev->priv.veth_attr.pair); free(netdev->upscript); free(netdev->hwaddr); free(netdev->mtu); free(netdev->ipv4_gateway); free(netdev->ipv6_gateway); lxc_list_for_each_safe(it2, &netdev->ipv4, next) { lxc_list_del(it2); free(it2->elem); free(it2); } lxc_list_for_each_safe(it2, &netdev->ipv6, next) { lxc_list_del(it2); free(it2->elem); free(it2); } free(netdev); free(it); } /* we get passed in something like '0', '0.ipv4' or '1.ipv6' */ int lxc_clear_nic(struct lxc_conf *c, const char *key) { char *p1; int ret, idx, i; struct lxc_list *it; struct lxc_netdev *netdev; p1 = strchr(key, '.'); if (!p1 || *(p1+1) == '\0') p1 = NULL; ret = sscanf(key, "%d", &idx); if (ret != 1) return -1; if (idx < 0) return -1; i = 0; lxc_list_for_each(it, &c->network) { if (i == idx) break; i++; } if (i < idx) // we don't have that many nics defined return -1; if (!it || !it->elem) return -1; netdev = it->elem; if (!p1) { lxc_remove_nic(it); } else if (strcmp(p1, ".ipv4") == 0) { struct lxc_list *it2,*next; lxc_list_for_each_safe(it2, &netdev->ipv4, next) { lxc_list_del(it2); free(it2->elem); free(it2); } } else if (strcmp(p1, ".ipv6") == 0) { struct lxc_list *it2,*next; lxc_list_for_each_safe(it2, &netdev->ipv6, next) { lxc_list_del(it2); free(it2->elem); free(it2); } } else return -1; return 0; } int lxc_clear_config_network(struct lxc_conf *c) { struct lxc_list *it,*next; lxc_list_for_each_safe(it, &c->network, next) { lxc_remove_nic(it); } return 0; } int lxc_clear_config_caps(struct lxc_conf *c) { struct lxc_list *it,*next; lxc_list_for_each_safe(it, &c->caps, next) { lxc_list_del(it); free(it->elem); free(it); } return 0; } static int lxc_free_idmap(struct lxc_list *id_map) { struct lxc_list *it, *next; lxc_list_for_each_safe(it, id_map, next) { lxc_list_del(it); free(it->elem); free(it); } return 0; } int lxc_clear_idmaps(struct lxc_conf *c) { return lxc_free_idmap(&c->id_map); } int lxc_clear_config_keepcaps(struct lxc_conf *c) { struct lxc_list *it,*next; lxc_list_for_each_safe(it, &c->keepcaps, next) { lxc_list_del(it); free(it->elem); free(it); } return 0; } int lxc_clear_cgroups(struct lxc_conf *c, const char *key) { struct lxc_list *it,*next; bool all = false; const char *k = key + 11; if (strcmp(key, "lxc.cgroup") == 0) all = true; lxc_list_for_each_safe(it, &c->cgroup, next) { struct lxc_cgroup *cg = it->elem; if (!all && strcmp(cg->subsystem, k) != 0) continue; lxc_list_del(it); free(cg->subsystem); free(cg->value); free(cg); free(it); } return 0; } int lxc_clear_groups(struct lxc_conf *c) { struct lxc_list *it,*next; lxc_list_for_each_safe(it, &c->groups, next) { lxc_list_del(it); free(it->elem); free(it); } return 0; } int lxc_clear_environment(struct lxc_conf *c) { struct lxc_list *it,*next; lxc_list_for_each_safe(it, &c->environment, next) { lxc_list_del(it); free(it->elem); free(it); } return 0; } int lxc_clear_mount_entries(struct lxc_conf *c) { struct lxc_list *it,*next; lxc_list_for_each_safe(it, &c->mount_list, next) { lxc_list_del(it); free(it->elem); free(it); } return 0; } int lxc_clear_automounts(struct lxc_conf *c) { c->auto_mounts = 0; return 0; } int lxc_clear_hooks(struct lxc_conf *c, const char *key) { struct lxc_list *it,*next; bool all = false, done = false; const char *k = key + 9; int i; if (strcmp(key, "lxc.hook") == 0) all = true; for (i=0; i<NUM_LXC_HOOKS; i++) { if (all || strcmp(k, lxchook_names[i]) == 0) { lxc_list_for_each_safe(it, &c->hooks[i], next) { lxc_list_del(it); free(it->elem); free(it); } done = true; } } if (!done) { ERROR("Invalid hook key: %s", key); return -1; } return 0; } static void lxc_clear_saved_nics(struct lxc_conf *conf) { int i; if (!conf->saved_nics) return; for (i=0; i < conf->num_savednics; i++) free(conf->saved_nics[i].orig_name); free(conf->saved_nics); } static inline void lxc_clear_aliens(struct lxc_conf *conf) { struct lxc_list *it,*next; lxc_list_for_each_safe(it, &conf->aliens, next) { lxc_list_del(it); free(it->elem); free(it); } } static inline void lxc_clear_includes(struct lxc_conf *conf) { struct lxc_list *it,*next; lxc_list_for_each_safe(it, &conf->includes, next) { lxc_list_del(it); free(it->elem); free(it); } } void lxc_conf_free(struct lxc_conf *conf) { if (!conf) return; if (current_config == conf) current_config = NULL; free(conf->console.log_path); free(conf->console.path); free(conf->rootfs.mount); free(conf->rootfs.options); free(conf->rootfs.path); free(conf->rootfs.pivot); free(conf->logfile); if (conf->logfd != -1) close(conf->logfd); free(conf->utsname); free(conf->ttydir); free(conf->fstab); free(conf->rcfile); free(conf->init_cmd); free(conf->unexpanded_config); free(conf->pty_names); lxc_clear_config_network(conf); free(conf->lsm_aa_profile); free(conf->lsm_se_context); lxc_seccomp_free(conf); lxc_clear_config_caps(conf); lxc_clear_config_keepcaps(conf); lxc_clear_cgroups(conf, "lxc.cgroup"); lxc_clear_hooks(conf, "lxc.hook"); lxc_clear_mount_entries(conf); lxc_clear_saved_nics(conf); lxc_clear_idmaps(conf); lxc_clear_groups(conf); lxc_clear_includes(conf); lxc_clear_aliens(conf); lxc_clear_environment(conf); free(conf); } struct userns_fn_data { int (*fn)(void *); void *arg; int p[2]; }; static int run_userns_fn(void *data) { struct userns_fn_data *d = data; char c; // we're not sharing with the parent any more, if it was a thread close(d->p[1]); if (read(d->p[0], &c, 1) != 1) return -1; close(d->p[0]); return d->fn(d->arg); } /* * Add ID_TYPE_UID/ID_TYPE_GID entries to an existing lxc_conf, * if they are not already there. */ static struct lxc_list *idmap_add_id(struct lxc_conf *conf, uid_t uid, gid_t gid) { int hostuid_mapped = mapped_hostid(uid, conf, ID_TYPE_UID); int hostgid_mapped = mapped_hostid(gid, conf, ID_TYPE_GID); struct lxc_list *new = NULL, *tmp, *it, *next; struct id_map *entry; new = malloc(sizeof(*new)); if (!new) { ERROR("Out of memory building id map"); return NULL; } lxc_list_init(new); if (hostuid_mapped < 0) { hostuid_mapped = find_unmapped_nsuid(conf, ID_TYPE_UID); if (hostuid_mapped < 0) goto err; tmp = malloc(sizeof(*tmp)); if (!tmp) goto err; entry = malloc(sizeof(*entry)); if (!entry) { free(tmp); goto err; } tmp->elem = entry; entry->idtype = ID_TYPE_UID; entry->nsid = hostuid_mapped; entry->hostid = (unsigned long) uid; entry->range = 1; lxc_list_add_tail(new, tmp); } if (hostgid_mapped < 0) { hostgid_mapped = find_unmapped_nsuid(conf, ID_TYPE_GID); if (hostgid_mapped < 0) goto err; tmp = malloc(sizeof(*tmp)); if (!tmp) goto err; entry = malloc(sizeof(*entry)); if (!entry) { free(tmp); goto err; } tmp->elem = entry; entry->idtype = ID_TYPE_GID; entry->nsid = hostgid_mapped; entry->hostid = (unsigned long) gid; entry->range = 1; lxc_list_add_tail(new, tmp); } lxc_list_for_each_safe(it, &conf->id_map, next) { tmp = malloc(sizeof(*tmp)); if (!tmp) goto err; entry = malloc(sizeof(*entry)); if (!entry) { free(tmp); goto err; } memset(entry, 0, sizeof(*entry)); memcpy(entry, it->elem, sizeof(*entry)); tmp->elem = entry; lxc_list_add_tail(new, tmp); } return new; err: ERROR("Out of memory building a new uid/gid map"); if (new) lxc_free_idmap(new); free(new); return NULL; } /* * Run a function in a new user namespace. * The caller's euid/egid will be mapped in if it is not already. */ int userns_exec_1(struct lxc_conf *conf, int (*fn)(void *), void *data) { int ret, pid; struct userns_fn_data d; char c = '1'; int p[2]; struct lxc_list *idmap; ret = pipe(p); if (ret < 0) { SYSERROR("opening pipe"); return -1; } d.fn = fn; d.arg = data; d.p[0] = p[0]; d.p[1] = p[1]; pid = lxc_clone(run_userns_fn, &d, CLONE_NEWUSER); if (pid < 0) goto err; close(p[0]); p[0] = -1; if ((idmap = idmap_add_id(conf, geteuid(), getegid())) == NULL) { ERROR("Error adding self to container uid/gid map"); goto err; } ret = lxc_map_ids(idmap, pid); lxc_free_idmap(idmap); free(idmap); if (ret) { ERROR("Error setting up child mappings"); goto err; } // kick the child if (write(p[1], &c, 1) != 1) { SYSERROR("writing to pipe to child"); goto err; } ret = wait_for_pid(pid); close(p[1]); return ret; err: if (p[0] != -1) close(p[0]); close(p[1]); return -1; } /* not thread-safe, do not use from api without first forking */ static char* getuname(void) { struct passwd *result; result = getpwuid(geteuid()); if (!result) return NULL; return strdup(result->pw_name); } /* not thread-safe, do not use from api without first forking */ static char *getgname(void) { struct group *result; result = getgrgid(getegid()); if (!result) return NULL; return strdup(result->gr_name); } /* not thread-safe, do not use from api without first forking */ void suggest_default_idmap(void) { FILE *f; unsigned int uid = 0, urange = 0, gid = 0, grange = 0; char *line = NULL; char *uname, *gname; size_t len = 0; if (!(uname = getuname())) return; if (!(gname = getgname())) { free(uname); return; } f = fopen(subuidfile, "r"); if (!f) { ERROR("Your system is not configured with subuids"); free(gname); free(uname); return; } while (getline(&line, &len, f) != -1) { char *p = strchr(line, ':'), *p2; if (*line == '#') continue; if (!p) continue; *p = '\0'; p++; if (strcmp(line, uname)) continue; p2 = strchr(p, ':'); if (!p2) continue; *p2 = '\0'; p2++; if (!*p2) continue; uid = atoi(p); urange = atoi(p2); } fclose(f); f = fopen(subuidfile, "r"); if (!f) { ERROR("Your system is not configured with subgids"); free(gname); free(uname); return; } while (getline(&line, &len, f) != -1) { char *p = strchr(line, ':'), *p2; if (*line == '#') continue; if (!p) continue; *p = '\0'; p++; if (strcmp(line, uname)) continue; p2 = strchr(p, ':'); if (!p2) continue; *p2 = '\0'; p2++; if (!*p2) continue; gid = atoi(p); grange = atoi(p2); } fclose(f); free(line); if (!urange || !grange) { ERROR("You do not have subuids or subgids allocated"); ERROR("Unprivileged containers require subuids and subgids"); return; } ERROR("You must either run as root, or define uid mappings"); ERROR("To pass uid mappings to lxc-create, you could create"); ERROR("~/.config/lxc/default.conf:"); ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG); ERROR("lxc.id_map = u 0 %u %u", uid, urange); ERROR("lxc.id_map = g 0 %u %u", gid, grange); free(gname); free(uname); } static void free_cgroup_settings(struct lxc_list *result) { struct lxc_list *iterator, *next; lxc_list_for_each_safe(iterator, result, next) { lxc_list_del(iterator); free(iterator); } free(result); } /* * Return the list of cgroup_settings sorted according to the following rules * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes */ struct lxc_list *sort_cgroup_settings(struct lxc_list* cgroup_settings) { struct lxc_list *result; struct lxc_list *memsw_limit = NULL; struct lxc_list *it = NULL; struct lxc_cgroup *cg = NULL; struct lxc_list *item = NULL; result = malloc(sizeof(*result)); if (!result) { ERROR("failed to allocate memory to sort cgroup settings"); return NULL; } lxc_list_init(result); /*Iterate over the cgroup settings and copy them to the output list*/ lxc_list_for_each(it, cgroup_settings) { item = malloc(sizeof(*item)); if (!item) { ERROR("failed to allocate memory to sort cgroup settings"); free_cgroup_settings(result); return NULL; } item->elem = it->elem; cg = it->elem; if (strcmp(cg->subsystem, "memory.memsw.limit_in_bytes") == 0) { /* Store the memsw_limit location */ memsw_limit = item; } else if (strcmp(cg->subsystem, "memory.limit_in_bytes") == 0 && memsw_limit != NULL) { /* lxc.cgroup.memory.memsw.limit_in_bytes is found before * lxc.cgroup.memory.limit_in_bytes, swap these two items */ item->elem = memsw_limit->elem; memsw_limit->elem = it->elem; } lxc_list_add_tail(result, item); } return result; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_1471_3
crossvul-cpp_data_bad_436_5
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Configuration file parser/reader. Place into the dynamic * data structure representation the conf file representing * the loadbalanced server pool. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <unistd.h> #include <string.h> #include <stdint.h> #include <net/if_arp.h> #include <sys/types.h> #include <sys/stat.h> //#include <unistd.h> #include <stdio.h> #include <ctype.h> #include <net/if.h> #include "vrrp_parser.h" #include "logger.h" #include "parser.h" #include "bitops.h" #include "utils.h" #include "main.h" #include "global_data.h" #include "global_parser.h" #include "vrrp_data.h" #include "vrrp_ipaddress.h" #include "vrrp_sync.h" #include "vrrp_track.h" #ifdef _HAVE_VRRP_VMAC_ #include "vrrp_vmac.h" #endif #include "vrrp_static_track.h" #ifdef _WITH_LVS_ #include "check_parser.h" #endif #ifdef _WITH_BFD_ #include "bfd_parser.h" #endif /* Used for initialising track files */ static enum { TRACK_FILE_NO_INIT, TRACK_FILE_CREATE, TRACK_FILE_INIT, } track_file_init; static int track_file_init_value; static bool script_user_set; static bool remove_script; /* track groups for static items */ static void static_track_group_handler(vector_t *strvec) { element e; static_track_group_t *tg; char* gname; if (!strvec) return; if (vector_count(strvec) != 2) { report_config_error(CONFIG_GENERAL_ERROR, "track_group must have a name - skipping"); skip_block(true); return; } gname = strvec_slot(strvec, 1); /* check group doesn't already exist */ LIST_FOREACH(vrrp_data->static_track_groups, tg, e) { if (!strcmp(gname,tg->gname)) { report_config_error(CONFIG_GENERAL_ERROR, "track_group %s already defined", gname); skip_block(true); return; } } alloc_static_track_group(gname); } static void static_track_group_group_handler(vector_t *strvec) { static_track_group_t *tgroup = LIST_TAIL_DATA(vrrp_data->static_track_groups); if (tgroup->iname) { report_config_error(CONFIG_GENERAL_ERROR, "Group list already specified for sync group %s", tgroup->gname); skip_block(true); return; } tgroup->iname = read_value_block(strvec); if (!tgroup->iname) report_config_error(CONFIG_GENERAL_ERROR, "Warning - track group %s has empty group block", tgroup->gname); } /* Static addresses handler */ static void static_addresses_handler(vector_t *strvec) { global_data->have_vrrp_config = true; if (!strvec) return; alloc_value_block(alloc_saddress, vector_slot(strvec, 0)); } #ifdef _HAVE_FIB_ROUTING_ /* Static routes handler */ static void static_routes_handler(vector_t *strvec) { global_data->have_vrrp_config = true; if (!strvec) return; alloc_value_block(alloc_sroute, vector_slot(strvec, 0)); } /* Static rules handler */ static void static_rules_handler(vector_t *strvec) { global_data->have_vrrp_config = true; if (!strvec) return; alloc_value_block(alloc_srule, vector_slot(strvec, 0)); } #endif /* VRRP handlers */ static void vrrp_sync_group_handler(vector_t *strvec) { list l; element e; vrrp_sgroup_t *sg; char* gname; if (!strvec) return; if (vector_count(strvec) != 2) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_sync_group must have a name - skipping"); skip_block(true); return; } gname = strvec_slot(strvec, 1); /* check group doesn't already exist */ if (!LIST_ISEMPTY(vrrp_data->vrrp_sync_group)) { l = vrrp_data->vrrp_sync_group; for (e = LIST_HEAD(l); e; ELEMENT_NEXT(e)) { sg = ELEMENT_DATA(e); if (!strcmp(gname,sg->gname)) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp sync group %s already defined", gname); skip_block(true); return; } } } alloc_vrrp_sync_group(gname); } static void vrrp_group_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->iname) { report_config_error(CONFIG_GENERAL_ERROR, "Group list already specified for sync group %s", vgroup->gname); skip_block(true); return; } vgroup->iname = read_value_block(strvec); if (!vgroup->iname) report_config_error(CONFIG_GENERAL_ERROR, "Warning - sync group %s has empty group block", vgroup->gname); } static void vrrp_group_track_if_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_group_track_if, vector_slot(strvec, 0)); } static void vrrp_group_track_scr_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_group_track_script, vector_slot(strvec, 0)); } static void vrrp_group_track_file_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_group_track_file, vector_slot(strvec, 0)); } #if defined _WITH_BFD_ static void vrrp_group_track_bfd_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_group_track_bfd, vector_slot(strvec, 0)); } #endif static inline notify_script_t* set_vrrp_notify_script(__attribute__((unused)) vector_t *strvec, int extra_params) { return notify_script_init(extra_params, "notify"); } static void vrrp_gnotify_backup_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->script_backup) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp group %s: notify_backup script already specified - ignoring %s", vgroup->gname, FMT_STR_VSLOT(strvec,1)); return; } vgroup->script_backup = set_vrrp_notify_script(strvec, 0); vgroup->notify_exec = true; } static void vrrp_gnotify_master_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->script_master) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp group %s: notify_master script already specified - ignoring %s", vgroup->gname, FMT_STR_VSLOT(strvec,1)); return; } vgroup->script_master = set_vrrp_notify_script(strvec, 0); vgroup->notify_exec = true; } static void vrrp_gnotify_fault_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->script_fault) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp group %s: notify_fault script already specified - ignoring %s", vgroup->gname, FMT_STR_VSLOT(strvec,1)); return; } vgroup->script_fault = set_vrrp_notify_script(strvec, 0); vgroup->notify_exec = true; } static void vrrp_gnotify_stop_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->script_stop) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp group %s: notify_stop script already specified - ignoring %s", vgroup->gname, FMT_STR_VSLOT(strvec,1)); return; } vgroup->script_stop = set_vrrp_notify_script(strvec, 0); vgroup->notify_exec = true; } static void vrrp_gnotify_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->script) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp group %s: notify script already specified - ignoring %s", vgroup->gname, FMT_STR_VSLOT(strvec,1)); return; } vgroup->script = set_vrrp_notify_script(strvec, 4); vgroup->notify_exec = true; } static void vrrp_gsmtp_handler(__attribute__((unused)) vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec, 1)); if (res == -1) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_group smtp_alert parameter %s", FMT_STR_VSLOT(strvec, 1)); return; } } vgroup->smtp_alert = res; } static void vrrp_gglobal_tracking_handler(__attribute__((unused)) vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); report_config_error(CONFIG_GENERAL_ERROR, "(%s) global_tracking is deprecated. Use track_interface/script/file on the sync group", vgroup->gname); vgroup->sgroup_tracking_weight = true; } static void vrrp_sg_tracking_weight_handler(__attribute__((unused)) vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); vgroup->sgroup_tracking_weight = true; } static void vrrp_handler(vector_t *strvec) { list l; element e; vrrp_t *vrrp; char *iname; global_data->have_vrrp_config = true; if (!strvec) return; if (vector_count(strvec) != 2) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp_instance must have a name"); skip_block(true); return; } iname = strvec_slot(strvec,1); /* Make sure the vrrp instance doesn't already exist */ if (!LIST_ISEMPTY(vrrp_data->vrrp)) { l = vrrp_data->vrrp; for (e = LIST_HEAD(l); e; ELEMENT_NEXT(e)) { vrrp = ELEMENT_DATA(e); if (!strcmp(iname,vrrp->iname)) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp instance %s already defined", iname ); skip_block(true); return; } } } alloc_vrrp(iname); } #ifdef _HAVE_VRRP_VMAC_ static void vrrp_vmac_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); interface_t *ifp; __set_bit(VRRP_VMAC_BIT, &vrrp->vmac_flags); if (vector_size(strvec) >= 2) { if (strlen(strvec_slot(strvec, 1)) >= IFNAMSIZ) { report_config_error(CONFIG_GENERAL_ERROR, "VMAC interface name '%s' too long - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } strcpy(vrrp->vmac_ifname, strvec_slot(strvec, 1)); /* Check if the interface exists and is a macvlan we can use */ if ((ifp = if_get_by_ifname(vrrp->vmac_ifname, IF_NO_CREATE)) && ifp->vmac_type != MACVLAN_MODE_PRIVATE) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) interface %s already exists and is not a private macvlan; ignoring vmac if_name", vrrp->iname, vrrp->vmac_ifname); vrrp->vmac_ifname[0] = '\0'; } } } static void vrrp_vmac_xmit_base_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); __set_bit(VRRP_VMAC_XMITBASE_BIT, &vrrp->vmac_flags); } #endif static void vrrp_unicast_peer_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_unicast_peer, vector_slot(strvec, 0)); } #ifdef _WITH_UNICAST_CHKSUM_COMPAT_ static void vrrp_unicast_chksum_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vector_size(strvec) >= 2) { if (!strcmp(strvec_slot(strvec, 1), "never")) vrrp->unicast_chksum_compat = CHKSUM_COMPATIBILITY_NEVER; else report_config_error(CONFIG_GENERAL_ERROR, "(%s) Unknown old_unicast_chksum mode %s - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); } else vrrp->unicast_chksum_compat = CHKSUM_COMPATIBILITY_CONFIG; } #endif static void vrrp_native_ipv6_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->family == AF_INET) { report_config_error(CONFIG_GENERAL_ERROR,"(%s) Cannot specify native_ipv6 with IPv4 addresses", vrrp->iname); return; } vrrp->family = AF_INET6; vrrp->version = VRRP_VERSION_3; } static void vrrp_state_handler(vector_t *strvec) { char *str = strvec_slot(strvec, 1); vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (!strcmp(str, "MASTER")) vrrp->wantstate = VRRP_STATE_MAST; else if (!strcmp(str, "BACKUP")) { if (vrrp->wantstate == VRRP_STATE_MAST) report_config_error(CONFIG_GENERAL_ERROR, "(%s) state previously set as MASTER - ignoring BACKUP", vrrp->iname); else vrrp->wantstate = VRRP_STATE_BACK; } else { report_config_error(CONFIG_GENERAL_ERROR,"(%s) unknown state '%s', defaulting to BACKUP", vrrp->iname, str); vrrp->wantstate = VRRP_STATE_BACK; } } static void vrrp_int_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); char *name = strvec_slot(strvec, 1); if (strlen(name) >= IFNAMSIZ) { report_config_error(CONFIG_GENERAL_ERROR, "Interface name '%s' too long - ignoring", name); return; } vrrp->ifp = if_get_by_ifname(name, IF_CREATE_IF_DYNAMIC); if (!vrrp->ifp) report_config_error(CONFIG_GENERAL_ERROR, "WARNING - interface %s for vrrp_instance %s doesn't exist", name, vrrp->iname); else if (vrrp->ifp->hw_type == ARPHRD_LOOPBACK) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) cannot use a loopback interface (%s) for vrrp - ignoring", vrrp->iname, vrrp->ifp->ifname); vrrp->ifp = NULL; } #ifdef _HAVE_VRRP_VMAC_ vrrp->configured_ifp = vrrp->ifp; #endif } static void vrrp_linkbeat_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->linkbeat_use_polling = true; } static void vrrp_track_if_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_track_if, vector_slot(strvec, 0)); } static void vrrp_track_scr_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_track_script, vector_slot(strvec, 0)); } static void vrrp_track_file_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_track_file, vector_slot(strvec, 0)); } static void vrrp_dont_track_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->dont_track_primary = true; } #ifdef _WITH_BFD_ static void vrrp_track_bfd_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_track_bfd, vector_slot(strvec, 0)); } #endif static void vrrp_srcip_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); struct sockaddr_storage *saddr = &vrrp->saddr; if (inet_stosockaddr(strvec_slot(strvec, 1), NULL, saddr)) { report_config_error(CONFIG_GENERAL_ERROR, "Configuration error: VRRP instance[%s] malformed" " src address[%s]. Skipping..." , vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } vrrp->saddr_from_config = true; if (vrrp->family == AF_UNSPEC) vrrp->family = saddr->ss_family; else if (saddr->ss_family != vrrp->family) { report_config_error(CONFIG_GENERAL_ERROR, "Configuration error: VRRP instance[%s] and src address" "[%s] MUST be of the same family !!! Skipping..." , vrrp->iname, FMT_STR_VSLOT(strvec, 1)); saddr->ss_family = AF_UNSPEC; vrrp->saddr_from_config = false; } } static void vrrp_track_srcip_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->track_saddr = true; } static void vrrp_vrid_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned vrid; if (!read_unsigned_strvec(strvec, 1, &vrid, 1, 255, false)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): VRID '%s' not valid - must be between 1 & 255", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } vrrp->vrid = (uint8_t)vrid; } static void vrrp_prio_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned base_priority; if (!read_unsigned_strvec(strvec, 1, &base_priority, 1, VRRP_PRIO_OWNER, false)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) Priority not valid! must be between 1 & %d. Using default %d", vrrp->iname, VRRP_PRIO_OWNER, VRRP_PRIO_DFL); vrrp->base_priority = VRRP_PRIO_DFL; } else vrrp->base_priority = (uint8_t)base_priority; } static void vrrp_adv_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); double adver_int; bool res; res = read_double_strvec(strvec, 1, &adver_int, 0.01, 255.0, true); /* Simple check - just positive */ if (!res || adver_int <= 0) report_config_error(CONFIG_GENERAL_ERROR, "(%s) Advert interval (%s) not valid! Must be > 0 - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); else vrrp->adver_int = (unsigned)(adver_int * TIMER_HZ); } static void vrrp_debug_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned debug; if (!read_unsigned_strvec(strvec, 1, &debug, 0, 4, true)) report_config_error(CONFIG_GENERAL_ERROR, "(%s) Debug value '%s' not valid; must be between 0-4", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); else vrrp->debug = debug; } static void vrrp_skip_check_adv_addr_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); int res; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec, 1)); if (res >= 0) vrrp->skip_check_adv_addr = (bool)res; else report_config_error(CONFIG_GENERAL_ERROR, "(%s) invalid skip_check_adv_addr %s specified", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); } else { /* Defaults to true */ vrrp->skip_check_adv_addr = true; } } static void vrrp_strict_mode_handler(vector_t *strvec) { int res; vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec, 1)); if (res >= 0) vrrp->strict_mode = (bool)res; else report_config_error(CONFIG_GENERAL_ERROR, "(%s) invalid strict_mode %s specified", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); } else { /* Defaults to true */ vrrp->strict_mode = true; } } static void vrrp_nopreempt_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->nopreempt = 1; } static void /* backwards compatibility */ vrrp_preempt_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->nopreempt = 0; } static void vrrp_preempt_delay_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); double preempt_delay; if (!read_double_strvec(strvec, 1, &preempt_delay, 0, TIMER_MAX_SEC, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) Preempt_delay not valid! must be between 0-%d", vrrp->iname, TIMER_MAX_SEC); vrrp->preempt_delay = 0; } else vrrp->preempt_delay = (unsigned long)(preempt_delay * TIMER_HZ); } static void vrrp_notify_backup_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->script_backup) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) notify_backup script already specified - ignoring %s", vrrp->iname, FMT_STR_VSLOT(strvec,1)); return; } vrrp->script_backup = set_vrrp_notify_script(strvec, 0); vrrp->notify_exec = true; } static void vrrp_notify_master_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->script_master) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) notify_master script already specified - ignoring %s", vrrp->iname, FMT_STR_VSLOT(strvec,1)); return; } vrrp->script_master = set_vrrp_notify_script(strvec, 0); vrrp->notify_exec = true; } static void vrrp_notify_fault_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->script_fault) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) notify_fault script already specified - ignoring %s", vrrp->iname, FMT_STR_VSLOT(strvec,1)); return; } vrrp->script_fault = set_vrrp_notify_script(strvec, 0); vrrp->notify_exec = true; } static void vrrp_notify_stop_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->script_stop) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) notify_stop script already specified - ignoring %s", vrrp->iname, FMT_STR_VSLOT(strvec,1)); return; } vrrp->script_stop = set_vrrp_notify_script(strvec, 0); vrrp->notify_exec = true; } static void vrrp_notify_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->script) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) notify script already specified - ignoring %s", vrrp->iname, FMT_STR_VSLOT(strvec,1)); return; } vrrp->script = set_vrrp_notify_script(strvec, 4); vrrp->notify_exec = true; } static void vrrp_notify_master_rx_lower_pri(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->script_master_rx_lower_pri) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) notify_master_rx_lower_pri script already specified - ignoring %s", vrrp->iname, FMT_STR_VSLOT(strvec,1)); return; } vrrp->script_master_rx_lower_pri = set_vrrp_notify_script(strvec, 0); vrrp->notify_exec = true; } static void vrrp_smtp_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); int res = true; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec, 1)); if (res == -1) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid vrrp_instance smtp_alert parameter %s", FMT_STR_VSLOT(strvec, 1)); return; } } vrrp->smtp_alert = res; } #ifdef _WITH_LVS_ static void vrrp_lvs_syncd_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); report_config_error(CONFIG_GENERAL_ERROR, "(%s) Specifying lvs_sync_daemon_interface against a vrrp is deprecated.", vrrp->iname); /* Deprecated after v1.2.19 */ report_config_error(CONFIG_GENERAL_ERROR, " %*sPlease use global lvs_sync_daemon", (int)strlen(vrrp->iname) - 2, ""); if (global_data->lvs_syncd.ifname) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) lvs_sync_daemon_interface has already been specified as %s - ignoring", vrrp->iname, global_data->lvs_syncd.ifname); return; } global_data->lvs_syncd.ifname = set_value(strvec); global_data->lvs_syncd.vrrp = vrrp; } #endif static void vrrp_garp_delay_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned delay; if (!read_unsigned_strvec(strvec, 1, &delay, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): garp_master_delay '%s' invalid - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } vrrp->garp_delay = delay * TIMER_HZ; } static void vrrp_garp_refresh_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned refresh; if (!read_unsigned_strvec(strvec, 1, &refresh, 0, UINT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): Invalid garp_master_refresh '%s' - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); vrrp->garp_refresh.tv_sec = 0; } else vrrp->garp_refresh.tv_sec = refresh; vrrp->garp_refresh.tv_usec = 0; } static void vrrp_garp_rep_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned repeats; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &repeats, 0, UINT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): garp_master_repeat '%s' invalid - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } if (repeats == 0) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): garp_master_repeat must be greater than 0, setting to 1", vrrp->iname); repeats = 1; } vrrp->garp_rep = repeats; } static void vrrp_garp_refresh_rep_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned repeats; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &repeats, 0, UINT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): garp_master_refresh_repeat '%s' invalid - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } if (repeats == 0) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): garp_master_refresh_repeat must be greater than 0, setting to 1", vrrp->iname); repeats = 1; } vrrp->garp_refresh_rep = repeats; } static void vrrp_garp_lower_prio_delay_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned delay; if (!read_unsigned_strvec(strvec, 1, &delay, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): garp_lower_prio_delay '%s' invalid - ignoring", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } vrrp->garp_lower_prio_delay = delay * TIMER_HZ; } static void vrrp_garp_lower_prio_rep_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned garp_lower_prio_rep; if (!read_unsigned_strvec(strvec, 1, &garp_lower_prio_rep, 0, INT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): Invalid garp_lower_prio_repeat '%s'", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); return; } vrrp->garp_lower_prio_rep = garp_lower_prio_rep; } static void vrrp_lower_prio_no_advert_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); int res; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec, 1)); if (res >= 0) vrrp->lower_prio_no_advert = (unsigned)res; else report_config_error(CONFIG_GENERAL_ERROR, "(%s) invalid lower_prio_no_advert %s specified", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); } else { /* Defaults to true */ vrrp->lower_prio_no_advert = true; } } static void vrrp_higher_prio_send_advert_handler(vector_t *strvec) { int res; vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec, 1)); if (res >= 0) vrrp->higher_prio_send_advert = (unsigned)res; else report_config_error(CONFIG_GENERAL_ERROR, "(%s) invalid higher_prio_send_advert %s specified", vrrp->iname, FMT_STR_VSLOT(strvec, 1)); } else { /* Defaults to true */ vrrp->higher_prio_send_advert = true; } } static void kernel_rx_buf_size_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); unsigned rx_buf_size; if (vector_size(strvec) == 2 && read_unsigned_strvec(strvec, 1, &rx_buf_size, 0, UINT_MAX, false)) { vrrp->kernel_rx_buf_size = rx_buf_size; return; } report_config_error(CONFIG_GENERAL_ERROR, "(%s) invalid kernel_rx_buf_size specified", vrrp->iname); } #if defined _WITH_VRRP_AUTH_ static void vrrp_auth_type_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); char *str = strvec_slot(strvec, 1); if (!strcmp(str, "AH")) vrrp->auth_type = VRRP_AUTH_AH; else if (!strcmp(str, "PASS")) vrrp->auth_type = VRRP_AUTH_PASS; else report_config_error(CONFIG_GENERAL_ERROR, "(%s) unknown authentication type '%s'", vrrp->iname, str); } static void vrrp_auth_pass_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); char *str = strvec_slot(strvec, 1); size_t max_size = sizeof (vrrp->auth_data); size_t str_len = strlen(str); if (str_len > max_size) { str_len = max_size; report_config_error(CONFIG_GENERAL_ERROR, "Truncating auth_pass to %zu characters", max_size); } memset(vrrp->auth_data, 0, max_size); memcpy(vrrp->auth_data, str, str_len); } #endif static void vrrp_vip_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_vip, vector_slot(strvec, 0)); } static void vrrp_evip_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_evip, vector_slot(strvec, 0)); } static void vrrp_promote_secondaries_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->promote_secondaries = true; } #ifdef _HAVE_FIB_ROUTING_ static void vrrp_vroutes_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_vroute, vector_slot(strvec, 0)); } static void vrrp_vrules_handler(vector_t *strvec) { alloc_value_block(alloc_vrrp_vrule, vector_slot(strvec, 0)); } #endif static void vrrp_script_handler(vector_t *strvec) { if (!strvec) return; alloc_vrrp_script(strvec_slot(strvec, 1)); script_user_set = false; remove_script = false; } static void vrrp_vscript_script_handler(__attribute__((unused)) vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); vector_t *strvec_qe; /* We need to allow quoted and escaped strings for the script and parameters */ strvec_qe = alloc_strvec_quoted_escaped(NULL); set_script_params_array(strvec_qe, &vscript->script, 0); free_strvec(strvec_qe); } static void vrrp_vscript_interval_handler(vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); unsigned interval; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &interval, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): vrrp script interval '%s' must be between 1 and %u - ignoring", vscript->sname, FMT_STR_VSLOT(strvec, 1), UINT_MAX / TIMER_HZ); return; } if (interval == 0) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): vrrp script interval must be greater than 0, setting to 1", vscript->sname); interval = 1; } vscript->interval = interval * TIMER_HZ; } static void vrrp_vscript_timeout_handler(vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); unsigned timeout; /* The min value should be 1, but allow 0 to maintain backward compatibility * with pre v2.0.7 */ if (!read_unsigned_strvec(strvec, 1, &timeout, 0, UINT_MAX / TIMER_HZ, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): vrrp script timeout '%s' invalid - ignoring", vscript->sname, FMT_STR_VSLOT(strvec, 1)); return; } if (timeout == 0) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): vrrp script timeout must be greater than 0, setting to 1", vscript->sname); timeout = 1; } vscript->timeout = timeout * TIMER_HZ; } static void vrrp_vscript_weight_handler(vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); int weight; if (!read_int_strvec(strvec, 1, &weight, -253, 253, true)) report_config_error(CONFIG_GENERAL_ERROR, "vrrp_script %s weight %s must be in [-253, 253]", vscript->sname, FMT_STR_VSLOT(strvec, 1)); vscript->weight = weight; } static void vrrp_vscript_rise_handler(vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); unsigned rise; if (!read_unsigned_strvec(strvec, 1, &rise, 1, INT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): vrrp script rise value '%s' invalid, defaulting to 1", vscript->sname, FMT_STR_VSLOT(strvec, 1)); vscript->rise = 1; } else vscript->rise = rise; } static void vrrp_vscript_fall_handler(vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); unsigned fall; if (!read_unsigned_strvec(strvec, 1, &fall, 1, INT_MAX, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): vrrp script fall value '%s' invalid, defaulting to 1", vscript->sname, FMT_STR_VSLOT(strvec, 1)); vscript->fall = 1; } else vscript->fall = fall; } static void vrrp_vscript_user_handler(vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); if (set_script_uid_gid(strvec, 1, &vscript->script.uid, &vscript->script.gid)) { report_config_error(CONFIG_GENERAL_ERROR, "Unable to set uid/gid for script %s", cmd_str(&vscript->script)); remove_script = true; } else { remove_script = false; script_user_set = true; } } static void vrrp_vscript_end_handler(void) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); if (!vscript->script.args || !vscript->script.args[0]) { report_config_error(CONFIG_GENERAL_ERROR, "No script set for vrrp_script %s - removing", vscript->sname); remove_script = true; } else if (!remove_script) { if (script_user_set) return; if (set_default_script_user(NULL, NULL)) { report_config_error(CONFIG_GENERAL_ERROR, "Unable to set default user for vrrp script %s - removing", vscript->sname); remove_script = true; } } if (remove_script) { free_list_element(vrrp_data->vrrp_script, vrrp_data->vrrp_script->tail); return; } vscript->script.uid = default_script_uid; vscript->script.gid = default_script_gid; } static void vrrp_tfile_handler(vector_t *strvec) { if (!strvec) return; alloc_vrrp_file(strvec_slot(strvec, 1)); track_file_init = TRACK_FILE_NO_INIT; } static void vrrp_tfile_file_handler(vector_t *strvec) { vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files); if (tfile->file_path) { report_config_error(CONFIG_GENERAL_ERROR, "File already set for track file %s - ignoring %s", tfile->fname, FMT_STR_VSLOT(strvec, 1)); return; } tfile->file_path = set_value(strvec); } static void vrrp_tfile_weight_handler(vector_t *strvec) { int weight; vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files); if (vector_size(strvec) < 2) { report_config_error(CONFIG_GENERAL_ERROR, "No weight specified for track file %s - ignoring", tfile->fname); return; } if (tfile->weight != 1) { report_config_error(CONFIG_GENERAL_ERROR, "Weight already set for track file %s - ignoring %s", tfile->fname, FMT_STR_VSLOT(strvec, 1)); return; } if (!read_int_strvec(strvec, 1, &weight, -254, 254, true)) { report_config_error(CONFIG_GENERAL_ERROR, "Weight (%s) for vrrp_track_file %s must be between " "[-254..254] inclusive. Ignoring...", FMT_STR_VSLOT(strvec, 1), tfile->fname); weight = 1; } tfile->weight = weight; } static void vrrp_tfile_init_handler(vector_t *strvec) { unsigned i; char *word; vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files); int value; track_file_init = TRACK_FILE_CREATE; track_file_init_value = 0; for (i = 1; i < vector_size(strvec); i++) { word = strvec_slot(strvec, i); word += strspn(word, WHITE_SPACE); if (isdigit(word[0]) || word[0] == '-') { if (!read_int_strvec(strvec, i, &value, INT_MIN, INT_MAX, false)) { /* It is not a valid integer */ report_config_error(CONFIG_GENERAL_ERROR, "Track file %s init value %s is invalid", tfile->fname, word); value = 0; } else if (value < -254 || value > 254) report_config_error(CONFIG_GENERAL_ERROR, "Track file %s init value %d is outside sensible range [%d, %d]", tfile->fname, value, -254, 254); track_file_init_value = value; } else if (!strcmp(word, "overwrite")) track_file_init = TRACK_FILE_INIT; else report_config_error(CONFIG_GENERAL_ERROR, "Unknown track file init option %s", word); } } static void vrrp_tfile_end_handler(void) { vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files); struct stat statb; FILE *tf; int ret; if (!tfile->file_path) { report_config_error(CONFIG_GENERAL_ERROR, "No file set for track_file %s - removing", tfile->fname); free_list_element(vrrp_data->vrrp_track_files, vrrp_data->vrrp_track_files->tail); return; } if (track_file_init == TRACK_FILE_NO_INIT) return; ret = stat(tfile->file_path, &statb); if (!ret) { if (track_file_init == TRACK_FILE_CREATE) { /* The file exists */ return; } if ((statb.st_mode & S_IFMT) != S_IFREG) { /* It is not a regular file */ report_config_error(CONFIG_GENERAL_ERROR, "Cannot initialise track file %s - it is not a regular file", tfile->fname); return; } /* Don't overwrite a file on reload */ if (reload) return; } if (!__test_bit(CONFIG_TEST_BIT, &debug)) { /* Write the value to the file */ if ((tf = fopen(tfile->file_path, "w"))) { fprintf(tf, "%d\n", track_file_init_value); fclose(tf); } else report_config_error(CONFIG_GENERAL_ERROR, "Unable to initialise track file %s", tfile->fname); } } static void vrrp_vscript_init_fail_handler(__attribute__((unused)) vector_t *strvec) { vrrp_script_t *vscript = LIST_TAIL_DATA(vrrp_data->vrrp_script); vscript->init_state = SCRIPT_INIT_STATE_FAILED; } static void vrrp_version_handler(vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); int version; if (!read_int_strvec(strvec, 1, &version, 2, 3, true)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s): Version must be either 2 or 3", vrrp->iname); return; } if ((vrrp->version && vrrp->version != version) || (version == VRRP_VERSION_2 && vrrp->family == AF_INET6)) { report_config_error(CONFIG_GENERAL_ERROR, "(%s) vrrp_version %d conflicts with configured or deduced version %d; ignoring.", vrrp->iname, version, vrrp->version); return; } vrrp->version = version; } static void vrrp_accept_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->accept = true; } static void vrrp_no_accept_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); vrrp->accept = false; } static void garp_group_handler(vector_t *strvec) { if (!strvec) return; alloc_garp_delay(); } static void garp_group_garp_interval_handler(vector_t *strvec) { garp_delay_t *delay = LIST_TAIL_DATA(garp_delay); double val; if (!read_double_strvec(strvec, 1, &val, 0, INT_MAX / 1000000, true)) { report_config_error(CONFIG_GENERAL_ERROR, "garp_group garp_interval '%s' invalid", FMT_STR_VSLOT(strvec, 1)); return; } delay->garp_interval.tv_sec = (time_t)val; delay->garp_interval.tv_usec = (suseconds_t)((val - delay->garp_interval.tv_sec) * 1000000); delay->have_garp_interval = true; if (delay->garp_interval.tv_sec >= 1) log_message(LOG_INFO, "The garp_interval is very large - %s seconds", FMT_STR_VSLOT(strvec,1)); } static void garp_group_gna_interval_handler(vector_t *strvec) { garp_delay_t *delay = LIST_TAIL_DATA(garp_delay); double val; if (!read_double_strvec(strvec, 1, &val, 0, INT_MAX / 1000000, true)) { report_config_error(CONFIG_GENERAL_ERROR, "garp_group gna_interval '%s' invalid", FMT_STR_VSLOT(strvec, 1)); return; } delay->gna_interval.tv_sec = (time_t)val; delay->gna_interval.tv_usec = (suseconds_t)((val - delay->gna_interval.tv_sec) * 1000000); delay->have_gna_interval = true; if (delay->gna_interval.tv_sec >= 1) log_message(LOG_INFO, "The gna_interval is very large - %s seconds", FMT_STR_VSLOT(strvec,1)); } static void garp_group_interface_handler(vector_t *strvec) { interface_t *ifp = if_get_by_ifname(strvec_slot(strvec, 1), IF_CREATE_IF_DYNAMIC); if (!ifp) { report_config_error(CONFIG_GENERAL_ERROR, "WARNING - interface %s specified for garp_group doesn't exist", FMT_STR_VSLOT(strvec, 1)); return; } if (ifp->garp_delay) { report_config_error(CONFIG_GENERAL_ERROR, "garp_group already specified for %s - ignoring", FMT_STR_VSLOT(strvec, 1)); return; } #ifdef _HAVE_VRRP_VMAC_ /* We cannot have a group on a vmac interface */ if (ifp->vmac_type) { report_config_error(CONFIG_GENERAL_ERROR, "Cannot specify garp_delay on a vmac (%s) - ignoring", ifp->ifname); return; } #endif ifp->garp_delay = LIST_TAIL_DATA(garp_delay); } static void garp_group_interfaces_handler(vector_t *strvec) { garp_delay_t *delay = LIST_TAIL_DATA(garp_delay); interface_t *ifp; vector_t *interface_vec = read_value_block(strvec); size_t i; garp_delay_t *gd; element e; /* Handle the interfaces block being empty */ if (!interface_vec) { report_config_error(CONFIG_GENERAL_ERROR, "Warning - empty garp_group interfaces block"); return; } /* First set the next aggregation group number */ delay->aggregation_group = 1; for (e = LIST_HEAD(garp_delay); e; ELEMENT_NEXT(e)) { gd = ELEMENT_DATA(e); if (gd->aggregation_group && gd != delay) delay->aggregation_group++; } for (i = 0; i < vector_size(interface_vec); i++) { ifp = if_get_by_ifname(vector_slot(interface_vec, i), IF_CREATE_IF_DYNAMIC); if (!ifp) { if (global_data->dynamic_interfaces) log_message(LOG_INFO, "WARNING - interface %s specified for garp_group doesn't exist", FMT_STR_VSLOT(strvec, i)); else report_config_error(CONFIG_GENERAL_ERROR, "WARNING - interface %s specified for garp_group doesn't exist", FMT_STR_VSLOT(strvec, i)); continue; } if (ifp->garp_delay) { report_config_error(CONFIG_GENERAL_ERROR, "garp_group already specified for %s - ignoring", FMT_STR_VSLOT(strvec, 1)); continue; } #ifdef _HAVE_VRRP_VMAC_ if (ifp->vmac_type) { report_config_error(CONFIG_GENERAL_ERROR, "Cannot specify garp_delay on a vmac (%s) - ignoring", ifp->ifname); continue; } #endif ifp->garp_delay = delay; } free_strvec(interface_vec); } static void garp_group_end_handler(void) { garp_delay_t *delay = LIST_TAIL_DATA(garp_delay); element e, next; interface_t *ifp; if (!delay->have_garp_interval && !delay->have_gna_interval) { report_config_error(CONFIG_GENERAL_ERROR, "garp group %d does not have any delay set - removing", delay->aggregation_group); /* Remove the garp_delay from any interfaces that are using it */ LIST_FOREACH_NEXT(get_if_list(), ifp, e, next) { if (ifp->garp_delay == delay) ifp->garp_delay = NULL; } free_list_element(garp_delay, garp_delay->tail); } } void init_vrrp_keywords(bool active) { /* Static addresses/routes/rules */ install_keyword_root("track_group", &static_track_group_handler, active); install_keyword("group", &static_track_group_group_handler); install_keyword_root("static_ipaddress", &static_addresses_handler, active); #ifdef _HAVE_FIB_ROUTING_ install_keyword_root("static_routes", &static_routes_handler, active); install_keyword_root("static_rules", &static_rules_handler, active); #endif /* Sync group declarations */ install_keyword_root("vrrp_sync_group", &vrrp_sync_group_handler, active); install_keyword("group", &vrrp_group_handler); install_keyword("track_interface", &vrrp_group_track_if_handler); install_keyword("track_script", &vrrp_group_track_scr_handler); install_keyword("track_file", &vrrp_group_track_file_handler); #ifdef _WITH_BFD_ install_keyword("track_bfd", &vrrp_group_track_bfd_handler); #endif install_keyword("notify_backup", &vrrp_gnotify_backup_handler); install_keyword("notify_master", &vrrp_gnotify_master_handler); install_keyword("notify_fault", &vrrp_gnotify_fault_handler); install_keyword("notify_stop", &vrrp_gnotify_stop_handler); install_keyword("notify", &vrrp_gnotify_handler); install_keyword("smtp_alert", &vrrp_gsmtp_handler); install_keyword("global_tracking", &vrrp_gglobal_tracking_handler); install_keyword("sync_group_tracking_weight", &vrrp_sg_tracking_weight_handler); install_keyword_root("garp_group", &garp_group_handler, active); install_keyword("garp_interval", &garp_group_garp_interval_handler); install_keyword("gna_interval", &garp_group_gna_interval_handler); install_keyword("interface", &garp_group_interface_handler); install_keyword("interfaces", &garp_group_interfaces_handler); install_sublevel_end_handler(&garp_group_end_handler); /* VRRP Instance mapping */ install_keyword_root("vrrp_instance", &vrrp_handler, active); #ifdef _HAVE_VRRP_VMAC_ install_keyword("use_vmac", &vrrp_vmac_handler); install_keyword("vmac_xmit_base", &vrrp_vmac_xmit_base_handler); #endif install_keyword("unicast_peer", &vrrp_unicast_peer_handler); #ifdef _WITH_UNICAST_CHKSUM_COMPAT_ install_keyword("old_unicast_checksum", &vrrp_unicast_chksum_handler); #endif install_keyword("native_ipv6", &vrrp_native_ipv6_handler); install_keyword("state", &vrrp_state_handler); install_keyword("interface", &vrrp_int_handler); install_keyword("dont_track_primary", &vrrp_dont_track_handler); install_keyword("track_interface", &vrrp_track_if_handler); install_keyword("track_script", &vrrp_track_scr_handler); install_keyword("track_file", &vrrp_track_file_handler); #ifdef _WITH_BFD_ install_keyword("track_bfd", &vrrp_track_bfd_handler); #endif install_keyword("mcast_src_ip", &vrrp_srcip_handler); install_keyword("unicast_src_ip", &vrrp_srcip_handler); install_keyword("track_src_ip", &vrrp_track_srcip_handler); install_keyword("virtual_router_id", &vrrp_vrid_handler); install_keyword("version", &vrrp_version_handler); install_keyword("priority", &vrrp_prio_handler); install_keyword("advert_int", &vrrp_adv_handler); install_keyword("virtual_ipaddress", &vrrp_vip_handler); install_keyword("virtual_ipaddress_excluded", &vrrp_evip_handler); install_keyword("promote_secondaries", &vrrp_promote_secondaries_handler); install_keyword("linkbeat_use_polling", &vrrp_linkbeat_handler); #ifdef _HAVE_FIB_ROUTING_ install_keyword("virtual_routes", &vrrp_vroutes_handler); install_keyword("virtual_rules", &vrrp_vrules_handler); #endif install_keyword("accept", &vrrp_accept_handler); install_keyword("no_accept", &vrrp_no_accept_handler); install_keyword("skip_check_adv_addr", &vrrp_skip_check_adv_addr_handler); install_keyword("strict_mode", &vrrp_strict_mode_handler); install_keyword("preempt", &vrrp_preempt_handler); install_keyword("nopreempt", &vrrp_nopreempt_handler); install_keyword("preempt_delay", &vrrp_preempt_delay_handler); install_keyword("debug", &vrrp_debug_handler); install_keyword("notify_backup", &vrrp_notify_backup_handler); install_keyword("notify_master", &vrrp_notify_master_handler); install_keyword("notify_fault", &vrrp_notify_fault_handler); install_keyword("notify_stop", &vrrp_notify_stop_handler); install_keyword("notify", &vrrp_notify_handler); install_keyword("notify_master_rx_lower_pri", vrrp_notify_master_rx_lower_pri); install_keyword("smtp_alert", &vrrp_smtp_handler); #ifdef _WITH_LVS_ install_keyword("lvs_sync_daemon_interface", &vrrp_lvs_syncd_handler); #endif install_keyword("garp_master_delay", &vrrp_garp_delay_handler); install_keyword("garp_master_refresh", &vrrp_garp_refresh_handler); install_keyword("garp_master_repeat", &vrrp_garp_rep_handler); install_keyword("garp_master_refresh_repeat", &vrrp_garp_refresh_rep_handler); install_keyword("garp_lower_prio_delay", &vrrp_garp_lower_prio_delay_handler); install_keyword("garp_lower_prio_repeat", &vrrp_garp_lower_prio_rep_handler); install_keyword("lower_prio_no_advert", &vrrp_lower_prio_no_advert_handler); install_keyword("higher_prio_send_advert", &vrrp_higher_prio_send_advert_handler); install_keyword("kernel_rx_buf_size", &kernel_rx_buf_size_handler); #if defined _WITH_VRRP_AUTH_ install_keyword("authentication", NULL); install_sublevel(); install_keyword("auth_type", &vrrp_auth_type_handler); install_keyword("auth_pass", &vrrp_auth_pass_handler); install_sublevel_end(); #endif install_keyword_root("vrrp_script", &vrrp_script_handler, active); install_keyword("script", &vrrp_vscript_script_handler); install_keyword("interval", &vrrp_vscript_interval_handler); install_keyword("timeout", &vrrp_vscript_timeout_handler); install_keyword("weight", &vrrp_vscript_weight_handler); install_keyword("rise", &vrrp_vscript_rise_handler); install_keyword("fall", &vrrp_vscript_fall_handler); install_keyword("user", &vrrp_vscript_user_handler); install_keyword("init_fail", &vrrp_vscript_init_fail_handler); install_sublevel_end_handler(&vrrp_vscript_end_handler); /* Track file declarations */ install_keyword_root("vrrp_track_file", &vrrp_tfile_handler, active); install_keyword("file", &vrrp_tfile_file_handler); install_keyword("weight", &vrrp_tfile_weight_handler); install_keyword("init_file", &vrrp_tfile_init_handler); install_sublevel_end_handler(&vrrp_tfile_end_handler); } vector_t * vrrp_init_keywords(void) { /* global definitions mapping */ init_global_keywords(reload); init_vrrp_keywords(true); #ifdef _WITH_LVS_ init_check_keywords(false); #endif #ifdef _WITH_BFD_ init_bfd_keywords(true); #endif return keywords; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_5
crossvul-cpp_data_bad_436_4
/* * Soft: Vrrpd is an implementation of VRRPv2 as specified in rfc2338. * VRRP is a protocol which elect a master server on a LAN. If the * master fails, a backup server takes over. * The original implementation has been made by jerome etienne. * * Part: Output running VRRP state information in JSON format * * Author: Damien Clabaut, <Damien.Clabaut@corp.ovh.com> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2017 Damien Clabaut, <Damien.Clabaut@corp.ovh.com> * Copyright (C) 2017-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include "vrrp_json.h" #include <errno.h> #include <stdio.h> #include <json.h> #include "vrrp.h" #include "vrrp_track.h" #include "list.h" #include "vrrp_data.h" #include "vrrp_iproute.h" #include "vrrp_iprule.h" #include "logger.h" #include "timer.h" static inline double timeval_to_double(const timeval_t *t) { /* The casts are necessary to avoid conversion warnings */ return (double)t->tv_sec + (double)t->tv_usec / TIMER_HZ_FLOAT; } void vrrp_print_json(void) { FILE *file; element e; struct json_object *array; if (LIST_ISEMPTY(vrrp_data->vrrp)) return; file = fopen ("/tmp/keepalived.json","w"); if (!file) { log_message(LOG_INFO, "Can't open /tmp/keepalived.json (%d: %s)", errno, strerror(errno)); return; } array = json_object_new_array(); for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { struct json_object *instance_json, *json_stats, *json_data, *vips, *evips, *track_ifp, *track_script; #ifdef _HAVE_FIB_ROUTING_ struct json_object *vroutes, *vrules; #endif element f; vrrp_t *vrrp = ELEMENT_DATA(e); instance_json = json_object_new_object(); json_stats = json_object_new_object(); json_data = json_object_new_object(); vips = json_object_new_array(); evips = json_object_new_array(); track_ifp = json_object_new_array(); track_script = json_object_new_array(); #ifdef _HAVE_FIB_ROUTING_ vroutes = json_object_new_array(); vrules = json_object_new_array(); #endif // Dump data to json json_object_object_add(json_data, "iname", json_object_new_string(vrrp->iname)); json_object_object_add(json_data, "dont_track_primary", json_object_new_int(vrrp->dont_track_primary)); json_object_object_add(json_data, "skip_check_adv_addr", json_object_new_int(vrrp->skip_check_adv_addr)); json_object_object_add(json_data, "strict_mode", json_object_new_int((int)vrrp->strict_mode)); #ifdef _HAVE_VRRP_VMAC_ json_object_object_add(json_data, "vmac_ifname", json_object_new_string(vrrp->vmac_ifname)); #endif // Tracked interfaces are stored in a list if (!LIST_ISEMPTY(vrrp->track_ifp)) { for (f = LIST_HEAD(vrrp->track_ifp); f; ELEMENT_NEXT(f)) { interface_t *ifp = ELEMENT_DATA(f); json_object_array_add(track_ifp, json_object_new_string(ifp->ifname)); } } json_object_object_add(json_data, "track_ifp", track_ifp); // Tracked scripts also if (!LIST_ISEMPTY(vrrp->track_script)) { for (f = LIST_HEAD(vrrp->track_script); f; ELEMENT_NEXT(f)) { tracked_sc_t *tsc = ELEMENT_DATA(f); vrrp_script_t *vscript = tsc->scr; json_object_array_add(track_script, json_object_new_string(cmd_str(&vscript->script))); } } json_object_object_add(json_data, "track_script", track_script); json_object_object_add(json_data, "ifp_ifname", json_object_new_string(vrrp->ifp->ifname)); json_object_object_add(json_data, "master_priority", json_object_new_int(vrrp->master_priority)); json_object_object_add(json_data, "last_transition", json_object_new_double(timeval_to_double(&vrrp->last_transition))); json_object_object_add(json_data, "garp_delay", json_object_new_double(vrrp->garp_delay / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "garp_refresh", json_object_new_int((int)vrrp->garp_refresh.tv_sec)); json_object_object_add(json_data, "garp_rep", json_object_new_int((int)vrrp->garp_rep)); json_object_object_add(json_data, "garp_refresh_rep", json_object_new_int((int)vrrp->garp_refresh_rep)); json_object_object_add(json_data, "garp_lower_prio_delay", json_object_new_int((int)(vrrp->garp_lower_prio_delay / TIMER_HZ))); json_object_object_add(json_data, "garp_lower_prio_rep", json_object_new_int((int)vrrp->garp_lower_prio_rep)); json_object_object_add(json_data, "lower_prio_no_advert", json_object_new_int((int)vrrp->lower_prio_no_advert)); json_object_object_add(json_data, "higher_prio_send_advert", json_object_new_int((int)vrrp->higher_prio_send_advert)); json_object_object_add(json_data, "vrid", json_object_new_int(vrrp->vrid)); json_object_object_add(json_data, "base_priority", json_object_new_int(vrrp->base_priority)); json_object_object_add(json_data, "effective_priority", json_object_new_int(vrrp->effective_priority)); json_object_object_add(json_data, "vipset", json_object_new_boolean(vrrp->vipset)); //Virtual IPs are stored in a list if (!LIST_ISEMPTY(vrrp->vip)) { for (f = LIST_HEAD(vrrp->vip); f; ELEMENT_NEXT(f)) { ip_address_t *vip = ELEMENT_DATA(f); char ipaddr[INET6_ADDRSTRLEN]; inet_ntop(vrrp->family, &(vip->u.sin.sin_addr.s_addr), ipaddr, INET6_ADDRSTRLEN); json_object_array_add(vips, json_object_new_string(ipaddr)); } } json_object_object_add(json_data, "vips", vips); //External VIPs are also stored in a list if (!LIST_ISEMPTY(vrrp->evip)) { for (f = LIST_HEAD(vrrp->evip); f; ELEMENT_NEXT(f)) { ip_address_t *evip = ELEMENT_DATA(f); char ipaddr[INET6_ADDRSTRLEN]; inet_ntop(vrrp->family, &(evip->u.sin.sin_addr.s_addr), ipaddr, INET6_ADDRSTRLEN); json_object_array_add(evips, json_object_new_string(ipaddr)); } } json_object_object_add(json_data, "evips", evips); json_object_object_add(json_data, "promote_secondaries", json_object_new_boolean(vrrp->promote_secondaries)); #ifdef _HAVE_FIB_ROUTING_ // Dump vroutes if (!LIST_ISEMPTY(vrrp->vroutes)) { for (f = LIST_HEAD(vrrp->vroutes); f; ELEMENT_NEXT(f)) { ip_route_t *route = ELEMENT_DATA(f); char *buf = MALLOC(ROUTE_BUF_SIZE); format_iproute(route, buf, ROUTE_BUF_SIZE); json_object_array_add(vroutes, json_object_new_string(buf)); } } json_object_object_add(json_data, "vroutes", vroutes); // Dump vrules if (!LIST_ISEMPTY(vrrp->vrules)) { for (f = LIST_HEAD(vrrp->vrules); f; ELEMENT_NEXT(f)) { ip_rule_t *rule = ELEMENT_DATA(f); char *buf = MALLOC(RULE_BUF_SIZE); format_iprule(rule, buf, RULE_BUF_SIZE); json_object_array_add(vrules, json_object_new_string(buf)); } } json_object_object_add(json_data, "vrules", vrules); #endif json_object_object_add(json_data, "adver_int", json_object_new_double(vrrp->adver_int / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "master_adver_int", json_object_new_double(vrrp->master_adver_int / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "accept", json_object_new_int((int)vrrp->accept)); json_object_object_add(json_data, "nopreempt", json_object_new_boolean(vrrp->nopreempt)); json_object_object_add(json_data, "preempt_delay", json_object_new_int((int)(vrrp->preempt_delay / TIMER_HZ))); json_object_object_add(json_data, "state", json_object_new_int(vrrp->state)); json_object_object_add(json_data, "wantstate", json_object_new_int(vrrp->wantstate)); json_object_object_add(json_data, "version", json_object_new_int(vrrp->version)); if (vrrp->script_backup) json_object_object_add(json_data, "script_backup", json_object_new_string(cmd_str(vrrp->script_backup))); if (vrrp->script_master) json_object_object_add(json_data, "script_master", json_object_new_string(cmd_str(vrrp->script_master))); if (vrrp->script_fault) json_object_object_add(json_data, "script_fault", json_object_new_string(cmd_str(vrrp->script_fault))); if (vrrp->script_stop) json_object_object_add(json_data, "script_stop", json_object_new_string(cmd_str(vrrp->script_stop))); if (vrrp->script) json_object_object_add(json_data, "script", json_object_new_string(cmd_str(vrrp->script))); if (vrrp->script_master_rx_lower_pri) json_object_object_add(json_data, "script_master_rx_lower_pri", json_object_new_string(cmd_str(vrrp->script_master_rx_lower_pri))); json_object_object_add(json_data, "smtp_alert", json_object_new_boolean(vrrp->smtp_alert)); #ifdef _WITH_VRRP_AUTH_ if (vrrp->auth_type) { json_object_object_add(json_data, "auth_type", json_object_new_int(vrrp->auth_type)); if (vrrp->auth_type != VRRP_AUTH_AH) { char auth_data[sizeof(vrrp->auth_data) + 1]; memcpy(auth_data, vrrp->auth_data, sizeof(vrrp->auth_data)); auth_data[sizeof(vrrp->auth_data)] = '\0'; json_object_object_add(json_data, "auth_data", json_object_new_string(auth_data)); } } else json_object_object_add(json_data, "auth_type", json_object_new_int(0)); #endif // Dump stats to json json_object_object_add(json_stats, "advert_rcvd", json_object_new_int64((int64_t)vrrp->stats->advert_rcvd)); json_object_object_add(json_stats, "advert_sent", json_object_new_int64(vrrp->stats->advert_sent)); json_object_object_add(json_stats, "become_master", json_object_new_int64(vrrp->stats->become_master)); json_object_object_add(json_stats, "release_master", json_object_new_int64(vrrp->stats->release_master)); json_object_object_add(json_stats, "packet_len_err", json_object_new_int64((int64_t)vrrp->stats->packet_len_err)); json_object_object_add(json_stats, "advert_interval_err", json_object_new_int64((int64_t)vrrp->stats->advert_interval_err)); json_object_object_add(json_stats, "ip_ttl_err", json_object_new_int64((int64_t)vrrp->stats->ip_ttl_err)); json_object_object_add(json_stats, "invalid_type_rcvd", json_object_new_int64((int64_t)vrrp->stats->invalid_type_rcvd)); json_object_object_add(json_stats, "addr_list_err", json_object_new_int64((int64_t)vrrp->stats->addr_list_err)); json_object_object_add(json_stats, "invalid_authtype", json_object_new_int64(vrrp->stats->invalid_authtype)); #ifdef _WITH_VRRP_AUTH_ json_object_object_add(json_stats, "authtype_mismatch", json_object_new_int64(vrrp->stats->authtype_mismatch)); json_object_object_add(json_stats, "auth_failure", json_object_new_int64(vrrp->stats->auth_failure)); #endif json_object_object_add(json_stats, "pri_zero_rcvd", json_object_new_int64((int64_t)vrrp->stats->pri_zero_rcvd)); json_object_object_add(json_stats, "pri_zero_sent", json_object_new_int64((int64_t)vrrp->stats->pri_zero_sent)); // Add both json_data and json_stats to main instance_json json_object_object_add(instance_json, "data", json_data); json_object_object_add(instance_json, "stats", json_stats); // Add instance_json to main array json_object_array_add(array, instance_json); } fprintf(file, "%s", json_object_to_json_string(array)); fclose(file); }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_4
crossvul-cpp_data_good_2235_0
/* * * Copyright (C) 2006-2011 Anders Brander <anders@brander.dk>, * * Anders Kvist <akv@lnxbx.dk> and Klaus Post <klauspost@gmail.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdlib.h> /* system() */ #include <rawstudio.h> #include "rs-filter.h" #if 0 /* Change to 1 to enable performance info */ #define filter_performance printf #define FILTER_SHOW_PERFORMANCE #else #define filter_performance(...) {} #endif /* How much time should a filter at least have taken to show performance number */ #define FILTER_PERF_ELAPSED_MIN 0.001 #define CHAIN_PERF_ELAPSED_MIN 0.001 G_DEFINE_TYPE (RSFilter, rs_filter, G_TYPE_OBJECT) enum { CHANGED_SIGNAL, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = { 0 }; static void dispose(GObject *obj) { RSFilter *filter = RS_FILTER(obj); if (!filter->dispose_has_run) { filter->dispose_has_run = TRUE; if (filter->previous) { filter->previous->next_filters = g_slist_remove(filter->previous->next_filters, filter); g_object_unref(filter->previous); } } } static void rs_filter_class_init(RSFilterClass *klass) { RS_DEBUG(FILTERS, "rs_filter_class_init(%p)", klass); GObjectClass *object_class = G_OBJECT_CLASS(klass); signals[CHANGED_SIGNAL] = g_signal_new ("changed", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION, 0, NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); klass->get_image = NULL; klass->get_image8 = NULL; klass->get_size = NULL; klass->previous_changed = NULL; object_class->dispose = dispose; } static void rs_filter_init(RSFilter *self) { RS_DEBUG(FILTERS, "rs_filter_init(%p)", self); self->previous = NULL; self->next_filters = NULL; self->enabled = TRUE; } /** * Return a new instance of a RSFilter * @param name The name of the filter * @param previous The previous filter or NULL * @return The newly instantiated RSFilter or NULL */ RSFilter * rs_filter_new(const gchar *name, RSFilter *previous) { RS_DEBUG(FILTERS, "rs_filter_new(%s, %s [%p])", name, RS_FILTER_NAME(previous), previous); g_return_val_if_fail(name != NULL, NULL); g_return_val_if_fail((previous == NULL) || RS_IS_FILTER(previous), NULL); GType type = g_type_from_name(name); RSFilter *filter = NULL; if (g_type_is_a (type, RS_TYPE_FILTER)) filter = g_object_new(type, NULL); if (!RS_IS_FILTER(filter)) g_warning("Could not instantiate filter of type \"%s\"", name); if (previous) rs_filter_set_previous(filter, previous); return filter; } /** * Set the previous RSFilter in a RSFilter-chain * @param filter A RSFilter * @param previous A previous RSFilter */ void rs_filter_set_previous(RSFilter *filter, RSFilter *previous) { RS_DEBUG(FILTERS, "rs_filter_set_previous(%p, %p)", filter, previous); g_return_if_fail(RS_IS_FILTER(filter)); g_return_if_fail(RS_IS_FILTER(previous)); /* We will only set the previous filter if it differs from current previous filter */ if (filter->previous != previous) { if (filter->previous) { /* If we already got a previous filter, clean up */ filter->previous->next_filters = g_slist_remove(filter->previous->next_filters, filter); g_object_unref(filter->previous); } filter->previous = g_object_ref(previous); previous->next_filters = g_slist_append(previous->next_filters, filter); } } /** * Signal that a filter has changed, filters depending on this will be invoked * This should only be called from filter code * @param filter The changed filter * @param mask A mask indicating what changed */ void rs_filter_changed(RSFilter *filter, RSFilterChangedMask mask) { RS_DEBUG(FILTERS, "rs_filter_changed(%s [%p], %04x)", RS_FILTER_NAME(filter), filter, mask); g_return_if_fail(RS_IS_FILTER(filter)); gint i, n_next = g_slist_length(filter->next_filters); for(i=0; i<n_next; i++) { RSFilter *next = RS_FILTER(g_slist_nth_data(filter->next_filters, i)); g_assert(RS_IS_FILTER(next)); /* Notify "next" filter or try "next next" filter */ if (RS_FILTER_GET_CLASS(next)->previous_changed) RS_FILTER_GET_CLASS(next)->previous_changed(next, filter, mask); else rs_filter_changed(next, mask); } g_signal_emit(G_OBJECT(filter), signals[CHANGED_SIGNAL], 0, mask); } /* Clamps ROI rectangle to image size */ /* Returns a new rectangle, or NULL if ROI was within bounds*/ static GdkRectangle* clamp_roi(const GdkRectangle *roi, RSFilter *filter, const RSFilterRequest *request) { RSFilterResponse *response = rs_filter_get_size(filter, request); gint w = rs_filter_response_get_width(response); gint h = rs_filter_response_get_height(response); g_object_unref(response); if ((roi->x >= 0) && (roi->y >=0) && (roi->x + roi->width <= w) && (roi->y + roi->height <= h)) return NULL; GdkRectangle* new_roi = g_new(GdkRectangle, 1); new_roi->x = MAX(0, roi->x); new_roi->y = MAX(0, roi->y); new_roi->width = MIN(w - new_roi->x, roi->width); new_roi->height = MAX(h - new_roi->y, roi->height); return new_roi; } /** * Get the output image from a RSFilter * @param filter A RSFilter * @param param A RSFilterRequest defining parameters for a image request * @return A RS_IMAGE16, this must be unref'ed */ RSFilterResponse * rs_filter_get_image(RSFilter *filter, const RSFilterRequest *request) { GdkRectangle* roi = NULL; RSFilterRequest *r = NULL; g_return_val_if_fail(RS_IS_FILTER(filter), NULL); g_return_val_if_fail(RS_IS_FILTER_REQUEST(request), NULL); RS_DEBUG(FILTERS, "rs_filter_get_image(%s [%p])", RS_FILTER_NAME(filter), filter); /* This timer-hack will break badly when multithreaded! */ static gfloat last_elapsed = 0.0; static gint count = -1; gfloat elapsed; static GTimer *gt = NULL; RSFilterResponse *response; RS_IMAGE16 *image; if (count == -1) gt = g_timer_new(); count++; if (filter->enabled && (roi = rs_filter_request_get_roi(request))) { roi = clamp_roi(roi, filter, request); if (roi) { r = rs_filter_request_clone(request); rs_filter_request_set_roi(r, roi); request = r; } } if (RS_FILTER_GET_CLASS(filter)->get_image && filter->enabled) response = RS_FILTER_GET_CLASS(filter)->get_image(filter, request); else response = rs_filter_get_image(filter->previous, request); g_assert(RS_IS_FILTER_RESPONSE(response)); image = rs_filter_response_get_image(response); elapsed = g_timer_elapsed(gt, NULL) - last_elapsed; if (roi) g_free(roi); if (r) g_object_unref(r); #ifdef FILTER_SHOW_PERFORMANCE if ((elapsed > FILTER_PERF_ELAPSED_MIN) && (image != NULL)) { gint iw = image->w; gint ih = image->h; if (rs_filter_response_get_roi(response)) { roi = rs_filter_response_get_roi(response); iw = roi->width; ih = roi->height; } filter_performance("%s took: \033[32m%.0f\033[0mms", RS_FILTER_NAME(filter), elapsed*1000); if ((elapsed > 0.001) && (image != NULL)) filter_performance(" [\033[33m%.01f\033[0mMpix/s]", ((gfloat)(iw*ih))/elapsed/1000000.0); if (image) filter_performance(" [w: %d, h: %d, roi-w:%d, roi-h:%d, channels: %d, pixelsize: %d, rowstride: %d]", image->w, image->h, iw, ih, image->channels, image->pixelsize, image->rowstride); filter_performance("\n"); } #endif g_assert(RS_IS_IMAGE16(image) || (image == NULL)); last_elapsed += elapsed; count--; if (count == -1) { last_elapsed = 0.0; if (g_timer_elapsed(gt,NULL) > CHAIN_PERF_ELAPSED_MIN) filter_performance("Complete 16 bit chain took: \033[32m%.0f\033[0mms\n\n", g_timer_elapsed(gt, NULL)*1000.0); rs_filter_param_set_float(RS_FILTER_PARAM(response), "16-bit-time", g_timer_elapsed(gt, NULL)); g_timer_destroy(gt); } if (image) g_object_unref(image); return response; } /** * Get 8 bit output image from a RSFilter * @param filter A RSFilter * @param param A RSFilterRequest defining parameters for a image request * @return A RS_IMAGE16, this must be unref'ed */ RSFilterResponse * rs_filter_get_image8(RSFilter *filter, const RSFilterRequest *request) { g_return_val_if_fail(RS_IS_FILTER(filter), NULL); g_return_val_if_fail(RS_IS_FILTER_REQUEST(request), NULL); RS_DEBUG(FILTERS, "rs_filter_get_image8(%s [%p])", RS_FILTER_NAME(filter), filter); /* This timer-hack will break badly when multithreaded! */ static gfloat last_elapsed = 0.0; static gint count = -1; gfloat elapsed, temp; static GTimer *gt = NULL; RSFilterResponse *response = NULL; GdkPixbuf *image = NULL; GdkRectangle* roi = NULL; RSFilterRequest *r = NULL; g_return_val_if_fail(RS_IS_FILTER(filter), NULL); g_return_val_if_fail(RS_IS_FILTER_REQUEST(request), NULL); if (count == -1) gt = g_timer_new(); count++; if (filter->enabled && (roi = rs_filter_request_get_roi(request))) { roi = clamp_roi(roi, filter, request); if (roi) { r = rs_filter_request_clone(request); rs_filter_request_set_roi(r, roi); request = r; } } if (RS_FILTER_GET_CLASS(filter)->get_image8 && filter->enabled) response = RS_FILTER_GET_CLASS(filter)->get_image8(filter, request); else if (filter->previous) response = rs_filter_get_image8(filter->previous, request); g_assert(RS_IS_FILTER_RESPONSE(response)); image = rs_filter_response_get_image8(response); elapsed = g_timer_elapsed(gt, NULL) - last_elapsed; /* Subtract 16 bit time */ if (rs_filter_param_get_float(RS_FILTER_PARAM(response), "16-bit-time", &temp)) elapsed -= temp; if (roi) g_free(roi); if (r) g_object_unref(r); #ifdef FILTER_SHOW_PERFORMANCE if ((elapsed > FILTER_PERF_ELAPSED_MIN) && (image != NULL)) { gint iw = gdk_pixbuf_get_width(image); gint ih = gdk_pixbuf_get_height(image); if (rs_filter_response_get_roi(response)) { GdkRectangle *roi = rs_filter_response_get_roi(response); iw = roi->width; ih = roi->height; } filter_performance("%s took: \033[32m%.0f\033[0mms", RS_FILTER_NAME(filter), elapsed * 1000); filter_performance(" [\033[33m%.01f\033[0mMpix/s]", ((gfloat)(iw * ih)) / elapsed / 1000000.0); filter_performance("\n"); } #endif last_elapsed += elapsed; g_assert(GDK_IS_PIXBUF(image) || (image == NULL)); count--; if (count == -1) { last_elapsed = 0.0; rs_filter_param_get_float(RS_FILTER_PARAM(response), "16-bit-time", &last_elapsed); last_elapsed = g_timer_elapsed(gt, NULL)-last_elapsed; if (last_elapsed > CHAIN_PERF_ELAPSED_MIN) filter_performance("Complete 8 bit chain took: \033[32m%.0f\033[0mms\n\n", last_elapsed*1000.0); g_timer_destroy(gt); last_elapsed = 0.0; } if (image) g_object_unref(image); return response; } /** * Get predicted size of a RSFilter * @param filter A RSFilter * @param request A RSFilterRequest defining parameters for the request */ RSFilterResponse * rs_filter_get_size(RSFilter *filter, const RSFilterRequest *request) { RSFilterResponse *response = NULL; g_return_val_if_fail(RS_IS_FILTER(filter), NULL); g_return_val_if_fail(RS_IS_FILTER_REQUEST(request), NULL); if (RS_FILTER_GET_CLASS(filter)->get_size && filter->enabled) response = RS_FILTER_GET_CLASS(filter)->get_size(filter, request); else if (filter->previous) response = rs_filter_get_size(filter->previous, request); return response; } /** * Get predicted size of a RSFilter * @param filter A RSFilter * @param request A RSFilterRequest defining parameters for the request * @param width A pointer to a gint where the width will be written or NULL * @param height A pointer to a gint where the height will be written or NULL * @return TRUE if width/height is known, FALSE otherwise */ gboolean rs_filter_get_size_simple(RSFilter *filter, const RSFilterRequest *request, gint *width, gint *height) { gint w, h; RSFilterResponse *response; g_return_val_if_fail(RS_IS_FILTER(filter), FALSE); g_return_val_if_fail(RS_IS_FILTER_REQUEST(request), FALSE); response = rs_filter_get_size(filter, request); if (!RS_IS_FILTER_RESPONSE(response)) return FALSE; w = rs_filter_response_get_width(response); h = rs_filter_response_get_height(response); if (width) *width = w; if (height) *height = h; g_object_unref(response); return ((w>0) && (h>0)); } /** * Set a GObject property on zero or more filters above #filter recursively * @param filter A RSFilter * @param ... Pairs of property names and values followed by NULL */ void rs_filter_set_recursive(RSFilter *filter, ...) { va_list ap; gchar *property_name; RSFilter *current_filter; GParamSpec *spec; RSFilter *first_seen_here = NULL; GTypeValueTable *table = NULL; GType type = 0; union CValue { gint v_int; glong v_long; gint64 v_int64; gdouble v_double; gpointer v_pointer; } value; g_return_if_fail(RS_IS_FILTER(filter)); va_start(ap, filter); /* Loop through all properties */ while ((property_name = va_arg(ap, gchar *))) { /* We set table to NULL for every property to indicate that we (again) * have an "unknown" type */ table = NULL; current_filter = filter; /* Iterate through all filters previous to filter */ do { if ((spec = g_object_class_find_property(G_OBJECT_GET_CLASS(current_filter), property_name))) if (spec->flags & G_PARAM_WRITABLE) { /* If we got no GTypeValueTable at this point, we aquire * one. We rely on all filters using the same type for all * properties equally named */ if (!table) { first_seen_here = current_filter; type = spec->value_type; table = g_type_value_table_peek(type); /* If we have no valuetable, we're screwed, bail out */ if (!table) g_error("No GTypeValueTable found for '%s'", g_type_name(type)); switch (table->collect_format[0]) { case 'i': value.v_int = va_arg(ap, gint); break; case 'l': value.v_long = va_arg(ap, glong); break; case 'd': value.v_double = va_arg(ap, gdouble); break; case 'p': value.v_pointer = va_arg(ap, gpointer); break; default: g_error("Don't know how to collect for '%s'", g_type_name(type)); break; } } if (table) { /* We try to catch cases where different filters use * the same property name for different types */ if (type != spec->value_type) g_warning("Diverging types found for property '%s' (on filter '%s' and '%s')", property_name, RS_FILTER_NAME(first_seen_here), RS_FILTER_NAME(current_filter)); switch (table->collect_format[0]) { case 'i': g_object_set(current_filter, property_name, value.v_int, NULL); break; case 'l': g_object_set(current_filter, property_name, value.v_long, NULL); break; case 'd': g_object_set(current_filter, property_name, value.v_double, NULL); break; case 'p': g_object_set(current_filter, property_name, value.v_pointer, NULL); break; default: break; } } } } while (RS_IS_FILTER(current_filter = current_filter->previous)); if (!table) { // g_warning("Property: %s could not be found in filter chain. Skipping further properties", property_name); va_end(ap); return; } } va_end(ap); } /** * Get a GObject property from a RSFilter chain recursively * @param filter A RSFilter * @param ... Pairs of property names and a return pointers followed by NULL */ void rs_filter_get_recursive(RSFilter *filter, ...) { va_list ap; gchar *property_name; gpointer property_ret; RSFilter *current_filter; g_return_if_fail(RS_IS_FILTER(filter)); va_start(ap, filter); /* Loop through all properties */ while ((property_name = va_arg(ap, gchar *))) { property_ret = va_arg(ap, gpointer); g_assert(property_ret != NULL); current_filter = filter; /* Iterate through all filter previous to filter */ do { if (current_filter->enabled && g_object_class_find_property(G_OBJECT_GET_CLASS(current_filter), property_name)) { g_object_get(current_filter, property_name, property_ret, NULL); break; } } while (RS_IS_FILTER(current_filter = current_filter->previous)); } va_end(ap); } /** * Set enabled state of a RSFilter * @param filter A RSFilter * @param enabled TRUE to enable filter, FALSE to disable * @return Previous state */ gboolean rs_filter_set_enabled(RSFilter *filter, gboolean enabled) { gboolean previous_state; g_return_val_if_fail(RS_IS_FILTER(filter), FALSE); previous_state = filter->enabled; if (filter->enabled != enabled) { filter->enabled = enabled; rs_filter_changed(filter, RS_FILTER_CHANGED_PIXELDATA); } return previous_state; } /** * Get enabled state of a RSFilter * @param filter A RSFilter * @return TRUE if filter is enabled, FALSE if disabled */ gboolean rs_filter_get_enabled(RSFilter *filter) { g_return_val_if_fail(RS_IS_FILTER(filter), FALSE); return filter->enabled; } /** * Set a label for a RSFilter - only used for debugging * @param filter A RSFilter * @param label A new label for the RSFilter, this will NOT be copied */ extern void rs_filter_set_label(RSFilter *filter, const gchar *label) { g_return_if_fail(RS_IS_FILTER(filter)); filter->label = label; } /** * Get the label for a RSFilter * @param filter A RSFilter * @return The label for the RSFilter or NULL */ const gchar * rs_filter_get_label(RSFilter *filter) { g_return_val_if_fail(RS_IS_FILTER(filter), ""); return filter->label; } static void rs_filter_graph_helper(GString *str, RSFilter *filter) { g_assert(str != NULL); g_assert(RS_IS_FILTER(filter)); g_string_append_printf(str, "\"%p\" [\n\tshape=\"Mrecord\"\n", filter); if (!g_str_equal(RS_FILTER_NAME(filter), "RSCache")) g_string_append_printf(str, "\tcolor=grey\n\tstyle=filled\n"); if (filter->enabled) g_string_append_printf(str, "\tcolor=\"#66ba66\"\n"); else g_string_append_printf(str, "\tcolor=grey\n"); g_string_append_printf(str, "\tlabel=<<table cellborder=\"0\" border=\"0\">\n"); GObjectClass *klass = G_OBJECT_GET_CLASS(filter); GParamSpec **specs; gint i; guint n_specs = 0; /* Filter name (and label) */ g_string_append_printf(str, "\t\t<tr>\n\t\t\t<td colspan=\"2\" bgcolor=\"black\"><font color=\"white\">%s", RS_FILTER_NAME(filter)); if (filter->label) g_string_append_printf(str, " (%s)", filter->label); g_string_append_printf(str, "</font></td>\n\t\t</tr>\n"); /* Parameter and value list */ specs = g_object_class_list_properties(G_OBJECT_CLASS(klass), &n_specs); for(i=0; i<n_specs; i++) { gboolean boolean = FALSE; gint integer = 0; gfloat loat = 0.0; gchar *ostr = NULL; g_string_append_printf(str, "\t\t<tr>\n\t\t\t<td align=\"right\">%s:</td>\n\t\t\t<td align=\"left\">", specs[i]->name); /* We have to use if/else here, because RS_TYPE_* does not resolve to a constant */ if (G_PARAM_SPEC_VALUE_TYPE(specs[i]) == RS_TYPE_LENS) { RSLens *lens; gchar *identifier; g_object_get(filter, specs[i]->name, &lens, NULL); if (lens) { g_object_get(lens, "identifier", &identifier, NULL); g_object_unref(lens); g_string_append_printf(str, "%s", identifier); g_free(identifier); } else g_string_append_printf(str, "n/a"); } else if (G_PARAM_SPEC_VALUE_TYPE(specs[i]) == RS_TYPE_ICC_PROFILE) { RSIccProfile *profile; gchar *profile_filename; gchar *profile_basename; g_object_get(filter, specs[i]->name, &profile, NULL); g_object_get(profile, "filename", &profile_filename, NULL); g_object_unref(profile); profile_basename = g_path_get_basename (profile_filename); g_free(profile_filename); g_string_append_printf(str, "%s", profile_basename); g_free(profile_basename); } else switch (G_PARAM_SPEC_VALUE_TYPE(specs[i])) { case G_TYPE_BOOLEAN: g_object_get(filter, specs[i]->name, &boolean, NULL); g_string_append_printf(str, "%s", (boolean) ? "TRUE" : "FALSE"); break; case G_TYPE_INT: g_object_get(filter, specs[i]->name, &integer, NULL); g_string_append_printf(str, "%d", integer); break; case G_TYPE_FLOAT: g_object_get(filter, specs[i]->name, &loat, NULL); g_string_append_printf(str, "%.05f", loat); break; case G_TYPE_STRING: g_object_get(filter, specs[i]->name, &ostr, NULL); g_string_append_printf(str, "%s", ostr); break; default: g_string_append_printf(str, "n/a"); break; } g_string_append_printf(str, "</td>\n\t\t</tr>\n"); } g_string_append_printf(str, "\t\t</table>>\n\t];\n"); gint n_next = g_slist_length(filter->next_filters); for(i=0; i<n_next; i++) { RSFilter *next = RS_FILTER(g_slist_nth_data(filter->next_filters, i)); RSFilterResponse *response = rs_filter_get_size(filter, RS_FILTER_REQUEST_QUICK); /* Edge - print dimensions along */ g_string_append_printf(str, "\t\"%p\" -> \"%p\" [label=\" %dx%d\"];\n", filter, next, rs_filter_response_get_width(response), rs_filter_response_get_height(response)); g_object_unref(response); /* Recursively call ourself for every "next" filter */ rs_filter_graph_helper(str, next); } } /** * Draw a nice graph of the filter chain * note: Requires graphviz * @param filter The top-most filter to graph */ void rs_filter_graph(RSFilter *filter) { g_return_if_fail(RS_IS_FILTER(filter)); gchar *dot_filename; gchar *png_filename; gchar *command_line; GString *str = g_string_new("digraph G {\n"); rs_filter_graph_helper(str, filter); g_string_append_printf(str, "}\n"); /* Here we would like to use g_mkdtemp(), but due to a bug in upstream, that's impossible */ dot_filename = g_strdup_printf("/tmp/rs-filter-graph.%u", g_random_int()); png_filename = g_strdup_printf("%s.%u.png", dot_filename, g_random_int()); g_file_set_contents(dot_filename, str->str, str->len, NULL); command_line = g_strdup_printf("dot -Tpng >%s <%s", png_filename, dot_filename); if (0 != system(command_line)) g_warning("Calling dot failed"); g_free(command_line); command_line = g_strdup_printf("gnome-open %s", png_filename); if (0 != system(command_line)) g_warning("Calling gnome-open failed."); g_free(command_line); g_free(dot_filename); g_free(png_filename); g_string_free(str, TRUE); }
./CrossVul/dataset_final_sorted/CWE-59/c/good_2235_0
crossvul-cpp_data_good_1673_0
/* abrt-hook-ccpp.cpp - the hook for C/C++ crashing program Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com) Copyright (C) 2009 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/utsname.h> #include "libabrt.h" #include <selinux/selinux.h> #ifdef ENABLE_DUMP_TIME_UNWIND #include <satyr/abrt.h> #include <satyr/utils.h> #endif /* ENABLE_DUMP_TIME_UNWIND */ static int g_user_core_flags; static int g_need_nonrelative; /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) /* Custom version of copyfd_xyz, * one which is able to write into two descriptors at once. */ #define CONFIG_FEATURE_COPYBUF_KB 4 static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; // truncate to 0 or even delete the second file? // No, kernel does not delete nor truncate core files. } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } /* Global data */ static char *user_pwd; static DIR *proc_cwd; static struct dump_dir *dd; /* * %s - signal number * %c - ulimit -c value * %p - pid * %u - uid * %g - gid * %t - UNIX time of dump * %e - executable filename * %i - crash thread tid * %P - global pid * %% - output one "%" */ /* Hook must be installed with exactly the same sequence of %c specifiers. * Last one, %h, may be omitted (we can find it out). */ static const char percent_specifiers[] = "%scpugtePi"; static char *core_basename = (char*) "core"; static DIR *open_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); DIR *cwd = opendir(buf); if (cwd == NULL) perror_msg("Can't open process's CWD for CompatCore"); return cwd; } /* Computes a security context of new file created by the given process with * pid in the given directory represented by file descriptor. * * On errors returns negative number. Returns 0 if the function succeeds and * computes the context and returns positive number and assigns NULL to newcon * if the security context is not needed (SELinux disabled). */ static int compute_selinux_con_for_new_file(pid_t pid, int dir_fd, security_context_t *newcon) { security_context_t srccon; security_context_t dstcon; const int r = is_selinux_enabled(); if (r == 0) { *newcon = NULL; return 1; } else if (r == -1) { perror_msg("Couldn't get state of SELinux"); return -1; } else if (r != 1) error_msg_and_die("Unexpected SELinux return value: %d", r); if (getpidcon_raw(pid, &srccon) < 0) { perror_msg("getpidcon_raw(%d)", pid); return -1; } if (fgetfilecon_raw(dir_fd, &dstcon) < 0) { perror_msg("getfilecon_raw(%s)", user_pwd); return -1; } if (security_compute_create_raw(srccon, dstcon, string_to_security_class("file"), newcon) < 0) { perror_msg("security_compute_create_raw(%s, %s, 'file')", srccon, dstcon); return -1; } return 0; } static int open_user_core(uid_t uid, uid_t fsuid, gid_t fsgid, pid_t pid, char **percent_values) { proc_cwd = open_cwd(pid); if (proc_cwd == NULL) return -1; /* http://article.gmane.org/gmane.comp.security.selinux/21842 */ security_context_t newcon; if (compute_selinux_con_for_new_file(pid, dirfd(proc_cwd), &newcon) < 0) { log_notice("Not going to create a user core due to SELinux errors"); return -1; } if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } if (g_need_nonrelative && core_basename[0] != '/') { error_msg("Current suid_dumpable policy prevents from saving core dumps according to relative core_pattern"); return -1; } /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ int user_core_fd = -1; int selinux_fail = 1; /* * These calls must be reverted as soon as possible. */ xsetegid(fsgid); xseteuid(fsuid); /* Set SELinux context like kernel when creating core dump file. * This condition is TRUE if */ if (/* SELinux is disabled */ newcon == NULL || /* or the call succeeds */ setfscreatecon_raw(newcon) >= 0) { /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ user_core_fd = openat(dirfd(proc_cwd), core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW | g_user_core_flags, 0600); /* kernel makes 0600 too */ /* Do the error check here and print the error message in order to * avoid interference in 'errno' usage caused by SELinux functions */ if (user_core_fd < 0) perror_msg("Can't open '%s' at '%s'", core_basename, user_pwd); /* Fail if SELinux is enabled and the call fails */ if (newcon != NULL && setfscreatecon_raw(NULL) < 0) perror_msg("setfscreatecon_raw(NULL)"); else selinux_fail = 0; } else perror_msg("setfscreatecon_raw(%s)", newcon); /* * DON'T JUMP OVER THIS REVERT OF THE UID/GID CHANGES */ xsetegid(0); xseteuid(0); if (user_core_fd < 0 || selinux_fail) goto user_core_fail; struct stat sb; if (fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 || sb.st_uid != fsuid ) { perror_msg("'%s' at '%s' is not a regular file with link count 1 owned by UID(%d)", core_basename, user_pwd, fsuid); goto user_core_fail; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' at '%s' to size 0", core_basename, user_pwd); goto user_core_fail; } return user_core_fd; user_core_fail: if (user_core_fd >= 0) close(user_core_fd); return -1; } static int close_user_core(int user_core_fd, off_t core_size) { if (user_core_fd >= 0 && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0)) { perror_msg("Error writing '%s' at '%s'", core_basename, user_pwd); return -1; } return 0; } /* Like xopen, but on error, unlocks and deletes dd and user core */ static int create_or_die(const char *filename, int user_core_fd) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, DEFAULT_DUMP_DIR_MODE); if (fd >= 0) { IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid)); return fd; } int sv_errno = errno; if (dd) dd_delete(dd); if (user_core_fd >= 0) close(user_core_fd); errno = sv_errno; perror_msg_and_die("Can't open '%s'", filename); } static void create_core_backtrace(pid_t tid, const char *executable, int signal_no, struct dump_dir *dd) { #ifdef ENABLE_DUMP_TIME_UNWIND if (g_verbose > 1) sr_debug_parser = true; char *error_message = NULL; char *core_bt = sr_abrt_get_core_stacktrace_from_core_hook(tid, executable, signal_no, &error_message); if (core_bt == NULL) { log("Failed to create core_backtrace: %s", error_message); free(error_message); return; } dd_save_text(dd, FILENAME_CORE_BACKTRACE, core_bt); free(core_bt); #endif /* ENABLE_DUMP_TIME_UNWIND */ } static int create_user_core(int user_core_fd, pid_t pid, off_t ulimit_c) { int err = 1; if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (close_user_core(user_core_fd, core_size) != 0) goto finito; log_notice("Saved core dump of pid %lu to '%s' at '%s' (%llu bytes)", (long)pid, core_basename, user_pwd, (long long)core_size); } err = 0; finito: if (proc_cwd != NULL) { closedir(proc_cwd); proc_cwd = NULL; } return err; } static int test_configuration(bool setting_SaveFullCore, bool setting_CreateCoreBacktrace) { if (!setting_SaveFullCore && !setting_CreateCoreBacktrace) { fprintf(stderr, "Both SaveFullCore and CreateCoreBacktrace are disabled - " "at least one of them is needed for useful report.\n"); return 1; } return 0; } static int save_crashing_binary(pid_t pid, struct dump_dir *dd) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); int src_fd_binary = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ if (src_fd_binary < 0) { log_notice("Failed to open an image of crashing binary"); return 0; } int dst_fd = openat(dd->dd_fd, FILENAME_BINARY, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, DEFAULT_DUMP_DIR_MODE); if (dst_fd < 0) { log_notice("Failed to create file '"FILENAME_BINARY"' at '%s'", dd->dd_dirname); close(src_fd_binary); return -1; } IGNORE_RESULT(fchown(dst_fd, dd->dd_uid, dd->dd_gid)); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); close(src_fd_binary); return fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0; } int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); int err = 1; logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; bool setting_SaveFullCore; bool setting_CreateCoreBacktrace; bool setting_SaveContainerizedPackageData; bool setting_StandaloneHook; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveFullCore"); setting_SaveFullCore = value ? string_to_bool(value) : true; value = get_map_string_item_or_NULL(settings, "CreateCoreBacktrace"); setting_CreateCoreBacktrace = value ? string_to_bool(value) : true; value = get_map_string_item_or_NULL(settings, "SaveContainerizedPackageData"); setting_SaveContainerizedPackageData = value && string_to_bool(value); /* Do not call abrt-action-save-package-data with process's root, if ExploreChroots is disabled. */ if (!g_settings_explorechroots) { if (setting_SaveContainerizedPackageData) log_warning("Ignoring SaveContainerizedPackageData because ExploreChroots is disabled"); setting_SaveContainerizedPackageData = false; } value = get_map_string_item_or_NULL(settings, "StandaloneHook"); setting_StandaloneHook = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } if (argc == 2 && strcmp(argv[1], "--config-test")) return test_configuration(setting_SaveFullCore, setting_CreateCoreBacktrace); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %P %i*/ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME GLOBAL_PID [TID]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t local_pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || local_pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } const char *global_pid_str = argv[8]; pid_t pid = xatoi_positive(argv[8]); pid_t tid = -1; const char *tid_str = argv[9]; if (tid_str) { tid = xatoi_positive(tid_str); } char path[PATH_MAX]; char *executable = get_executable(pid); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); char *proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(proc_pid_status); if (tmp_fsuid < 0) perror_msg_and_die("Can't parse 'Uid: line' in /proc/%lu/status", (long)pid); const int fsgid = get_fsgid(proc_pid_status); if (fsgid < 0) error_msg_and_die("Can't parse 'Gid: line' in /proc/%lu/status", (long)pid); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) fsuid = tmp_fsuid; else { g_user_core_flags = O_EXCL; g_need_nonrelative = 1; } } /* Open a fd to compat coredump, if requested and is possible */ int user_core_fd = -1; if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, fsgid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); return create_user_core(user_core_fd, pid, ulimit_c); } const char *signame = NULL; if (!signal_is_fatal(signal_no, &signame)) return create_user_core(user_core_fd, pid, ulimit_c); // not a signal we care about const int abrtd_running = daemon_is_ok(); if (!setting_StandaloneHook && !abrtd_running) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); return create_user_core(user_core_fd, pid, ulimit_c); } if (setting_StandaloneHook) ensure_writable_dir(g_settings_dump_location, DEFAULT_DUMP_LOCATION_MODE, "abrt"); if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) return create_user_core(user_core_fd, pid, ulimit_c); } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ return create_user_core(user_core_fd, pid, ulimit_c); } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { if (g_settings_debug_level == 0) { log_warning("Ignoring crash of %s (SIG%s).", executable, signame ? signame : signal_str); goto cleanup_and_exit; } /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ if (snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash) >= sizeof(path)) error_msg_and_die("Error saving '%s': truncated long file path", path); unlink(path); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_EXCL, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log_notice("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); err = 0; goto cleanup_and_exit; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { return create_user_core(user_core_fd, pid, ulimit_c); } /* If you don't want to have fs owner as root then: * * - use fsuid instead of uid for fs owner, so we don't expose any * sensitive information of suided app in /var/(tmp|spool)/abrt * * - use dd_create_skeleton() and dd_reset_ownership(), when you finish * creating the new dump directory, to prevent the real owner to write to * the directory until the hook is done (avoid race conditions and defend * hard and symbolic link attacs) */ dd = dd_create(path, /*fs owner*/0, DEFAULT_DUMP_DIR_MODE); if (dd) { char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/root", (long)pid); source_base_ofs -= strlen("root"); /* What's wrong on using /proc/[pid]/root every time ?*/ /* It creates os_info_in_root_dir for all crashes. */ char *rootdir = process_has_own_root(pid) ? get_rootdir(pid) : NULL; /* Reading data from an arbitrary root directory is not secure. */ if (g_settings_explorechroots) { /* Yes, test 'rootdir' but use 'source_filename' because 'rootdir' can * be '/' for a process with own namespace. 'source_filename' is /proc/[pid]/root. */ dd_create_basic_files(dd, fsuid, (rootdir != NULL) ? source_filename : NULL); } else { dd_create_basic_files(dd, fsuid, NULL); } char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: // dd_copy_file(dd, FILENAME_SMAPS, source_filename); strcpy(source_filename + source_base_ofs, "maps"); dd_copy_file(dd, FILENAME_MAPS, source_filename); strcpy(source_filename + source_base_ofs, "limits"); dd_copy_file(dd, FILENAME_LIMITS, source_filename); strcpy(source_filename + source_base_ofs, "cgroup"); dd_copy_file(dd, FILENAME_CGROUP, source_filename); strcpy(source_filename + source_base_ofs, "mountinfo"); dd_copy_file(dd, FILENAME_MOUNTINFO, source_filename); strcpy(dest_base, FILENAME_OPEN_FDS); strcpy(source_filename + source_base_ofs, "fd"); dump_fd_info_ext(dest_filename, source_filename, dd->dd_uid, dd->dd_gid); strcpy(dest_base, FILENAME_NAMESPACES); dump_namespace_diff_ext(dest_filename, 1, pid, dd->dd_uid, dd->dd_gid); free(dest_filename); char *tmp = NULL; get_env_variable(pid, "container", &tmp); if (tmp != NULL) { dd_save_text(dd, FILENAME_CONTAINER, tmp); free(tmp); tmp = NULL; } get_env_variable(pid, "container_uuid", &tmp); if (tmp != NULL) { dd_save_text(dd, FILENAME_CONTAINER_UUID, tmp); free(tmp); } /* There's no need to compare mount namespaces and search for '/' in * mountifo. Comparison of inodes of '/proc/[pid]/root' and '/' works * fine. If those inodes do not equal each other, we have to verify * that '/proc/[pid]/root' is not a symlink to a chroot. */ const int containerized = (rootdir != NULL && strcmp(rootdir, "/") == 0); if (containerized) { log_debug("Process %d is considered to be containerized", pid); pid_t container_pid; if (get_pid_of_container(pid, &container_pid) == 0) { char *container_cmdline = get_cmdline(container_pid); dd_save_text(dd, FILENAME_CONTAINER_CMDLINE, container_cmdline); free(container_cmdline); } } dd_save_text(dd, FILENAME_ANALYZER, "abrt-ccpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_GLOBAL_PID, global_pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (tid_str) dd_save_text(dd, FILENAME_TID, tid_str); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } free(rootdir); char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); /* In case of errors, treat the process as if it has locked memory */ long unsigned lck_bytes = ULONG_MAX; const char *vmlck = strstr(proc_pid_status, "VmLck:"); if (vmlck == NULL) error_msg("/proc/%s/status does not contain 'VmLck:' line", pid_str); else if (1 != sscanf(vmlck + 6, "%lu kB\n", &lck_bytes)) error_msg("Failed to parse 'VmLck:' line in /proc/%s/status", pid_str); if (lck_bytes) { log_notice("Process %s of user %lu has locked memory", pid_str, (long unsigned)uid); dd_mark_as_notreportable(dd, "The process had locked memory " "which usually indicates efforts to protect sensitive " "data (passwords) from being written to disk.\n" "In order to avoid sensitive information leakages, " "ABRT will not allow you to report this problem to " "bug tracking tools"); } if (setting_SaveBinaryImage) { if (save_crashing_binary(pid, dd)) { error_msg("Error saving '%s'", path); goto cleanup_and_exit; } } off_t core_size = 0; if (setting_SaveFullCore) { strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path, user_core_fd); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); close_user_core(user_core_fd, core_size); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg("Error writing '%s'", path); goto cleanup_and_exit; } } else { /* User core is created even if WriteFullCore is off. */ create_user_core(user_core_fd, pid, ulimit_c); } /* User core is either written or closed */ user_core_fd = -1; /* * ! No other errors should cause removal of the user core ! */ /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path, user_core_fd); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { error_msg("Error saving '%s'", path); goto cleanup_and_exit; } close(src_fd); } } #endif /* Perform crash-time unwind of the guilty thread. */ if (tid > 0 && setting_CreateCoreBacktrace) create_core_backtrace(tid, executable, signal_no, dd); /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); dd = NULL; path[path_len] = '\0'; /* path now contains only directory name */ if (abrtd_running && setting_SaveContainerizedPackageData && containerized) { /* Do we really need to run rpm from core_pattern hook? */ sprintf(source_filename, "/proc/%lu/root", (long)pid); const char *cmd_args[6]; cmd_args[0] = BIN_DIR"/abrt-action-save-package-data"; cmd_args[1] = "-d"; cmd_args[2] = path; cmd_args[3] = "-r"; cmd_args[4] = source_filename; cmd_args[5] = NULL; pid_t pid = fork_execv_on_steroids(0, (char **)cmd_args, NULL, NULL, path, 0); int stat; safe_waitpid(pid, &stat, 0); } char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); if (core_size > 0) log_notice("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); if (abrtd_running) notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } err = 0; } else { /* We didn't create abrt dump, but may need to create compat coredump */ return create_user_core(user_core_fd, pid, ulimit_c); } cleanup_and_exit: if (dd) dd_delete(dd); if (user_core_fd >= 0) unlinkat(dirfd(proc_cwd), core_basename, /*only files*/0); if (proc_cwd != NULL) closedir(proc_cwd); return err; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_1673_0
crossvul-cpp_data_bad_436_1
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: pidfile utility. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include "logger.h" #include "pidfile.h" #include "main.h" #include "bitops.h" #include "utils.h" const char *pid_directory = PID_DIR PACKAGE; /* Create the directory for non-standard pid files */ void create_pid_dir(void) { if (mkdir(pid_directory, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) && errno != EEXIST) { log_message(LOG_INFO, "Unable to create directory %s", pid_directory); return; } } void remove_pid_dir(void) { if (rmdir(pid_directory) && errno != ENOTEMPTY && errno != EBUSY) log_message(LOG_INFO, "unlink of %s failed - error (%d) '%s'", pid_directory, errno, strerror(errno)); } /* Create the running daemon pidfile */ int pidfile_write(const char *pid_file, int pid) { FILE *pidfile = NULL; int pidfd = creat(pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (pidfd != -1) pidfile = fdopen(pidfd, "w"); if (!pidfile) { log_message(LOG_INFO, "pidfile_write : Cannot open %s pidfile", pid_file); return 0; } fprintf(pidfile, "%d\n", pid); fclose(pidfile); return 1; } /* Remove the running daemon pidfile */ void pidfile_rm(const char *pid_file) { unlink(pid_file); } /* return the daemon running state */ static int process_running(const char *pid_file) { FILE *pidfile = fopen(pid_file, "r"); pid_t pid = 0; int ret; /* No pidfile */ if (!pidfile) return 0; ret = fscanf(pidfile, "%d", &pid); fclose(pidfile); if (ret != 1) { log_message(LOG_INFO, "Error reading pid file %s", pid_file); pid = 0; pidfile_rm(pid_file); } /* What should we return - we don't know if it is running or not. */ if (!pid) return 1; /* If no process is attached to pidfile, remove it */ if (kill(pid, 0)) { log_message(LOG_INFO, "Remove a zombie pid file %s", pid_file); pidfile_rm(pid_file); return 0; } return 1; } /* Return parent process daemon state */ bool keepalived_running(unsigned long mode) { if (process_running(main_pidfile)) return true; #ifdef _WITH_VRRP_ if (__test_bit(DAEMON_VRRP, &mode) && process_running(vrrp_pidfile)) return true; #endif #ifdef _WITH_LVS_ if (__test_bit(DAEMON_CHECKERS, &mode) && process_running(checkers_pidfile)) return true; #endif #ifdef _WITH_BFD_ if (__test_bit(DAEMON_BFD, &mode) && process_running(bfd_pidfile)) return true; #endif return false; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_1
crossvul-cpp_data_bad_5487_2
/***************************************************************************** * * LOGGING.C - Log file functions for use with Nagios * * * License: * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * *****************************************************************************/ #include "../include/config.h" #include "../include/common.h" #include "../include/statusdata.h" #include "../include/macros.h" #include "../include/nagios.h" #include "../include/broker.h" #include <fcntl.h> static FILE *debug_file_fp; static FILE *log_fp; /******************************************************************/ /************************ LOGGING FUNCTIONS ***********************/ /******************************************************************/ /* write something to the console */ static void write_to_console(char *buffer) { /* should we print to the console? */ if(daemon_mode == FALSE) printf("%s\n", buffer); } /* write something to the log file, syslog, and possibly the console */ static void write_to_logs_and_console(char *buffer, unsigned long data_type, int display) { register int len = 0; register int x = 0; /* strip unnecessary newlines */ len = strlen(buffer); for(x = len - 1; x >= 0; x--) { if(buffer[x] == '\n') buffer[x] = '\x0'; else break; } /* write messages to the logs */ write_to_all_logs(buffer, data_type); /* write message to the console */ if(display == TRUE) { /* don't display warnings if we're just testing scheduling */ if(test_scheduling == TRUE && data_type == NSLOG_VERIFICATION_WARNING) return; write_to_console(buffer); } } /* The main logging function */ void logit(int data_type, int display, const char *fmt, ...) { va_list ap; char *buffer = NULL; va_start(ap, fmt); if(vasprintf(&buffer, fmt, ap) > 0) { write_to_logs_and_console(buffer, data_type, display); free(buffer); } va_end(ap); } /* write something to the log file and syslog facility */ int write_to_all_logs(char *buffer, unsigned long data_type) { /* write to syslog */ write_to_syslog(buffer, data_type); /* write to main log */ write_to_log(buffer, data_type, NULL); return OK; } /* write something to the log file and syslog facility */ static void write_to_all_logs_with_timestamp(char *buffer, unsigned long data_type, time_t *timestamp) { /* write to syslog */ write_to_syslog(buffer, data_type); /* write to main log */ write_to_log(buffer, data_type, timestamp); } static FILE *open_log_file(void) { if(log_fp) /* keep it open unless we rotate */ return log_fp; log_fp = fopen(log_file, "a+"); if(log_fp == NULL) { if (daemon_mode == FALSE) { printf("Warning: Cannot open log file '%s' for writing\n", log_file); } return NULL; } (void)fcntl(fileno(log_fp), F_SETFD, FD_CLOEXEC); return log_fp; } int fix_log_file_owner(uid_t uid, gid_t gid) { int r1 = 0, r2 = 0; if (!(log_fp = open_log_file())) return -1; r1 = fchown(fileno(log_fp), uid, gid); if (open_debug_log() != OK) return -1; if (debug_file_fp) r2 = fchown(fileno(debug_file_fp), uid, gid); /* return 0 if both are 0 and otherwise < 0 */ return r1 < r2 ? r1 : r2; } int close_log_file(void) { if(!log_fp) return 0; fflush(log_fp); fclose(log_fp); log_fp = NULL; return 0; } /* write something to the nagios log file */ int write_to_log(char *buffer, unsigned long data_type, time_t *timestamp) { FILE *fp; time_t log_time = 0L; if(buffer == NULL) return ERROR; /* don't log anything if we're not actually running... */ if(verify_config || test_scheduling == TRUE) return OK; /* make sure we can log this type of entry */ if(!(data_type & logging_options)) return OK; fp = open_log_file(); if (fp == NULL) return ERROR; /* what timestamp should we use? */ if(timestamp == NULL) time(&log_time); else log_time = *timestamp; /* strip any newlines from the end of the buffer */ strip(buffer); /* write the buffer to the log file */ fprintf(fp, "[%llu] %s\n", (unsigned long long)log_time, buffer); fflush(fp); #ifdef USE_EVENT_BROKER /* send data to the event broker */ broker_log_data(NEBTYPE_LOG_DATA, NEBFLAG_NONE, NEBATTR_NONE, buffer, data_type, log_time, NULL); #endif return OK; } /* write something to the syslog facility */ int write_to_syslog(char *buffer, unsigned long data_type) { if(buffer == NULL) return ERROR; /* don't log anything if we're not actually running... */ if(verify_config || test_scheduling == TRUE) return OK; /* bail out if we shouldn't write to syslog */ if(use_syslog == FALSE) return OK; /* make sure we should log this type of entry */ if(!(data_type & syslog_options)) return OK; /* write the buffer to the syslog facility */ syslog(LOG_USER | LOG_INFO, "%s", buffer); return OK; } /* write a service problem/recovery to the nagios log file */ int log_service_event(service *svc) { char *temp_buffer = NULL; unsigned long log_options = 0L; host *temp_host = NULL; /* don't log soft errors if the user doesn't want to */ if(svc->state_type == SOFT_STATE && !log_service_retries) return OK; /* get the log options */ if(svc->current_state == STATE_UNKNOWN) log_options = NSLOG_SERVICE_UNKNOWN; else if(svc->current_state == STATE_WARNING) log_options = NSLOG_SERVICE_WARNING; else if(svc->current_state == STATE_CRITICAL) log_options = NSLOG_SERVICE_CRITICAL; else log_options = NSLOG_SERVICE_OK; /* find the associated host */ if((temp_host = svc->host_ptr) == NULL) return ERROR; asprintf(&temp_buffer, "SERVICE ALERT: %s;%s;%s;%s;%d;%s\n", svc->host_name, svc->description, service_state_name(svc->current_state), state_type_name(svc->state_type), svc->current_attempt, (svc->plugin_output == NULL) ? "" : svc->plugin_output); write_to_all_logs(temp_buffer, log_options); free(temp_buffer); return OK; } /* write a host problem/recovery to the log file */ int log_host_event(host *hst) { char *temp_buffer = NULL; unsigned long log_options = 0L; /* get the log options */ if(hst->current_state == HOST_DOWN) log_options = NSLOG_HOST_DOWN; else if(hst->current_state == HOST_UNREACHABLE) log_options = NSLOG_HOST_UNREACHABLE; else log_options = NSLOG_HOST_UP; asprintf(&temp_buffer, "HOST ALERT: %s;%s;%s;%d;%s\n", hst->name, host_state_name(hst->current_state), state_type_name(hst->state_type), hst->current_attempt, (hst->plugin_output == NULL) ? "" : hst->plugin_output); write_to_all_logs(temp_buffer, log_options); my_free(temp_buffer); return OK; } /* logs host states */ int log_host_states(int type, time_t *timestamp) { char *temp_buffer = NULL; host *temp_host = NULL;; /* bail if we shouldn't be logging initial states */ if(type == INITIAL_STATES && log_initial_states == FALSE) return OK; for(temp_host = host_list; temp_host != NULL; temp_host = temp_host->next) { asprintf(&temp_buffer, "%s HOST STATE: %s;%s;%s;%d;%s\n", (type == INITIAL_STATES) ? "INITIAL" : "CURRENT", temp_host->name, host_state_name(temp_host->current_state), state_type_name(temp_host->state_type), temp_host->current_attempt, (temp_host->plugin_output == NULL) ? "" : temp_host->plugin_output); write_to_all_logs_with_timestamp(temp_buffer, NSLOG_INFO_MESSAGE, timestamp); my_free(temp_buffer); } return OK; } /* logs service states */ int log_service_states(int type, time_t *timestamp) { char *temp_buffer = NULL; service *temp_service = NULL; host *temp_host = NULL;; /* bail if we shouldn't be logging initial states */ if(type == INITIAL_STATES && log_initial_states == FALSE) return OK; for(temp_service = service_list; temp_service != NULL; temp_service = temp_service->next) { /* find the associated host */ if((temp_host = temp_service->host_ptr) == NULL) continue; asprintf(&temp_buffer, "%s SERVICE STATE: %s;%s;%s;%s;%d;%s\n", (type == INITIAL_STATES) ? "INITIAL" : "CURRENT", temp_service->host_name, temp_service->description, service_state_name(temp_service->current_state), state_type_name(temp_service->state_type), temp_service->current_attempt, temp_service->plugin_output); write_to_all_logs_with_timestamp(temp_buffer, NSLOG_INFO_MESSAGE, timestamp); my_free(temp_buffer); } return OK; } /* rotates the main log file */ int rotate_log_file(time_t rotation_time) { char *temp_buffer = NULL; char method_string[16] = ""; char *log_archive = NULL; struct tm *t, tm_s; int rename_result = 0; int stat_result = -1; struct stat log_file_stat; struct stat archive_stat; int archive_stat_result; if(log_rotation_method == LOG_ROTATION_NONE) { return OK; } else if(log_rotation_method == LOG_ROTATION_HOURLY) strcpy(method_string, "HOURLY"); else if(log_rotation_method == LOG_ROTATION_DAILY) strcpy(method_string, "DAILY"); else if(log_rotation_method == LOG_ROTATION_WEEKLY) strcpy(method_string, "WEEKLY"); else if(log_rotation_method == LOG_ROTATION_MONTHLY) strcpy(method_string, "MONTHLY"); else return ERROR; /* update the last log rotation time and status log */ last_log_rotation = time(NULL); update_program_status(FALSE); t = localtime_r(&rotation_time, &tm_s); stat_result = stat(log_file, &log_file_stat); close_log_file(); /* get the archived filename to use */ asprintf(&log_archive, "%s%snagios-%02d-%02d-%d-%02d.log", log_archive_path, (log_archive_path[strlen(log_archive_path) - 1] == '/') ? "" : "/", t->tm_mon + 1, t->tm_mday, t->tm_year + 1900, t->tm_hour); /* HACK: If the archive exists, don't overwrite it. This is a hack because the real problem is that some log rotations are executed early and as a result the next log rotatation is scheduled for the same time as the one that ran early */ archive_stat_result = stat(log_archive, &archive_stat); if((0 == archive_stat_result) || ((-1 == archive_stat_result) && (ENOENT != errno))) { return OK; } /* rotate the log file */ rename_result = my_rename(log_file, log_archive); log_fp = open_log_file(); if (log_fp == NULL) return ERROR; if(rename_result) { my_free(log_archive); return ERROR; } /* record the log rotation after it has been done... */ asprintf(&temp_buffer, "LOG ROTATION: %s\n", method_string); write_to_all_logs_with_timestamp(temp_buffer, NSLOG_PROCESS_INFO, &rotation_time); my_free(temp_buffer); /* record log file version format */ write_log_file_info(&rotation_time); if(stat_result == 0) { chmod(log_file, log_file_stat.st_mode); chown(log_file, log_file_stat.st_uid, log_file_stat.st_gid); } /* log current host and service state if activated */ if(log_current_states==TRUE) { log_host_states(CURRENT_STATES, &rotation_time); log_service_states(CURRENT_STATES, &rotation_time); } /* free memory */ my_free(log_archive); return OK; } /* record log file version/info */ int write_log_file_info(time_t *timestamp) { char *temp_buffer = NULL; /* write log version */ asprintf(&temp_buffer, "LOG VERSION: %s\n", LOG_VERSION_2); write_to_all_logs_with_timestamp(temp_buffer, NSLOG_PROCESS_INFO, timestamp); my_free(temp_buffer); return OK; } /* opens the debug log for writing */ int open_debug_log(void) { /* don't do anything if we're not actually running... */ if(verify_config || test_scheduling == TRUE) return OK; /* don't do anything if we're not debugging */ if(debug_level == DEBUGL_NONE) return OK; if((debug_file_fp = fopen(debug_file, "a+")) == NULL) return ERROR; (void)fcntl(fileno(debug_file_fp), F_SETFD, FD_CLOEXEC); return OK; } /* closes the debug log */ int close_debug_log(void) { if(debug_file_fp != NULL) fclose(debug_file_fp); debug_file_fp = NULL; return OK; } /* write to the debug log */ int log_debug_info(int level, int verbosity, const char *fmt, ...) { va_list ap; char *tmppath = NULL; struct timeval current_time; if(!(debug_level == DEBUGL_ALL || (level & debug_level))) return OK; if(verbosity > debug_verbosity) return OK; if(debug_file_fp == NULL) return ERROR; /* write the timestamp */ gettimeofday(&current_time, NULL); fprintf(debug_file_fp, "[%lu.%06lu] [%03d.%d] [pid=%lu] ", current_time.tv_sec, current_time.tv_usec, level, verbosity, (unsigned long)getpid()); /* write the data */ va_start(ap, fmt); vfprintf(debug_file_fp, fmt, ap); va_end(ap); /* flush, so we don't have problems tailing or when fork()ing */ fflush(debug_file_fp); /* if file has grown beyond max, rotate it */ if((unsigned long)ftell(debug_file_fp) > max_debug_file_size && max_debug_file_size > 0L) { /* close the file */ close_debug_log(); /* rotate the log file */ asprintf(&tmppath, "%s.old", debug_file); if(tmppath) { /* unlink the old debug file */ unlink(tmppath); /* rotate the debug file */ my_rename(debug_file, tmppath); /* free memory */ my_free(tmppath); } /* open a new file */ open_debug_log(); } return OK; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_5487_2
crossvul-cpp_data_bad_3263_0
/* * ProFTPD - FTP server daemon * Copyright (c) 1997, 1998 Public Flood Software * Copyright (c) 1999, 2000 MacGyver aka Habeeb J. Dihu <macgyver@tos.net> * Copyright (c) 2001-2017 The ProFTPD Project team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. * * As a special exemption, Public Flood Software/MacGyver aka Habeeb J. Dihu * and other respective copyright holders give permission to link this program * with OpenSSL, and distribute the resulting executable, without including * the source code for OpenSSL in the source distribution. */ /* Authentication module for ProFTPD */ #include "conf.h" #include "privs.h" #ifdef HAVE_USERSEC_H # include <usersec.h> #endif #ifdef HAVE_SYS_AUDIT_H # include <sys/audit.h> #endif extern pid_t mpid; module auth_module; #ifdef PR_USE_LASTLOG static unsigned char lastlog = FALSE; #endif /* PR_USE_LASTLOG */ static unsigned char mkhome = FALSE; static unsigned char authenticated_without_pass = FALSE; static int TimeoutLogin = PR_TUNABLE_TIMEOUTLOGIN; static int logged_in = FALSE; static int auth_anon_allow_robots = FALSE; static int auth_anon_allow_robots_enabled = FALSE; static int auth_client_connected = FALSE; static unsigned int auth_tries = 0; static char *auth_pass_resp_code = R_230; static pr_fh_t *displaylogin_fh = NULL; static int TimeoutSession = 0; static int saw_first_user_cmd = FALSE; static const char *timing_channel = "timing"; static int auth_count_scoreboard(cmd_rec *, const char *); static int auth_scan_scoreboard(void); static int auth_sess_init(void); /* auth_cmd_chk_cb() is hooked into the main server's auth_hook function, * so that we can deny all commands until authentication is complete. * * Note: Once this function returns true (i.e. client has authenticated), * it will ALWAYS return true. At least until REIN is implemented. Thus * we have a flag for such a situation, to save on redundant lookups for * the "authenticated" record. */ static int auth_have_authenticated = FALSE; static int auth_cmd_chk_cb(cmd_rec *cmd) { if (auth_have_authenticated == FALSE) { unsigned char *authd; authd = get_param_ptr(cmd->server->conf, "authenticated", FALSE); if (authd == NULL || *authd == FALSE) { pr_response_send(R_530, _("Please login with USER and PASS")); return FALSE; } auth_have_authenticated = TRUE; } return TRUE; } static int auth_login_timeout_cb(CALLBACK_FRAME) { pr_response_send_async(R_421, _("Login timeout (%d %s): closing control connection"), TimeoutLogin, TimeoutLogin != 1 ? "seconds" : "second"); /* It's possible that any listeners of this event might terminate the * session process themselves (e.g. mod_ban). So write out that the * TimeoutLogin has been exceeded to the log here, in addition to the * scheduled session exit message. */ pr_log_pri(PR_LOG_INFO, "%s", "Login timeout exceeded, disconnected"); pr_event_generate("core.timeout-login", NULL); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT, "TimeoutLogin"); /* Do not restart the timer (should never be reached). */ return 0; } static int auth_session_timeout_cb(CALLBACK_FRAME) { pr_event_generate("core.timeout-session", NULL); pr_response_send_async(R_421, _("Session Timeout (%d seconds): closing control connection"), TimeoutSession); pr_log_pri(PR_LOG_INFO, "%s", "FTP session timed out, disconnected"); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT, "TimeoutSession"); /* no need to restart the timer -- session's over */ return 0; } /* Event listeners */ static void auth_exit_ev(const void *event_data, void *user_data) { pr_auth_cache_clear(); /* Close the scoreboard descriptor that we opened. */ (void) pr_close_scoreboard(FALSE); } static void auth_sess_reinit_ev(const void *event_data, void *user_data) { int res; /* A HOST command changed the main_server pointer, reinitialize ourselves. */ pr_event_unregister(&auth_module, "core.exit", auth_exit_ev); pr_event_unregister(&auth_module, "core.session-reinit", auth_sess_reinit_ev); pr_timer_remove(PR_TIMER_LOGIN, &auth_module); /* Reset the CreateHome setting. */ mkhome = FALSE; /* Reset any MaxPasswordSize setting. */ (void) pr_auth_set_max_password_len(session.pool, 0); #if defined(PR_USE_LASTLOG) lastlog = FALSE; #endif /* PR_USE_LASTLOG */ mkhome = FALSE; res = auth_sess_init(); if (res < 0) { pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_SESSION_INIT_FAILED, NULL); } } /* Initialization functions */ static int auth_init(void) { /* Add the commands handled by this module to the HELP list. */ pr_help_add(C_USER, _("<sp> username"), TRUE); pr_help_add(C_PASS, _("<sp> password"), TRUE); pr_help_add(C_ACCT, _("is not implemented"), FALSE); pr_help_add(C_REIN, _("is not implemented"), FALSE); /* By default, enable auth checking */ set_auth_check(auth_cmd_chk_cb); return 0; } static int auth_sess_init(void) { config_rec *c = NULL; unsigned char *tmp = NULL; pr_event_register(&auth_module, "core.session-reinit", auth_sess_reinit_ev, NULL); /* Check for any MaxPasswordSize. */ c = find_config(main_server->conf, CONF_PARAM, "MaxPasswordSize", FALSE); if (c != NULL) { size_t len; len = *((size_t *) c->argv[0]); (void) pr_auth_set_max_password_len(session.pool, len); } /* Check for a server-specific TimeoutLogin */ c = find_config(main_server->conf, CONF_PARAM, "TimeoutLogin", FALSE); if (c != NULL) { TimeoutLogin = *((int *) c->argv[0]); } /* Start the login timer */ if (TimeoutLogin) { pr_timer_remove(PR_TIMER_LOGIN, &auth_module); pr_timer_add(TimeoutLogin, PR_TIMER_LOGIN, &auth_module, auth_login_timeout_cb, "TimeoutLogin"); } if (auth_client_connected == FALSE) { int res = 0; PRIVS_ROOT res = pr_open_scoreboard(O_RDWR); PRIVS_RELINQUISH if (res < 0) { switch (res) { case PR_SCORE_ERR_BAD_MAGIC: pr_log_debug(DEBUG0, "error opening scoreboard: bad/corrupted file"); break; case PR_SCORE_ERR_OLDER_VERSION: pr_log_debug(DEBUG0, "error opening scoreboard: bad version (too old)"); break; case PR_SCORE_ERR_NEWER_VERSION: pr_log_debug(DEBUG0, "error opening scoreboard: bad version (too new)"); break; default: pr_log_debug(DEBUG0, "error opening scoreboard: %s", strerror(errno)); break; } } } pr_event_register(&auth_module, "core.exit", auth_exit_ev, NULL); if (auth_client_connected == FALSE) { /* Create an entry in the scoreboard for this session, if we don't already * have one. */ if (pr_scoreboard_entry_get(PR_SCORE_CLIENT_ADDR) == NULL) { if (pr_scoreboard_entry_add() < 0) { pr_log_pri(PR_LOG_NOTICE, "notice: unable to add scoreboard entry: %s", strerror(errno)); } pr_scoreboard_entry_update(session.pid, PR_SCORE_USER, "(none)", PR_SCORE_SERVER_PORT, main_server->ServerPort, PR_SCORE_SERVER_ADDR, session.c->local_addr, session.c->local_port, PR_SCORE_SERVER_LABEL, main_server->ServerName, PR_SCORE_CLIENT_ADDR, session.c->remote_addr, PR_SCORE_CLIENT_NAME, session.c->remote_name, PR_SCORE_CLASS, session.conn_class ? session.conn_class->cls_name : "", PR_SCORE_PROTOCOL, "ftp", PR_SCORE_BEGIN_SESSION, time(NULL), NULL); } } else { /* We're probably handling a HOST comand, and the server changed; just * update the SERVER_LABEL field. */ pr_scoreboard_entry_update(session.pid, PR_SCORE_SERVER_LABEL, main_server->ServerName, NULL); } /* Should we create the home for a user, if they don't have one? */ tmp = get_param_ptr(main_server->conf, "CreateHome", FALSE); if (tmp != NULL && *tmp == TRUE) { mkhome = TRUE; } else { mkhome = FALSE; } #ifdef PR_USE_LASTLOG /* Use the lastlog file, if supported and requested. */ tmp = get_param_ptr(main_server->conf, "UseLastlog", FALSE); if (tmp && *tmp == TRUE) { lastlog = TRUE; } else { lastlog = FALSE; } #endif /* PR_USE_LASTLOG */ /* Scan the scoreboard now, in order to tally up certain values for * substituting in any of the Display* file variables. This function * also performs the MaxConnectionsPerHost enforcement. */ auth_scan_scoreboard(); auth_client_connected = TRUE; return 0; } static int do_auth(pool *p, xaset_t *conf, const char *u, char *pw) { char *cpw = NULL; config_rec *c; if (conf != NULL) { c = find_config(conf, CONF_PARAM, "UserPassword", FALSE); while (c != NULL) { pr_signals_handle(); if (strcmp(c->argv[0], u) == 0) { cpw = (char *) c->argv[1]; break; } c = find_config_next(c, c->next, CONF_PARAM, "UserPassword", FALSE); } } if (cpw != NULL) { if (pr_auth_getpwnam(p, u) == NULL) { int xerrno = errno; if (xerrno == ENOENT) { pr_log_pri(PR_LOG_NOTICE, "no such user '%s'", u); } errno = xerrno; return PR_AUTH_NOPWD; } return pr_auth_check(p, cpw, u, pw); } return pr_auth_authenticate(p, u, pw); } /* Command handlers */ static void login_failed(pool *p, const char *user) { #ifdef HAVE_LOGINFAILED const char *host, *sess_ttyname; int res, xerrno; host = pr_netaddr_get_dnsstr(session.c->remote_addr); sess_ttyname = pr_session_get_ttyname(p); PRIVS_ROOT res = loginfailed((char *) user, (char *) host, (char *) sess_ttyname, AUDIT_FAIL); xerrno = errno; PRIVS_RELINQUISH if (res < 0) { pr_trace_msg("auth", 3, "AIX loginfailed() error for user '%s', " "host '%s', tty '%s', reason %d: %s", user, host, sess_ttyname, AUDIT_FAIL, strerror(errno)); } #endif /* HAVE_LOGINFAILED */ } MODRET auth_err_pass(cmd_rec *cmd) { const char *user; user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (user != NULL) { login_failed(cmd->tmp_pool, user); } /* Remove the stashed original USER name here in a LOG_CMD_ERR handler, so * that other modules, who may want to lookup the original USER parameter on * a failed login in an earlier command handler phase, have a chance to do * so. This removal of the USER parameter on failure was happening directly * in the CMD handler previously, thus preventing POST_CMD_ERR handlers from * using USER. */ pr_table_remove(session.notes, "mod_auth.orig-user", NULL); return PR_HANDLED(cmd); } MODRET auth_log_pass(cmd_rec *cmd) { /* Only log, to the syslog, that the login has succeeded here, where we * know that the login has definitely succeeded. */ pr_log_auth(PR_LOG_INFO, "%s %s: Login successful.", (session.anon_config != NULL) ? "ANON" : C_USER, session.user); if (cmd->arg != NULL) { size_t passwd_len; /* And scrub the memory holding the password sent by the client, for * safety/security. */ passwd_len = strlen(cmd->arg); pr_memscrub(cmd->arg, passwd_len); } return PR_DECLINED(cmd); } static void login_succeeded(pool *p, const char *user) { #ifdef HAVE_LOGINSUCCESS const char *host, *sess_ttyname; char *msg = NULL; int res, xerrno; host = pr_netaddr_get_dnsstr(session.c->remote_addr); sess_ttyname = pr_session_get_ttyname(p); PRIVS_ROOT res = loginsuccess((char *) user, (char *) host, (char *) sess_ttyname, &msg); xerrno = errno; PRIVS_RELINQUISH if (res == 0) { if (msg != NULL) { pr_trace_msg("auth", 14, "AIX loginsuccess() report: %s", msg); } } else { pr_trace_msg("auth", 3, "AIX loginsuccess() error for user '%s', " "host '%s', tty '%s': %s", user, host, sess_ttyname, strerror(errno)); } if (msg != NULL) { free(msg); } #endif /* HAVE_LOGINSUCCESS */ } MODRET auth_post_pass(cmd_rec *cmd) { config_rec *c = NULL; const char *grantmsg = NULL, *user; unsigned int ctxt_precedence = 0; unsigned char have_user_timeout, have_group_timeout, have_class_timeout, have_all_timeout, *root_revoke = NULL, *authenticated; struct stat st; /* Was there a precending USER command? Was the client successfully * authenticated? */ authenticated = get_param_ptr(cmd->server->conf, "authenticated", FALSE); /* Clear the list of auth-only modules. */ pr_auth_clear_auth_only_modules(); if (authenticated != NULL && *authenticated == TRUE) { /* At this point, we can look up the Protocols config if the client * has been authenticated, which may have been tweaked via mod_ifsession's * user/group/class-specific sections. */ c = find_config(main_server->conf, CONF_PARAM, "Protocols", FALSE); if (c != NULL) { register unsigned int i; array_header *protocols; char **elts; const char *protocol; protocols = c->argv[0]; elts = protocols->elts; protocol = pr_session_get_protocol(PR_SESS_PROTO_FL_LOGOUT); /* We only want to check for 'ftp' in the configured Protocols list * if a) a RFC2228 mechanism (e.g. SSL or GSS) is not in use, and * b) an SSH protocol is not in use. */ if (session.rfc2228_mech == NULL && strncmp(protocol, "SSH2", 5) != 0) { int allow_ftp = FALSE; for (i = 0; i < protocols->nelts; i++) { char *proto; proto = elts[i]; if (proto != NULL) { if (strncasecmp(proto, "ftp", 4) == 0) { allow_ftp = TRUE; break; } } } if (!allow_ftp) { pr_log_debug(DEBUG0, "%s", "ftp protocol denied by Protocols config"); pr_response_send(R_530, "%s", _("Login incorrect.")); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by Protocols setting"); } } } } user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); /* Count up various quantities in the scoreboard, checking them against * the Max* limits to see if the session should be barred from going * any further. */ auth_count_scoreboard(cmd, session.user); /* Check for dynamic configuration. This check needs to be after the * setting of any possible anon_config, as that context may be allowed * or denied .ftpaccess-parsing separately from the containing server. */ if (pr_fsio_stat(session.cwd, &st) != -1) build_dyn_config(cmd->tmp_pool, session.cwd, &st, TRUE); have_user_timeout = have_group_timeout = have_class_timeout = have_all_timeout = FALSE; c = find_config(TOPLEVEL_CONF, CONF_PARAM, "TimeoutSession", FALSE); while (c != NULL) { pr_signals_handle(); if (c->argc == 3) { if (strncmp(c->argv[1], "user", 5) == 0) { if (pr_expr_eval_user_or((char **) &c->argv[2]) == TRUE) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_group_timeout = have_class_timeout = have_all_timeout = FALSE; have_user_timeout = TRUE; } } } else if (strncmp(c->argv[1], "group", 6) == 0) { if (pr_expr_eval_group_and((char **) &c->argv[2]) == TRUE) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_class_timeout = have_all_timeout = FALSE; have_group_timeout = TRUE; } } } else if (strncmp(c->argv[1], "class", 6) == 0) { if (session.conn_class != NULL && strcmp(session.conn_class->cls_name, c->argv[2]) == 0) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_group_timeout = have_all_timeout = FALSE; have_class_timeout = TRUE; } } } } else { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_group_timeout = have_class_timeout = FALSE; have_all_timeout = TRUE; } } c = find_config_next(c, c->next, CONF_PARAM, "TimeoutSession", FALSE); } /* If configured, start a session timer. The timer ID value for * session timers will not be #defined, as I think that is a bad approach. * A better mechanism would be to use the random timer ID generation, and * store the returned ID in order to later remove the timer. */ if (have_user_timeout || have_group_timeout || have_class_timeout || have_all_timeout) { pr_log_debug(DEBUG4, "setting TimeoutSession of %d seconds for current %s", TimeoutSession, have_user_timeout ? "user" : have_group_timeout ? "group" : have_class_timeout ? "class" : "all"); pr_timer_add(TimeoutSession, PR_TIMER_SESSION, &auth_module, auth_session_timeout_cb, "TimeoutSession"); } /* Handle a DisplayLogin file. */ if (displaylogin_fh) { if (!(session.sf_flags & SF_ANON)) { if (pr_display_fh(displaylogin_fh, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin_fh->fh_path, strerror(errno)); } pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } else { /* We're an <Anonymous> login, but there was a previous DisplayLogin * configured which was picked up earlier. Close that filehandle, * and look for a new one. */ char *displaylogin; pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin) { if (pr_display_file(displaylogin, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } } } } else { char *displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin) { if (pr_display_file(displaylogin, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } } } grantmsg = get_param_ptr(TOPLEVEL_CONF, "AccessGrantMsg", FALSE); if (grantmsg == NULL) { /* Append the final greeting lines. */ if (session.sf_flags & SF_ANON) { pr_response_add(auth_pass_resp_code, "%s", _("Anonymous access granted, restrictions apply")); } else { pr_response_add(auth_pass_resp_code, _("User %s logged in"), user); } } else { /* Handle any AccessGrantMsg directive. */ grantmsg = sreplace(cmd->tmp_pool, grantmsg, "%u", user, NULL); pr_response_add(auth_pass_resp_code, "%s", grantmsg); } login_succeeded(cmd->tmp_pool, user); /* A RootRevoke value of 0 indicates 'false', 1 indicates 'true', and * 2 indicates 'NonCompliantActiveTransfer'. We will drop root privs for any * RootRevoke value greater than 0. */ root_revoke = get_param_ptr(TOPLEVEL_CONF, "RootRevoke", FALSE); if (root_revoke != NULL && *root_revoke > 0) { pr_signals_block(); PRIVS_ROOT PRIVS_REVOKE pr_signals_unblock(); /* Disable future attempts at UID/GID manipulation. */ session.disable_id_switching = TRUE; if (*root_revoke == 1) { /* If the server's listening port is less than 1024, block PORT * commands (effectively allowing only passive connections, which is * not necessarily a Bad Thing). Only log this here -- the blocking * will need to occur in mod_core's handling of the PORT/EPRT commands. */ if (session.c->local_port < 1024) { pr_log_debug(DEBUG0, "RootRevoke in effect, active data transfers may not succeed"); } } pr_log_debug(DEBUG0, "RootRevoke in effect, dropped root privs"); } c = find_config(TOPLEVEL_CONF, CONF_PARAM, "AnonAllowRobots", FALSE); if (c != NULL) { auth_anon_allow_robots = *((int *) c->argv[0]); } return PR_DECLINED(cmd); } /* Handle group based authentication, only checked if pw based fails. */ static config_rec *auth_group(pool *p, const char *user, char **group, char **ournamep, char **anonnamep, char *pass) { config_rec *c; char *ourname = NULL, *anonname = NULL; char **grmem; struct group *grp; ourname = get_param_ptr(main_server->conf, "UserName", FALSE); if (ournamep != NULL && ourname != NULL) { *ournamep = ourname; } c = find_config(main_server->conf, CONF_PARAM, "GroupPassword", TRUE); if (c) do { grp = pr_auth_getgrnam(p, c->argv[0]); if (grp == NULL) { continue; } for (grmem = grp->gr_mem; *grmem; grmem++) { if (strcmp(*grmem, user) == 0) { if (pr_auth_check(p, c->argv[1], user, pass) == 0) { break; } } } if (*grmem) { if (group != NULL) { *group = c->argv[0]; } if (c->parent != NULL) { c = c->parent; } if (c->config_type == CONF_ANON) { anonname = get_param_ptr(c->subset, "UserName", FALSE); } if (anonnamep != NULL) { *anonnamep = anonname; } if (anonnamep != NULL && !anonname && ourname != NULL) { *anonnamep = ourname; } break; } } while((c = find_config_next(c, c->next, CONF_PARAM, "GroupPassword", TRUE)) != NULL); return c; } /* Determine any applicable chdirs. */ static const char *get_default_chdir(pool *p, xaset_t *conf) { config_rec *c; const char *dir = NULL; c = find_config(conf, CONF_PARAM, "DefaultChdir", FALSE); while (c != NULL) { int res; pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultChdir", FALSE); } /* If the directory is relative, concatenate w/ session.cwd. */ if (dir != NULL && *dir != '/' && *dir != '~') { dir = pdircat(p, session.cwd, dir, NULL); } /* Check for any expandable variables. */ if (dir != NULL) { dir = path_subst_uservar(p, &dir); } return dir; } /* Determine if the user (non-anon) needs a default root dir other than /. */ static int get_default_root(pool *p, int allow_symlinks, const char **root) { config_rec *c = NULL; const char *dir = NULL; int res; c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE); while (c != NULL) { pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE); } if (dir != NULL) { const char *new_dir; /* Check for any expandable variables. */ new_dir = path_subst_uservar(p, &dir); if (new_dir != NULL) { dir = new_dir; } if (strncmp(dir, "/", 2) == 0) { dir = NULL; } else { char *realdir; int xerrno = 0; if (allow_symlinks == FALSE) { char *path, target_path[PR_TUNABLE_PATH_MAX + 1]; struct stat st; size_t pathlen; /* First, deal with any possible interpolation. dir_realpath() will * do this for us, but dir_realpath() ALSO automatically follows * symlinks, which is what we do NOT want to do here. */ path = pstrdup(p, dir); if (*path != '/') { if (*path == '~') { if (pr_fs_interpolate(dir, target_path, sizeof(target_path)-1) < 0) { return -1; } path = target_path; } } /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ pathlen = strlen(path); if (pathlen > 1 && path[pathlen-1] == '/') { path[pathlen-1] = '\0'; } pr_fs_clear_cache2(path); res = pr_fsio_lstat(path, &st); if (res < 0) { xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path, strerror(xerrno)); errno = xerrno; return -1; } if (S_ISLNK(st.st_mode)) { pr_log_pri(PR_LOG_WARNING, "error: DefaultRoot %s is a symlink (denied by AllowChrootSymlinks " "config)", path); errno = EPERM; return -1; } } /* We need to be the final user here so that if the user has their home * directory with a mode the user proftpd is running (i.e. the User * directive) as can not traverse down, we can still have the default * root. */ pr_fs_clear_cache2(dir); PRIVS_USER realdir = dir_realpath(p, dir); xerrno = errno; PRIVS_RELINQUISH if (realdir) { dir = realdir; } else { /* Try to provide a more informative message. */ char interp_dir[PR_TUNABLE_PATH_MAX + 1]; memset(interp_dir, '\0', sizeof(interp_dir)); (void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1); pr_log_pri(PR_LOG_NOTICE, "notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s", dir, interp_dir, strerror(xerrno)); errno = xerrno; } } } *root = dir; return 0; } static struct passwd *passwd_dup(pool *p, struct passwd *pw) { struct passwd *npw; npw = pcalloc(p, sizeof(struct passwd)); npw->pw_name = pstrdup(p, pw->pw_name); npw->pw_passwd = pstrdup(p, pw->pw_passwd); npw->pw_uid = pw->pw_uid; npw->pw_gid = pw->pw_gid; npw->pw_gecos = pstrdup(p, pw->pw_gecos); npw->pw_dir = pstrdup(p, pw->pw_dir); npw->pw_shell = pstrdup(p, pw->pw_shell); return npw; } static void ensure_open_passwd(pool *p) { /* Make sure pass/group is open. */ pr_auth_setpwent(p); pr_auth_setgrent(p); /* On some unices the following is necessary to ensure the files * are open (BSDI 3.1) */ pr_auth_getpwent(p); pr_auth_getgrent(p); /* Per Debian bug report: * https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=717235 * we might want to do another set{pw,gr}ent(), to play better with * some NSS modules. */ pr_auth_setpwent(p); pr_auth_setgrent(p); } /* Next function (the biggie) handles all authentication, setting * up chroot() jail, etc. */ static int setup_env(pool *p, cmd_rec *cmd, const char *user, char *pass) { struct passwd *pw; config_rec *c, *tmpc; const char *defchdir = NULL, *defroot = NULL, *origuser, *sess_ttyname; char *ourname = NULL, *anonname = NULL, *anongroup = NULL, *ugroup = NULL; char *xferlog = NULL; int aclp, i, res = 0, allow_chroot_symlinks = TRUE, showsymlinks; unsigned char *wtmp_log = NULL, *anon_require_passwd = NULL; /********************* Authenticate the user here *********************/ session.hide_password = TRUE; origuser = user; c = pr_auth_get_anon_config(p, &user, &ourname, &anonname); if (c != NULL) { session.anon_config = c; } if (user == NULL) { pr_log_auth(PR_LOG_NOTICE, "USER %s: user is not a UserAlias from %s [%s] " "to %s:%i", origuser, session.c->remote_name, pr_netaddr_get_ipstr(session.c->remote_addr), pr_netaddr_get_ipstr(session.c->local_addr), session.c->local_port); goto auth_failure; } pw = pr_auth_getpwnam(p, user); if (pw == NULL && c != NULL && ourname != NULL) { /* If the client is authenticating using an alias (e.g. "AuthAliasOnly on"), * then we need to try checking using the real username, too (Bug#4255). */ pr_trace_msg("auth", 16, "no user entry found for <Anonymous> alias '%s', using '%s'", user, ourname); pw = pr_auth_getpwnam(p, ourname); } if (pw == NULL) { int auth_code = PR_AUTH_NOPWD; pr_log_auth(PR_LOG_NOTICE, "USER %s: no such user found from %s [%s] to %s:%i", user, session.c->remote_name, pr_netaddr_get_ipstr(session.c->remote_addr), pr_netaddr_get_ipstr(session.c->local_addr), session.c->local_port); pr_event_generate("mod_auth.authentication-code", &auth_code); goto auth_failure; } /* Security: other functions perform pw lookups, thus we need to make * a local copy of the user just looked up. */ pw = passwd_dup(p, pw); if (pw->pw_uid == PR_ROOT_UID) { unsigned char *root_allow = NULL; pr_event_generate("mod_auth.root-login", NULL); /* If RootLogin is set to true, we allow this... even though we * still log a warning. :) */ if ((root_allow = get_param_ptr(c ? c->subset : main_server->conf, "RootLogin", FALSE)) == NULL || *root_allow != TRUE) { if (pass) { pr_memscrub(pass, strlen(pass)); } pr_log_auth(PR_LOG_NOTICE, "SECURITY VIOLATION: Root login attempted"); return 0; } } session.user = pstrdup(p, pw->pw_name); session.group = pstrdup(p, pr_auth_gid2name(p, pw->pw_gid)); /* Set the login_uid and login_uid */ session.login_uid = pw->pw_uid; session.login_gid = pw->pw_gid; /* Check for any expandable variables in session.cwd. */ pw->pw_dir = (char *) path_subst_uservar(p, (const char **) &pw->pw_dir); /* Before we check for supplemental groups, check to see if the locally * resolved name of the user, returned via auth_getpwnam(), is different * from the USER argument sent by the client. The name can change, since * auth modules can play all sorts of neat tricks on us. * * If the names differ, assume that any cached data in the session.gids * and session.groups lists are stale, and clear them out. */ if (strcmp(pw->pw_name, user) != 0) { pr_trace_msg("auth", 10, "local user name '%s' differs from client-sent " "user name '%s', clearing cached group data", pw->pw_name, user); session.gids = NULL; session.groups = NULL; } if (!session.gids && !session.groups) { /* Get the supplemental groups. Note that we only look up the * supplemental group credentials if we have not cached the group * credentials before, in session.gids and session.groups. * * Those credentials may have already been retrieved, as part of the * pr_auth_get_anon_config() call. */ res = pr_auth_getgroups(p, pw->pw_name, &session.gids, &session.groups); if (res < 1) { pr_log_debug(DEBUG5, "no supplemental groups found for user '%s'", pw->pw_name); } } tmpc = find_config(main_server->conf, CONF_PARAM, "AllowChrootSymlinks", FALSE); if (tmpc != NULL) { allow_chroot_symlinks = *((int *) tmpc->argv[0]); } /* If c != NULL from this point on, we have an anonymous login */ aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); if (c != NULL) { anongroup = get_param_ptr(c->subset, "GroupName", FALSE); if (anongroup == NULL) { anongroup = get_param_ptr(main_server->conf, "GroupName",FALSE); } #ifdef PR_USE_REGEX /* Check for configured AnonRejectPasswords regex here, and fail the login * if the given password matches the regex. */ tmpc = find_config(c->subset, CONF_PARAM, "AnonRejectPasswords", FALSE); if (tmpc != NULL) { int re_notmatch; pr_regex_t *pw_regex; pw_regex = (pr_regex_t *) tmpc->argv[0]; re_notmatch = *((int *) tmpc->argv[1]); if (pw_regex != NULL && pass != NULL) { int re_res; re_res = pr_regexp_exec(pw_regex, pass, 0, NULL, 0, 0, 0); if (re_res == 0 || (re_res != 0 && re_notmatch == TRUE)) { char errstr[200] = {'\0'}; pr_regexp_error(re_res, pw_regex, errstr, sizeof(errstr)); pr_log_auth(PR_LOG_NOTICE, "ANON %s: AnonRejectPasswords denies login", origuser); pr_event_generate("mod_auth.anon-reject-passwords", session.c); goto auth_failure; } } } #endif if (!login_check_limits(c->subset, FALSE, TRUE, &i) || (!aclp && !i) ){ pr_log_auth(PR_LOG_NOTICE, "ANON %s (Login failed): Limit access denies " "login", origuser); goto auth_failure; } } if (c == NULL && aclp == 0) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Limit access denies login", origuser); goto auth_failure; } if (c != NULL) { anon_require_passwd = get_param_ptr(c->subset, "AnonRequirePassword", FALSE); } if (c == NULL || (anon_require_passwd != NULL && *anon_require_passwd == TRUE)) { int auth_code; const char *user_name = user; if (c != NULL && origuser != NULL && strcasecmp(user, origuser) != 0) { unsigned char *auth_using_alias; auth_using_alias = get_param_ptr(c->subset, "AuthUsingAlias", FALSE); /* If 'AuthUsingAlias' set and we're logging in under an alias, * then auth using that alias. */ if (auth_using_alias && *auth_using_alias == TRUE) { user_name = origuser; pr_log_auth(PR_LOG_INFO, "ANON AUTH: User %s, authenticating using alias %s", user, user_name); } } /* It is possible for the user to have already been authenticated during * the handling of the USER command, as by an RFC2228 mechanism. If * that had happened, we won't need to call do_auth() here. */ if (!authenticated_without_pass) { auth_code = do_auth(p, c ? c->subset : main_server->conf, user_name, pass); } else { auth_code = PR_AUTH_OK_NO_PASS; } pr_event_generate("mod_auth.authentication-code", &auth_code); if (auth_code < 0) { /* Normal authentication has failed, see if group authentication * passes */ c = auth_group(p, user, &anongroup, &ourname, &anonname, pass); if (c != NULL) { if (c->config_type != CONF_ANON) { c = NULL; ugroup = anongroup; anongroup = NULL; } auth_code = PR_AUTH_OK; } } if (pass) pr_memscrub(pass, strlen(pass)); if (session.auth_mech) pr_log_debug(DEBUG2, "user '%s' authenticated by %s", user, session.auth_mech); switch (auth_code) { case PR_AUTH_OK_NO_PASS: auth_pass_resp_code = R_232; break; case PR_AUTH_OK: auth_pass_resp_code = R_230; break; case PR_AUTH_NOPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): No such user found", user); goto auth_failure; case PR_AUTH_BADPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Incorrect password", origuser); goto auth_failure; case PR_AUTH_AGEPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Password expired", user); goto auth_failure; case PR_AUTH_DISABLEDPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Account disabled", user); goto auth_failure; case PR_AUTH_CRED_INSUFFICIENT: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Insufficient credentials", user); goto auth_failure; case PR_AUTH_CRED_UNAVAIL: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Unavailable credentials", user); goto auth_failure; case PR_AUTH_CRED_ERROR: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Failure setting credentials", user); goto auth_failure; case PR_AUTH_INFO_UNAVAIL: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Unavailable authentication service", user); goto auth_failure; case PR_AUTH_MAX_ATTEMPTS_EXCEEDED: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Max authentication service attempts reached", user); goto auth_failure; case PR_AUTH_INIT_ERROR: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Failed initializing authentication service", user); goto auth_failure; case PR_AUTH_NEW_TOKEN_REQUIRED: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): New authentication token required", user); goto auth_failure; default: break; }; /* Catch the case where we forgot to handle a bad auth code above. */ if (auth_code < 0) goto auth_failure; if (pw->pw_uid == PR_ROOT_UID) { pr_log_auth(PR_LOG_WARNING, "ROOT FTP login successful"); } } else if (c && (!anon_require_passwd || *anon_require_passwd == FALSE)) { session.hide_password = FALSE; } pr_auth_setgrent(p); res = pr_auth_is_valid_shell(c ? c->subset : main_server->conf, pw->pw_shell); if (res == FALSE) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Invalid shell: '%s'", user, pw->pw_shell); goto auth_failure; } res = pr_auth_banned_by_ftpusers(c ? c->subset : main_server->conf, pw->pw_name); if (res == TRUE) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): User in " PR_FTPUSERS_PATH, user); goto auth_failure; } if (c) { struct group *grp = NULL; unsigned char *add_userdir = NULL; const char *u; char *chroot_dir; u = pr_table_get(session.notes, "mod_auth.orig-user", NULL); add_userdir = get_param_ptr(c->subset, "UserDirRoot", FALSE); /* If resolving an <Anonymous> user, make sure that user's groups * are set properly for the check of the home directory path (which * depend on those supplemental group memberships). Additionally, * temporarily switch to the new user's uid. */ pr_signals_block(); PRIVS_ROOT res = set_groups(p, pw->pw_gid, session.gids); if (res < 0) { if (errno != ENOSYS) { pr_log_pri(PR_LOG_WARNING, "error: unable to set groups: %s", strerror(errno)); } } #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(pw->pw_uid, pw->pw_gid) if ((add_userdir && *add_userdir == TRUE) && strcmp(u, user) != 0) { chroot_dir = pdircat(p, c->name, u, NULL); } else { chroot_dir = c->name; } if (allow_chroot_symlinks == FALSE) { char *chroot_path, target_path[PR_TUNABLE_PATH_MAX+1]; struct stat st; chroot_path = chroot_dir; if (chroot_path[0] != '/') { if (chroot_path[0] == '~') { if (pr_fs_interpolate(chroot_path, target_path, sizeof(target_path)-1) == 0) { chroot_path = target_path; } else { chroot_path = NULL; } } } if (chroot_path != NULL) { size_t chroot_pathlen; /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ chroot_pathlen = strlen(chroot_path); if (chroot_pathlen > 1 && chroot_path[chroot_pathlen-1] == '/') { chroot_path[chroot_pathlen-1] = '\0'; } pr_fs_clear_cache2(chroot_path); res = pr_fsio_lstat(chroot_path, &st); if (res < 0) { int xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", chroot_path, strerror(xerrno)); errno = xerrno; chroot_path = NULL; } else { if (S_ISLNK(st.st_mode)) { pr_log_pri(PR_LOG_WARNING, "error: <Anonymous %s> is a symlink (denied by " "AllowChrootSymlinks config)", chroot_path); errno = EPERM; chroot_path = NULL; } } } if (chroot_path != NULL) { session.chroot_path = dir_realpath(p, chroot_dir); } else { session.chroot_path = NULL; } if (session.chroot_path == NULL) { pr_log_debug(DEBUG8, "error resolving '%s': %s", chroot_dir, strerror(errno)); } } else { session.chroot_path = dir_realpath(p, chroot_dir); if (session.chroot_path == NULL) { pr_log_debug(DEBUG8, "error resolving '%s': %s", chroot_dir, strerror(errno)); } } if (session.chroot_path && pr_fsio_access(session.chroot_path, X_OK, session.uid, session.gid, session.gids) != 0) { session.chroot_path = NULL; } else { session.chroot_path = pstrdup(session.pool, session.chroot_path); } /* Return all privileges back to that of the daemon, for now. */ PRIVS_ROOT res = set_groups(p, daemon_gid, daemon_gids); if (res < 0) { if (errno != ENOSYS) { pr_log_pri(PR_LOG_ERR, "error: unable to set groups: %s", strerror(errno)); } } #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(daemon_uid, daemon_gid) pr_signals_unblock(); /* Sanity check, make sure we have daemon_uid and daemon_gid back */ #ifdef HAVE_GETEUID if (getegid() != daemon_gid || geteuid() != daemon_uid) { PRIVS_RELINQUISH pr_log_pri(PR_LOG_WARNING, "switching IDs from user %s back to daemon uid/gid failed: %s", session.user, strerror(errno)); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL); } #endif /* HAVE_GETEUID */ if (anon_require_passwd && *anon_require_passwd == TRUE) { session.anon_user = pstrdup(session.pool, origuser); } else { session.anon_user = pstrdup(session.pool, pass); } if (!session.chroot_path) { pr_log_pri(PR_LOG_NOTICE, "%s: Directory %s is not accessible", session.user, c->name); pr_response_add_err(R_530, _("Unable to set anonymous privileges.")); goto auth_failure; } sstrncpy(session.cwd, "/", sizeof(session.cwd)); xferlog = get_param_ptr(c->subset, "TransferLog", FALSE); if (anongroup) { grp = pr_auth_getgrnam(p, anongroup); if (grp) { pw->pw_gid = grp->gr_gid; session.group = pstrdup(p, grp->gr_name); } } } else { struct group *grp; char *homedir; if (ugroup) { grp = pr_auth_getgrnam(p, ugroup); if (grp) { pw->pw_gid = grp->gr_gid; session.group = pstrdup(p, grp->gr_name); } } /* Attempt to resolve any possible symlinks. */ PRIVS_USER homedir = dir_realpath(p, pw->pw_dir); PRIVS_RELINQUISH if (homedir) sstrncpy(session.cwd, homedir, sizeof(session.cwd)); else sstrncpy(session.cwd, pw->pw_dir, sizeof(session.cwd)); } /* Create the home directory, if need be. */ if (!c && mkhome) { if (create_home(p, session.cwd, origuser, pw->pw_uid, pw->pw_gid) < 0) { /* NOTE: should this cause the login to fail? */ goto auth_failure; } } /* Get default chdir (if any) */ defchdir = get_default_chdir(p, (c ? c->subset : main_server->conf)); if (defchdir != NULL) { sstrncpy(session.cwd, defchdir, sizeof(session.cwd)); } /* Check limits again to make sure deny/allow directives still permit * access. */ if (!login_check_limits((c ? c->subset : main_server->conf), FALSE, TRUE, &i)) { pr_log_auth(PR_LOG_NOTICE, "%s %s: Limit access denies login", (c != NULL) ? "ANON" : C_USER, origuser); goto auth_failure; } /* Perform a directory fixup. */ resolve_deferred_dirs(main_server); fixup_dirs(main_server, CF_DEFER); /* If running under an anonymous context, resolve all <Directory> * blocks inside it. */ if (c && c->subset) resolve_anonymous_dirs(c->subset); /* Write the login to wtmp. This must be done here because we won't * have access after we give up root. This can result in falsified * wtmp entries if an error kicks the user out before we get * through with the login process. Oh well. */ sess_ttyname = pr_session_get_ttyname(p); /* Perform wtmp logging only if not turned off in <Anonymous> * or the current server */ if (c) wtmp_log = get_param_ptr(c->subset, "WtmpLog", FALSE); if (wtmp_log == NULL) wtmp_log = get_param_ptr(main_server->conf, "WtmpLog", FALSE); /* As per Bug#3482, we need to disable WtmpLog for FreeBSD 9.0, as * an interim measure. * * The issue is that some platforms update multiple files for a single * pututxline(3) call; proftpd tries to update those files manually, * do to chroots (after which a pututxline(3) call will fail). A proper * solution requires a separate process, running with the correct * privileges, which would handle wtmp logging. The proftpd session * processes would send messages to this logging daemon (via Unix domain * socket, or FIFO, or TCP socket). * * Also note that this hack to disable WtmpLog may need to be extended * to other platforms in the future. */ #if defined(HAVE_UTMPX_H) && \ defined(__FreeBSD_version) && __FreeBSD_version >= 900007 if (wtmp_log == NULL || *wtmp_log == TRUE) { wtmp_log = pcalloc(p, sizeof(unsigned char)); *wtmp_log = FALSE; pr_log_debug(DEBUG5, "WtpmLog automatically disabled; see Bug#3482 for details"); } #endif PRIVS_ROOT if (wtmp_log == NULL || *wtmp_log == TRUE) { log_wtmp(sess_ttyname, session.user, session.c->remote_name, session.c->remote_addr); session.wtmp_log = TRUE; } #ifdef PR_USE_LASTLOG if (lastlog) { log_lastlog(pw->pw_uid, session.user, sess_ttyname, session.c->remote_addr); } #endif /* PR_USE_LASTLOG */ /* Open any TransferLogs */ if (!xferlog) { if (c) xferlog = get_param_ptr(c->subset, "TransferLog", FALSE); if (!xferlog) xferlog = get_param_ptr(main_server->conf, "TransferLog", FALSE); if (!xferlog) xferlog = PR_XFERLOG_PATH; } if (strcasecmp(xferlog, "NONE") == 0) { xferlog_open(NULL); } else { xferlog_open(xferlog); } res = set_groups(p, pw->pw_gid, session.gids); if (res < 0) { if (errno != ENOSYS) { pr_log_pri(PR_LOG_ERR, "error: unable to set groups: %s", strerror(errno)); } } PRIVS_RELINQUISH /* Now check to see if the user has an applicable DefaultRoot */ if (c == NULL) { if (get_default_root(session.pool, allow_chroot_symlinks, &defroot) < 0) { pr_log_pri(PR_LOG_NOTICE, "error: unable to determine DefaultRoot directory"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } ensure_open_passwd(p); if (defroot != NULL) { if (pr_auth_chroot(defroot) == -1) { pr_log_pri(PR_LOG_NOTICE, "error: unable to set DefaultRoot directory"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } /* Re-calc the new cwd based on this root dir. If not applicable * place the user in / (of defroot) */ if (strncmp(session.cwd, defroot, strlen(defroot)) == 0) { char *newcwd = &session.cwd[strlen(defroot)]; if (*newcwd == '/') newcwd++; session.cwd[0] = '/'; sstrncpy(&session.cwd[1], newcwd, sizeof(session.cwd)); } } } if (c) ensure_open_passwd(p); if (c && pr_auth_chroot(session.chroot_path) == -1) { pr_log_pri(PR_LOG_NOTICE, "error: unable to set anonymous privileges"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } /* new in 1.1.x, I gave in and we don't give up root permanently.. * sigh. */ PRIVS_ROOT #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(pw->pw_uid, pw->pw_gid) #ifdef HAVE_GETEUID if (getegid() != pw->pw_gid || geteuid() != pw->pw_uid) { PRIVS_RELINQUISH pr_log_pri(PR_LOG_ERR, "error: %s setregid() or setreuid(): %s", session.user, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } #endif /* If the home directory is NULL or "", reject the login. */ if (pw->pw_dir == NULL || strncmp(pw->pw_dir, "", 1) == 0) { pr_log_pri(PR_LOG_WARNING, "error: user %s home directory is NULL or \"\"", session.user); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } { unsigned char *show_symlinks = get_param_ptr( c ? c->subset : main_server->conf, "ShowSymlinks", FALSE); if (!show_symlinks || *show_symlinks == TRUE) showsymlinks = TRUE; else showsymlinks = FALSE; } /* chdir to the proper directory, do this even if anonymous * to make sure we aren't outside our chrooted space. */ /* Attempt to change to the correct directory -- use session.cwd first. * This will contain the DefaultChdir directory, if configured... */ if (pr_fsio_chdir_canon(session.cwd, !showsymlinks) == -1) { /* if we've got DefaultRoot or anonymous login, ignore this error * and chdir to / */ if (session.chroot_path != NULL || defroot) { pr_log_debug(DEBUG2, "unable to chdir to %s (%s), defaulting to chroot " "directory %s", session.cwd, strerror(errno), (session.chroot_path ? session.chroot_path : defroot)); if (pr_fsio_chdir_canon("/", !showsymlinks) == -1) { pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"/\") failed: %s", session.user, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } else if (defchdir) { /* If we've got defchdir, failure is ok as well, simply switch to * user's homedir. */ pr_log_debug(DEBUG2, "unable to chdir to %s (%s), defaulting to home " "directory %s", session.cwd, strerror(errno), pw->pw_dir); if (pr_fsio_chdir_canon(pw->pw_dir, !showsymlinks) == -1) { pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"%s\") failed: %s", session.user, session.cwd, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } else { /* Unable to switch to user's real home directory, which is not * allowed. */ pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"%s\") failed: %s", session.user, session.cwd, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } sstrncpy(session.cwd, pr_fs_getcwd(), sizeof(session.cwd)); sstrncpy(session.vwd, pr_fs_getvwd(), sizeof(session.vwd)); /* Make sure directory config pointers are set correctly */ dir_check_full(p, cmd, G_NONE, session.cwd, NULL); if (c) { if (!session.hide_password) { session.proc_prefix = pstrcat(session.pool, session.c->remote_name, ": anonymous/", pass, NULL); } else { session.proc_prefix = pstrcat(session.pool, session.c->remote_name, ": anonymous", NULL); } session.sf_flags = SF_ANON; } else { session.proc_prefix = pstrdup(session.pool, session.c->remote_name); session.sf_flags = 0; } /* While closing the pointer to the password database would avoid any * potential attempt to hijack this information, it is unfortunately needed * in a chroot()ed environment. Otherwise, mappings from UIDs to names, * among other things, would fail. */ /* pr_auth_endpwent(p); */ /* Authentication complete, user logged in, now kill the login * timer. */ /* Update the scoreboard entry */ pr_scoreboard_entry_update(session.pid, PR_SCORE_USER, session.user, PR_SCORE_CWD, session.cwd, NULL); pr_session_set_idle(); pr_timer_remove(PR_TIMER_LOGIN, &auth_module); /* These copies are made from the session.pool, instead of the more * volatile pool used originally, in order that the copied data maintain * its integrity for the lifetime of the session. */ session.user = pstrdup(session.pool, session.user); if (session.group) session.group = pstrdup(session.pool, session.group); if (session.gids) session.gids = copy_array(session.pool, session.gids); /* session.groups is an array of strings, so we must copy the string data * as well as the pointers. */ session.groups = copy_array_str(session.pool, session.groups); /* Resolve any deferred-resolution paths in the FS layer */ pr_resolve_fs_map(); return 1; auth_failure: if (pass) pr_memscrub(pass, strlen(pass)); session.user = session.group = NULL; session.gids = session.groups = NULL; session.wtmp_log = FALSE; return 0; } /* This function counts the number of connected users. It only fills in the * Class-based counters and an estimate for the number of clients. The primary * purpose is to make it so that the %N/%y escapes work in a DisplayConnect * greeting. A secondary purpose is to enforce any configured * MaxConnectionsPerHost limit. */ static int auth_scan_scoreboard(void) { char *key; void *v; config_rec *c = NULL; pr_scoreboard_entry_t *score = NULL; unsigned int cur = 0, ccur = 0, hcur = 0; char curr_server_addr[80] = {'\0'}; const char *client_addr = pr_netaddr_get_ipstr(session.c->remote_addr); snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; /* Determine how many users are currently connected */ if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { pr_signals_handle(); /* Make sure it matches our current server */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { cur++; if (strcmp(score->sce_client_addr, client_addr) == 0) hcur++; /* Only count up authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) continue; /* Note: the class member of the scoreboard entry will never be * NULL. At most, it may be the empty string. */ if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Lookup any configured MaxConnectionsPerHost. */ c = find_config(main_server->conf, CONF_PARAM, "MaxConnectionsPerHost", FALSE); if (c) { unsigned int *max = c->argv[0]; if (*max && hcur > *max) { char maxstr[20]; char *msg = "Sorry, the maximum number of connections (%m) for your host " "are already connected."; pr_event_generate("mod_auth.max-connections-per-host", session.c); if (c->argc == 2) msg = c->argv[1]; memset(maxstr, '\0', sizeof(maxstr)); snprintf(maxstr, sizeof(maxstr), "%u", *max); maxstr[sizeof(maxstr)-1] = '\0'; pr_response_send(R_530, "%s", sreplace(session.pool, msg, "%m", maxstr, NULL)); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxConnectionsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxConnectionsPerHost"); } } return 0; } static int have_client_limits(cmd_rec *cmd) { if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerClass", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE) != NULL) { return TRUE; } return FALSE; } static int auth_count_scoreboard(cmd_rec *cmd, const char *user) { char *key; void *v; pr_scoreboard_entry_t *score = NULL; long cur = 0, hcur = 0, ccur = 0, hostsperuser = 1, usersessions = 0; config_rec *c = NULL, *maxc = NULL; /* First, check to see which Max* directives are configured. If none * are configured, then there is no need for us to needlessly scan the * ScoreboardFile. */ if (have_client_limits(cmd) == FALSE) { return 0; } /* Determine how many users are currently connected. */ /* We use this call to get the possibly-changed user name. */ c = pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Gather our statistics. */ if (user != NULL) { char curr_server_addr[80] = {'\0'}; snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { unsigned char same_host = FALSE; pr_signals_handle(); /* Make sure it matches our current server. */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { if ((c != NULL && c->config_type == CONF_ANON && !strcmp(score->sce_user, user)) || c == NULL) { /* This small hack makes sure that cur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c != NULL && c->config_type == CONF_ANON && cur == 0) { cur = 1; } /* Only count authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) { continue; } cur++; /* Count up sessions on a per-host basis. */ if (!strcmp(score->sce_client_addr, pr_netaddr_get_ipstr(session.c->remote_addr))) { same_host = TRUE; /* This small hack makes sure that hcur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c != NULL && c->config_type == CONF_ANON && hcur == 0) { hcur = 1; } hcur++; } /* Take a per-user count of connections. */ if (strcmp(score->sce_user, user) == 0) { usersessions++; /* Count up unique hosts. */ if (!same_host) { hostsperuser++; } } } if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); PRIVS_RELINQUISH } key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Try to determine what MaxClients/MaxHosts limits apply to this session * (if any) and count through the runtime file to see if this limit would * be exceeded. */ maxc = find_config(cmd->server->conf, CONF_PARAM, "MaxClientsPerClass", FALSE); while (session.conn_class != NULL && maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your class " "are already connected."; unsigned int *max = maxc->argv[1]; if (strcmp(maxc->argv[0], session.conn_class->cls_name) != 0) { maxc = find_config_next(maxc, maxc->next, CONF_PARAM, "MaxClientsPerClass", FALSE); continue; } if (maxc->argc > 2) { maxstr = maxc->argv[2]; } if (*max && ccur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-class", session.conn_class->cls_name); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerClass %s %u)", session.conn_class->cls_name, *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerClass"); } break; } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your host " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && hcur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-host", session.c); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerHost"); } } /* Check for any configured MaxClientsPerUser. */ maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) for this user " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && usersessions > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerUser %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerUser"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of allowed clients (%m) are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && cur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients", NULL); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClients %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClients"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of hosts (%m) for this user are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && hostsperuser > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-hosts-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxHostsPerUser %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxHostsPerUser"); } } return 0; } MODRET auth_pre_user(cmd_rec *cmd) { if (saw_first_user_cmd == FALSE) { if (pr_trace_get_level(timing_channel)) { unsigned long elapsed_ms; uint64_t finish_ms; pr_gettimeofday_millis(&finish_ms); elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms); pr_trace_msg(timing_channel, 4, "Time before first USER: %lu ms", elapsed_ms); } saw_first_user_cmd = TRUE; } if (logged_in) { return PR_DECLINED(cmd); } /* Close the passwd and group databases, because libc won't let us see new * entries to these files without this (only in PersistentPasswd mode). */ pr_auth_endpwent(cmd->tmp_pool); pr_auth_endgrent(cmd->tmp_pool); /* Check for a user name that exceeds PR_TUNABLE_LOGIN_MAX. */ if (strlen(cmd->arg) > PR_TUNABLE_LOGIN_MAX) { pr_log_pri(PR_LOG_NOTICE, "USER %s (Login failed): " "maximum USER length exceeded", cmd->arg); pr_response_add_err(R_501, _("Login incorrect.")); pr_cmd_set_errno(cmd, EPERM); errno = EPERM; return PR_ERROR(cmd); } return PR_DECLINED(cmd); } MODRET auth_user(cmd_rec *cmd) { int nopass = FALSE; config_rec *c; const char *denymsg = NULL, *user, *origuser; int failnopwprompt = 0, aclp, i; unsigned char *anon_require_passwd = NULL, *login_passwd_prompt = NULL; if (cmd->argc < 2) { return PR_ERROR_MSG(cmd, R_500, _("USER: command requires a parameter")); } if (logged_in) { /* If the client has already authenticated, BUT the given USER command * here is for the exact same user name, then allow the command to * succeed (Bug#4217). */ origuser = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (origuser != NULL && strcmp(origuser, cmd->arg) == 0) { pr_response_add(R_230, _("User %s logged in"), origuser); return PR_HANDLED(cmd); } pr_response_add_err(R_501, "%s", _("Reauthentication not supported")); return PR_ERROR(cmd); } user = cmd->arg; (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (pr_table_add_dup(session.notes, "mod_auth.orig-user", user, 0) < 0) { pr_log_debug(DEBUG3, "error stashing 'mod_auth.orig-user' in " "session.notes: %s", strerror(errno)); } origuser = user; c = pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Check for AccessDenyMsg */ denymsg = get_param_ptr((c ? c->subset : cmd->server->conf), "AccessDenyMsg", FALSE); if (denymsg != NULL) { if (strstr(denymsg, "%u") != NULL) { denymsg = sreplace(cmd->tmp_pool, denymsg, "%u", user, NULL); } } login_passwd_prompt = get_param_ptr( (c && c->config_type == CONF_ANON) ? c->subset : main_server->conf, "LoginPasswordPrompt", FALSE); if (login_passwd_prompt && *login_passwd_prompt == FALSE) { failnopwprompt = TRUE; } else { failnopwprompt = FALSE; } if (failnopwprompt) { if (!user) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_pri(PR_LOG_NOTICE, "USER %s (Login failed): Not a UserAlias", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, _("Login incorrect.")); } pr_session_end(0); } aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); if (c && c->config_type != CONF_ANON) { c = (config_rec *) pcalloc(session.pool, sizeof(config_rec)); c->config_type = CONF_ANON; c->name = ""; /* don't really need this yet */ c->subset = main_server->conf; } if (c) { if (!login_check_limits(c->subset, FALSE, TRUE, &i) || (!aclp && !i) ) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_auth(PR_LOG_NOTICE, "ANON %s: Limit access denies login", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, _("Login incorrect.")); } pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by <Limit LOGIN>"); } } if (c == NULL && aclp == 0) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_auth(PR_LOG_NOTICE, "USER %s: Limit access denies login", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, "%s", _("Login incorrect.")); } pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by <Limit LOGIN>"); } } if (c) anon_require_passwd = get_param_ptr(c->subset, "AnonRequirePassword", FALSE); if (c && user && (!anon_require_passwd || *anon_require_passwd == FALSE)) nopass = TRUE; session.gids = NULL; session.groups = NULL; session.user = NULL; session.group = NULL; if (nopass) { pr_response_add(R_331, _("Anonymous login ok, send your complete email " "address as your password")); } else if (pr_auth_requires_pass(cmd->tmp_pool, user) == FALSE) { /* Check to see if a password from the client is required. In the * vast majority of cases, a password will be required. */ /* Act as if we received a PASS command from the client. */ cmd_rec *fakecmd = pr_cmd_alloc(cmd->pool, 2, NULL); /* We use pstrdup() here, rather than assigning C_PASS directly, since * code elsewhere will attempt to modify this buffer, and C_PASS is * a string literal. */ fakecmd->argv[0] = pstrdup(fakecmd->pool, C_PASS); fakecmd->argv[1] = NULL; fakecmd->arg = NULL; c = add_config_param_set(&cmd->server->conf, "authenticated", 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = TRUE; authenticated_without_pass = TRUE; pr_log_auth(PR_LOG_NOTICE, "USER %s: Authenticated without password", user); pr_cmd_dispatch(fakecmd); } else { pr_response_add(R_331, _("Password required for %s"), (char *) cmd->argv[1]); } return PR_HANDLED(cmd); } /* Close the passwd and group databases, similar to auth_pre_user(). */ MODRET auth_pre_pass(cmd_rec *cmd) { const char *user; char *displaylogin; pr_auth_endpwent(cmd->tmp_pool); pr_auth_endgrent(cmd->tmp_pool); /* Handle cases where PASS might be sent before USER. */ user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (user != NULL) { config_rec *c; c = find_config(main_server->conf, CONF_PARAM, "AllowEmptyPasswords", FALSE); if (c == NULL) { const char *anon_user; config_rec *anon_config; /* Since we have not authenticated yet, we cannot use the TOPLEVEL_CONF * macro to handle <Anonymous> sections. So we do it manually. */ anon_user = pstrdup(cmd->tmp_pool, user); anon_config = pr_auth_get_anon_config(cmd->tmp_pool, &anon_user, NULL, NULL); if (anon_config != NULL) { c = find_config(anon_config->subset, CONF_PARAM, "AllowEmptyPasswords", FALSE); } } if (c != NULL) { int allow_empty_passwords; allow_empty_passwords = *((int *) c->argv[0]); if (allow_empty_passwords == FALSE) { size_t passwd_len = 0; if (cmd->argc > 1) { if (cmd->arg != NULL) { passwd_len = strlen(cmd->arg); } } /* Make sure to NOT enforce 'AllowEmptyPasswords off' if e.g. * the AllowDotLogin TLSOption is in effect. */ if (cmd->argc == 1 || passwd_len == 0) { if (session.auth_mech == NULL || strcmp(session.auth_mech, "mod_tls.c") != 0) { pr_log_debug(DEBUG5, "Refusing empty password from user '%s' (AllowEmptyPasswords " "false)", user); pr_log_auth(PR_LOG_NOTICE, "Refusing empty password from user '%s'", user); pr_event_generate("mod_auth.empty-password", user); pr_response_add_err(R_501, _("Login incorrect.")); return PR_ERROR(cmd); } pr_log_debug(DEBUG9, "%s", "'AllowEmptyPasswords off' in effect, " "BUT client authenticated via the AllowDotLogin TLSOption"); } } } } /* Look for a DisplayLogin file which has an absolute path. If we find one, * open a filehandle, such that that file can be displayed even if the * session is chrooted. DisplayLogin files with relative paths will be * handled after chroot, preserving the old behavior. */ displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin && *displaylogin == '/') { struct stat st; displaylogin_fh = pr_fsio_open(displaylogin, O_RDONLY); if (displaylogin_fh == NULL) { pr_log_debug(DEBUG6, "unable to open DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } else { if (pr_fsio_fstat(displaylogin_fh, &st) < 0) { pr_log_debug(DEBUG6, "unable to stat DisplayLogin file '%s': %s", displaylogin, strerror(errno)); pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } else { if (S_ISDIR(st.st_mode)) { errno = EISDIR; pr_log_debug(DEBUG6, "unable to use DisplayLogin file '%s': %s", displaylogin, strerror(errno)); pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } } } } return PR_DECLINED(cmd); } MODRET auth_pass(cmd_rec *cmd) { const char *user = NULL; int res = 0; if (logged_in) { return PR_ERROR_MSG(cmd, R_503, _("You are already logged in")); } user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (user == NULL) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); return PR_ERROR_MSG(cmd, R_503, _("Login with USER first")); } /* Clear any potentially cached directory config */ session.anon_config = NULL; session.dir_config = NULL; res = setup_env(cmd->tmp_pool, cmd, user, cmd->arg); if (res == 1) { config_rec *c = NULL; c = add_config_param_set(&cmd->server->conf, "authenticated", 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = TRUE; set_auth_check(NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (session.sf_flags & SF_ANON) { if (pr_table_add_dup(session.notes, "mod_auth.anon-passwd", pr_fs_decode_path(cmd->server->pool, cmd->arg), 0) < 0) { pr_log_debug(DEBUG3, "error stashing anonymous password in session.notes: %s", strerror(errno)); } } logged_in = TRUE; if (pr_trace_get_level(timing_channel)) { unsigned long elapsed_ms; uint64_t finish_ms; pr_gettimeofday_millis(&finish_ms); elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms); pr_trace_msg(timing_channel, 4, "Time before successful login (via '%s'): %lu ms", session.auth_mech, elapsed_ms); } return PR_HANDLED(cmd); } (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (res == 0) { unsigned int max_logins, *max = NULL; const char *denymsg = NULL; /* check for AccessDenyMsg */ if ((denymsg = get_param_ptr((session.anon_config ? session.anon_config->subset : cmd->server->conf), "AccessDenyMsg", FALSE)) != NULL) { if (strstr(denymsg, "%u") != NULL) { denymsg = sreplace(cmd->tmp_pool, denymsg, "%u", user, NULL); } } max = get_param_ptr(main_server->conf, "MaxLoginAttempts", FALSE); if (max != NULL) { max_logins = *max; } else { max_logins = 3; } if (max_logins > 0 && ++auth_tries >= max_logins) { if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, "%s", _("Login incorrect.")); } pr_log_auth(PR_LOG_NOTICE, "Maximum login attempts (%u) exceeded, connection refused", max_logins); /* Generate an event about this limit being exceeded. */ pr_event_generate("mod_auth.max-login-attempts", session.c); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxLoginAttempts"); } return PR_ERROR_MSG(cmd, R_530, denymsg ? denymsg : _("Login incorrect.")); } return PR_HANDLED(cmd); } MODRET auth_acct(cmd_rec *cmd) { pr_response_add(R_502, _("ACCT command not implemented")); return PR_HANDLED(cmd); } MODRET auth_rein(cmd_rec *cmd) { pr_response_add(R_502, _("REIN command not implemented")); return PR_HANDLED(cmd); } /* FSIO callbacks for providing a fake robots.txt file, for the AnonAllowRobots * functionality. */ #define AUTH_ROBOTS_TXT "User-agent: *\nDisallow: /\n" #define AUTH_ROBOTS_TXT_FD 6742 static int robots_fsio_stat(pr_fs_t *fs, const char *path, struct stat *st) { st->st_dev = (dev_t) 0; st->st_ino = (ino_t) 0; st->st_mode = (S_IFREG|S_IRUSR|S_IRGRP|S_IROTH); st->st_nlink = 0; st->st_uid = (uid_t) 0; st->st_gid = (gid_t) 0; st->st_atime = 0; st->st_mtime = 0; st->st_ctime = 0; st->st_size = strlen(AUTH_ROBOTS_TXT); st->st_blksize = 1024; st->st_blocks = 1; return 0; } static int robots_fsio_fstat(pr_fh_t *fh, int fd, struct stat *st) { if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } return robots_fsio_stat(NULL, NULL, st); } static int robots_fsio_lstat(pr_fs_t *fs, const char *path, struct stat *st) { return robots_fsio_stat(fs, path, st); } static int robots_fsio_unlink(pr_fs_t *fs, const char *path) { return 0; } static int robots_fsio_open(pr_fh_t *fh, const char *path, int flags) { if (flags != O_RDONLY) { errno = EINVAL; return -1; } return AUTH_ROBOTS_TXT_FD; } static int robots_fsio_close(pr_fh_t *fh, int fd) { if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } return 0; } static int robots_fsio_read(pr_fh_t *fh, int fd, char *buf, size_t bufsz) { size_t robots_len; if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } robots_len = strlen(AUTH_ROBOTS_TXT); if (bufsz < robots_len) { errno = EINVAL; return -1; } memcpy(buf, AUTH_ROBOTS_TXT, robots_len); return (int) robots_len; } static int robots_fsio_write(pr_fh_t *fh, int fd, const char *buf, size_t bufsz) { if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } return (int) bufsz; } static int robots_fsio_access(pr_fs_t *fs, const char *path, int mode, uid_t uid, gid_t gid, array_header *suppl_gids) { if (mode != R_OK) { errno = EACCES; return -1; } return 0; } static int robots_fsio_faccess(pr_fh_t *fh, int mode, uid_t uid, gid_t gid, array_header *suppl_gids) { if (fh->fh_fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } if (mode != R_OK) { errno = EACCES; return -1; } return 0; } MODRET auth_pre_retr(cmd_rec *cmd) { const char *path; pr_fs_t *curr_fs = NULL; struct stat st; /* Only apply this for <Anonymous> logins. */ if (session.anon_config == NULL) { return PR_DECLINED(cmd); } if (auth_anon_allow_robots == TRUE) { return PR_DECLINED(cmd); } auth_anon_allow_robots_enabled = FALSE; path = dir_canonical_path(cmd->tmp_pool, cmd->arg); if (strcasecmp(path, "/robots.txt") != 0) { return PR_DECLINED(cmd); } /* If a previous REST command, with a non-zero value, has been sent, then * do nothing. Ugh. */ if (session.restart_pos > 0) { pr_log_debug(DEBUG10, "'AnonAllowRobots off' in effect, but cannot " "support resumed download (REST %" PR_LU " previously sent by client)", (pr_off_t) session.restart_pos); return PR_DECLINED(cmd); } pr_fs_clear_cache2(path); if (pr_fsio_lstat(path, &st) == 0) { /* There's an existing REAL "robots.txt" file on disk; use that, and * preserve the principle of least surprise. */ pr_log_debug(DEBUG10, "'AnonAllowRobots off' in effect, but have " "real 'robots.txt' file on disk; using that"); return PR_DECLINED(cmd); } curr_fs = pr_get_fs(path, NULL); if (curr_fs != NULL) { pr_fs_t *robots_fs; robots_fs = pr_register_fs(cmd->pool, "robots", path); if (robots_fs == NULL) { pr_log_debug(DEBUG8, "'AnonAllowRobots off' in effect, but failed to " "register FS: %s", strerror(errno)); return PR_DECLINED(cmd); } /* Use enough of our own custom FSIO callbacks to be able to provide * a fake "robots.txt" file. */ robots_fs->stat = robots_fsio_stat; robots_fs->fstat = robots_fsio_fstat; robots_fs->lstat = robots_fsio_lstat; robots_fs->unlink = robots_fsio_unlink; robots_fs->open = robots_fsio_open; robots_fs->close = robots_fsio_close; robots_fs->read = robots_fsio_read; robots_fs->write = robots_fsio_write; robots_fs->access = robots_fsio_access; robots_fs->faccess = robots_fsio_faccess; /* For all other FSIO callbacks, use the underlying FS. */ robots_fs->rename = curr_fs->rename; robots_fs->lseek = curr_fs->lseek; robots_fs->link = curr_fs->link; robots_fs->readlink = curr_fs->readlink; robots_fs->symlink = curr_fs->symlink; robots_fs->ftruncate = curr_fs->ftruncate; robots_fs->truncate = curr_fs->truncate; robots_fs->chmod = curr_fs->chmod; robots_fs->fchmod = curr_fs->fchmod; robots_fs->chown = curr_fs->chown; robots_fs->fchown = curr_fs->fchown; robots_fs->lchown = curr_fs->lchown; robots_fs->utimes = curr_fs->utimes; robots_fs->futimes = curr_fs->futimes; robots_fs->fsync = curr_fs->fsync; pr_fs_clear_cache2(path); auth_anon_allow_robots_enabled = TRUE; } return PR_DECLINED(cmd); } MODRET auth_post_retr(cmd_rec *cmd) { if (auth_anon_allow_robots == TRUE) { return PR_DECLINED(cmd); } if (auth_anon_allow_robots_enabled == TRUE) { int res; res = pr_unregister_fs("/robots.txt"); if (res < 0) { pr_log_debug(DEBUG9, "error removing 'robots' FS for '/robots.txt': %s", strerror(errno)); } auth_anon_allow_robots_enabled = FALSE; } return PR_DECLINED(cmd); } /* Configuration handlers */ MODRET set_accessdenymsg(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_accessgrantmsg(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: AllowChrootSymlinks on|off */ MODRET set_allowchrootsymlinks(cmd_rec *cmd) { int allow_chroot_symlinks = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); allow_chroot_symlinks = get_boolean(cmd, 1); if (allow_chroot_symlinks == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = allow_chroot_symlinks; return PR_HANDLED(cmd); } /* usage: AllowEmptyPasswords on|off */ MODRET set_allowemptypasswords(cmd_rec *cmd) { int allow_empty_passwords = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); allow_empty_passwords = get_boolean(cmd, 1); if (allow_empty_passwords == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = allow_empty_passwords; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: AnonAllowRobots on|off */ MODRET set_anonallowrobots(cmd_rec *cmd) { int allow_robots = -1; config_rec *c; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); allow_robots = get_boolean(cmd, 1); if (allow_robots == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = palloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = allow_robots; return PR_HANDLED(cmd); } MODRET set_anonrequirepassword(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } /* usage: AnonRejectPasswords pattern [flags] */ MODRET set_anonrejectpasswords(cmd_rec *cmd) { #ifdef PR_USE_REGEX config_rec *c; pr_regex_t *pre = NULL; int notmatch = FALSE, regex_flags = REG_EXTENDED|REG_NOSUB, res = 0; char *pattern = NULL; if (cmd->argc-1 < 1 || cmd->argc-1 > 2) { CONF_ERROR(cmd, "bad number of parameters"); } CHECK_CONF(cmd, CONF_ANON); /* Make sure that, if present, the flags parameter is correctly formatted. */ if (cmd->argc-1 == 2) { int flags = 0; /* We need to parse the flags parameter here, to see if any flags which * affect the compilation of the regex (e.g. NC) are present. */ flags = pr_filter_parse_flags(cmd->tmp_pool, cmd->argv[2]); if (flags < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": badly formatted flags parameter: '", cmd->argv[2], "'", NULL)); } if (flags == 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown flags '", cmd->argv[2], "'", NULL)); } regex_flags |= flags; } pre = pr_regexp_alloc(&auth_module); pattern = cmd->argv[1]; if (*pattern == '!') { notmatch = TRUE; pattern++; } res = pr_regexp_compile(pre, pattern, regex_flags); if (res != 0) { char errstr[200] = {'\0'}; pr_regexp_error(res, pre, errstr, 200); pr_regexp_free(NULL, pre); CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "Unable to compile regex '", cmd->argv[1], "': ", errstr, NULL)); } c = add_config_param(cmd->argv[0], 2, pre, NULL); c->argv[1] = palloc(c->pool, sizeof(int)); *((int *) c->argv[1]) = notmatch; return PR_HANDLED(cmd); #else CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0], " directive " "cannot be used on this system, as you do not have POSIX compliant " "regex support", NULL)); #endif } MODRET set_authaliasonly(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_authusingalias(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_createhome(cmd_rec *cmd) { int bool = -1, start = 2; mode_t mode = (mode_t) 0700, dirmode = (mode_t) 0711; char *skel_path = NULL; config_rec *c = NULL; uid_t cuid = 0; gid_t cgid = 0, hgid = -1; unsigned long flags = 0UL; if (cmd->argc-1 < 1) { CONF_ERROR(cmd, "wrong number of parameters"); } CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } /* No need to process the rest if bool is FALSE. */ if (bool == FALSE) { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } /* Check the mode parameter, if present */ if (cmd->argc-1 >= 2 && strcasecmp(cmd->argv[2], "dirmode") != 0 && strcasecmp(cmd->argv[2], "skel") != 0) { char *tmp = NULL; mode = strtol(cmd->argv[2], &tmp, 8); if (tmp && *tmp) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": bad mode parameter: '", cmd->argv[2], "'", NULL)); start = 3; } if (cmd->argc-1 > 2) { register unsigned int i; /* Cycle through the rest of the parameters */ for (i = start; i < cmd->argc;) { if (strcasecmp(cmd->argv[i], "skel") == 0) { struct stat st; /* Check that the skel directory, if configured, meets the * requirements. */ skel_path = cmd->argv[++i]; if (*skel_path != '/') { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "skel path '", skel_path, "' is not a full path", NULL)); } if (pr_fsio_stat(skel_path, &st) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to stat '", skel_path, "': ", strerror(errno), NULL)); } if (!S_ISDIR(st.st_mode)) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", skel_path, "' is not a directory", NULL)); } /* Must not be world-writable. */ if (st.st_mode & S_IWOTH) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", skel_path, "' is world-writable", NULL)); } /* Move the index past the skel parameter */ i++; } else if (strcasecmp(cmd->argv[i], "dirmode") == 0) { char *tmp = NULL; dirmode = strtol(cmd->argv[++i], &tmp, 8); if (tmp && *tmp) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad mode parameter: '", cmd->argv[i], "'", NULL)); /* Move the index past the dirmode parameter */ i++; } else if (strcasecmp(cmd->argv[i], "uid") == 0) { /* Check for a "~" parameter. */ if (strncmp(cmd->argv[i+1], "~", 2) != 0) { uid_t uid; if (pr_str2uid(cmd->argv[++i], &uid) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad UID parameter: '", cmd->argv[i], "'", NULL)); } cuid = uid; } else { cuid = (uid_t) -1; i++; } /* Move the index past the uid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "gid") == 0) { /* Check for a "~" parameter. */ if (strncmp(cmd->argv[i+1], "~", 2) != 0) { gid_t gid; if (pr_str2gid(cmd->argv[++i], &gid) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad GID parameter: '", cmd->argv[i], "'", NULL)); } cgid = gid; } else { cgid = (gid_t) -1; i++; } /* Move the index past the gid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "homegid") == 0) { char *tmp = NULL; gid_t gid; gid = strtol(cmd->argv[++i], &tmp, 10); if (tmp && *tmp) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad GID parameter: '", cmd->argv[i], "'", NULL)); } hgid = gid; /* Move the index past the homegid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "NoRootPrivs") == 0) { flags |= PR_MKHOME_FL_USE_USER_PRIVS; i++; } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown parameter: '", cmd->argv[i], "'", NULL)); } } } c = add_config_param(cmd->argv[0], 8, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->argv[1] = pcalloc(c->pool, sizeof(mode_t)); *((mode_t *) c->argv[1]) = mode; c->argv[2] = pcalloc(c->pool, sizeof(mode_t)); *((mode_t *) c->argv[2]) = dirmode; if (skel_path) { c->argv[3] = pstrdup(c->pool, skel_path); } c->argv[4] = pcalloc(c->pool, sizeof(uid_t)); *((uid_t *) c->argv[4]) = cuid; c->argv[5] = pcalloc(c->pool, sizeof(gid_t)); *((gid_t *) c->argv[5]) = cgid; c->argv[6] = pcalloc(c->pool, sizeof(gid_t)); *((gid_t *) c->argv[6]) = hgid; c->argv[7] = pcalloc(c->pool, sizeof(unsigned long)); *((unsigned long *) c->argv[7]) = flags; return PR_HANDLED(cmd); } MODRET add_defaultroot(cmd_rec *cmd) { config_rec *c; char *dir; unsigned int argc; void **argv; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (cmd->argc < 2) { CONF_ERROR(cmd, "syntax: DefaultRoot <directory> [<group-expression>]"); } argc = cmd->argc - 2; argv = cmd->argv; dir = *++argv; /* dir must be / or ~. */ if (*dir != '/' && *dir != '~') { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") absolute pathname " "required", NULL)); } if (strchr(dir, '*')) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); } if (*(dir + strlen(dir) - 1) != '/') { dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); } acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(void *)); argv = c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } *argv = NULL; return PR_HANDLED(cmd); } MODRET add_defaultchdir(cmd_rec *cmd) { config_rec *c; char *dir; unsigned int argc; void **argv; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2) { CONF_ERROR(cmd, "syntax: DefaultChdir <directory> [<group-expression>]"); } argc = cmd->argc - 2; argv = cmd->argv; dir = *++argv; if (strchr(dir, '*')) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); } if (*(dir + strlen(dir) - 1) != '/') { dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); } acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(void *)); argv = c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) { while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } } *argv = NULL; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_displaylogin(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_grouppassword(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_loginpasswordprompt(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerClass class max|"none" ["message"] */ MODRET set_maxclientsclass(cmd_rec *cmd) { int max; config_rec *c; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[2], "none") == 0) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[2], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "max must be 'none' or a number greater than 0"); } if (cmd->argc == 4) { c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL); c->argv[0] = pstrdup(c->pool, cmd->argv[1]); c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = max; c->argv[2] = pstrdup(c->pool, cmd->argv[3]); } else { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pstrdup(c->pool, cmd->argv[1]); c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = max; } return PR_HANDLED(cmd); } /* usage: MaxClients max|"none" ["message"] */ MODRET set_maxclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerHost max|"none" ["message"] */ MODRET set_maxhostclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerUser max|"none" ["message"] */ MODRET set_maxuserclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxConnectionsPerHost max|"none" ["message"] */ MODRET set_maxconnectsperhost(cmd_rec *cmd) { int max; config_rec *c; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[1], "none") == 0) max = 0; else { char *tmp = NULL; max = (int) strtol(cmd->argv[1], &tmp, 10); if ((tmp && *tmp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; return PR_HANDLED(cmd); } /* usage: MaxHostsPerUser max|"none" ["message"] */ MODRET set_maxhostsperuser(cmd_rec *cmd) { int max; config_rec *c = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_maxloginattempts(cmd_rec *cmd) { int max; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[1], "none") == 0) { max = 0; } else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; return PR_HANDLED(cmd); } /* usage: MaxPasswordSize len */ MODRET set_maxpasswordsize(cmd_rec *cmd) { config_rec *c; size_t password_len; char *len, *ptr = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); len = cmd->argv[1]; if (*len == '-') { CONF_ERROR(cmd, "badly formatted parameter"); } password_len = strtoul(len, &ptr, 10); if (ptr && *ptr) { CONF_ERROR(cmd, "badly formatted parameter"); } /* XXX Applies to the following modules, which use crypt(3): * * mod_ldap (ldap_auth_check; "check" authtab) * ldap_auth_auth ("auth" authtab) calls pr_auth_check() * mod_sql (sql_auth_crypt, via SQLAuthTypes; cmd_check "check" authtab dispatches here) * cmd_auth ("auth" authtab) calls pr_auth_check() * mod_auth_file (authfile_chkpass, "check" authtab) * authfile_auth ("auth" authtab) calls pr_auth_check() * mod_auth_unix (pw_check, "check" authtab) * pw_auth ("auth" authtab) calls pr_auth_check() * * mod_sftp uses pr_auth_authenticate(), which will dispatch into above * * mod_radius does NOT use either -- up to RADIUS server policy? * * Is there a common code path that all of the above go through? */ c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = palloc(c->pool, sizeof(size_t)); *((size_t *) c->argv[0]) = password_len; return PR_HANDLED(cmd); } MODRET set_requirevalidshell(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: RewriteHome on|off */ MODRET set_rewritehome(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_rootlogin(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd,1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = (unsigned char) bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: RootRevoke on|off|UseNonCompliantActiveTransfer */ MODRET set_rootrevoke(cmd_rec *cmd) { int root_revoke = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* A RootRevoke value of 0 indicates 'false', 1 indicates 'true', and * 2 indicates 'NonCompliantActiveTransfer'. */ root_revoke = get_boolean(cmd, 1); if (root_revoke == -1) { if (strcasecmp(cmd->argv[1], "UseNonCompliantActiveTransfer") != 0 && strcasecmp(cmd->argv[1], "UseNonCompliantActiveTransfers") != 0) { CONF_ERROR(cmd, "expected Boolean parameter"); } root_revoke = 2; } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = (unsigned char) root_revoke; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_timeoutlogin(cmd_rec *cmd) { int timeout = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; return PR_HANDLED(cmd); } MODRET set_timeoutsession(cmd_rec *cmd) { int timeout = 0, precedence = 0; config_rec *c = NULL; int ctxt = (cmd->config && cmd->config->config_type != CONF_PARAM ? cmd->config->config_type : cmd->server->config_type ? cmd->server->config_type : CONF_ROOT); /* this directive must have either 1 or 3 arguments */ if (cmd->argc-1 != 1 && cmd->argc-1 != 3) { CONF_ERROR(cmd, "missing parameters"); } CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Set the precedence for this config_rec based on its configuration * context. */ if (ctxt & CONF_GLOBAL) { precedence = 1; /* These will never appear simultaneously */ } else if ((ctxt & CONF_ROOT) || (ctxt & CONF_VIRTUAL)) { precedence = 2; } else if (ctxt & CONF_ANON) { precedence = 3; } if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } if (timeout == 0) { /* do nothing */ return PR_HANDLED(cmd); } if (cmd->argc-1 == 3) { if (strncmp(cmd->argv[2], "user", 5) == 0 || strncmp(cmd->argv[2], "group", 6) == 0 || strncmp(cmd->argv[2], "class", 6) == 0) { /* no op */ } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[0], ": unknown classifier used: '", cmd->argv[2], "'", NULL)); } } if (cmd->argc-1 == 1) { c = add_config_param(cmd->argv[0], 2, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = precedence; } else if (cmd->argc-1 == 3) { array_header *acl = NULL; unsigned int argc; void **argv; argc = cmd->argc - 3; argv = cmd->argv + 2; acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 2; /* Add 3 to argc for the argv of the config_rec: one for the * seconds value, one for the precedence, one for the classifier, * and one for the terminating NULL. */ c->argv = pcalloc(c->pool, ((argc + 4) * sizeof(void *))); /* Capture the config_rec's argv pointer for doing the by-hand * population. */ argv = c->argv; /* Copy in the seconds. */ *argv = pcalloc(c->pool, sizeof(int)); *((int *) *argv++) = timeout; /* Copy in the precedence. */ *argv = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) *argv++) = precedence; /* Copy in the classifier. */ *argv++ = pstrdup(c->pool, cmd->argv[2]); /* now, copy in the expression arguments */ if (argc && acl) { while (argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } } /* don't forget the terminating NULL */ *argv = NULL; } else { /* Should never reach here. */ CONF_ERROR(cmd, "wrong number of parameters"); } c->flags |= CF_MERGEDOWN_MULTI; return PR_HANDLED(cmd); } MODRET set_useftpusers(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: UseLastlog on|off */ MODRET set_uselastlog(cmd_rec *cmd) { #ifdef PR_USE_LASTLOG int bool; config_rec *c; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); #else CONF_ERROR(cmd, "requires lastlog support (--with-lastlog)"); #endif /* PR_USE_LASTLOG */ } /* usage: UserAlias alias real-user */ MODRET set_useralias(cmd_rec *cmd) { config_rec *c = NULL; char *alias, *real_user; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Make sure that the given names differ. */ alias = cmd->argv[1]; real_user = cmd->argv[2]; if (strcmp(alias, real_user) == 0) { CONF_ERROR(cmd, "alias and real user names must differ"); } c = add_config_param_str(cmd->argv[0], 2, alias, real_user); /* Note: only merge this directive down if it is not appearing in an * <Anonymous> context. */ if (!check_context(cmd, CONF_ANON)) { c->flags |= CF_MERGEDOWN_MULTI; } return PR_HANDLED(cmd); } MODRET set_userdirroot(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_userpassword(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: WtmpLog on|off */ MODRET set_wtmplog(cmd_rec *cmd) { int use_wtmp = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (strcasecmp(cmd->argv[1], "NONE") == 0) { use_wtmp = FALSE; } else { use_wtmp = get_boolean(cmd, 1); if (use_wtmp == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = use_wtmp; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* Module API tables */ static conftable auth_conftab[] = { { "AccessDenyMsg", set_accessdenymsg, NULL }, { "AccessGrantMsg", set_accessgrantmsg, NULL }, { "AllowChrootSymlinks", set_allowchrootsymlinks, NULL }, { "AllowEmptyPasswords", set_allowemptypasswords, NULL }, { "AnonAllowRobots", set_anonallowrobots, NULL }, { "AnonRequirePassword", set_anonrequirepassword, NULL }, { "AnonRejectPasswords", set_anonrejectpasswords, NULL }, { "AuthAliasOnly", set_authaliasonly, NULL }, { "AuthUsingAlias", set_authusingalias, NULL }, { "CreateHome", set_createhome, NULL }, { "DefaultChdir", add_defaultchdir, NULL }, { "DefaultRoot", add_defaultroot, NULL }, { "DisplayLogin", set_displaylogin, NULL }, { "GroupPassword", set_grouppassword, NULL }, { "LoginPasswordPrompt", set_loginpasswordprompt, NULL }, { "MaxClients", set_maxclients, NULL }, { "MaxClientsPerClass", set_maxclientsclass, NULL }, { "MaxClientsPerHost", set_maxhostclients, NULL }, { "MaxClientsPerUser", set_maxuserclients, NULL }, { "MaxConnectionsPerHost", set_maxconnectsperhost, NULL }, { "MaxHostsPerUser", set_maxhostsperuser, NULL }, { "MaxLoginAttempts", set_maxloginattempts, NULL }, { "MaxPasswordSize", set_maxpasswordsize, NULL }, { "RequireValidShell", set_requirevalidshell, NULL }, { "RewriteHome", set_rewritehome, NULL }, { "RootLogin", set_rootlogin, NULL }, { "RootRevoke", set_rootrevoke, NULL }, { "TimeoutLogin", set_timeoutlogin, NULL }, { "TimeoutSession", set_timeoutsession, NULL }, { "UseFtpUsers", set_useftpusers, NULL }, { "UseLastlog", set_uselastlog, NULL }, { "UserAlias", set_useralias, NULL }, { "UserDirRoot", set_userdirroot, NULL }, { "UserPassword", set_userpassword, NULL }, { "WtmpLog", set_wtmplog, NULL }, { NULL, NULL, NULL } }; static cmdtable auth_cmdtab[] = { { PRE_CMD, C_USER, G_NONE, auth_pre_user, FALSE, FALSE, CL_AUTH }, { CMD, C_USER, G_NONE, auth_user, FALSE, FALSE, CL_AUTH }, { PRE_CMD, C_PASS, G_NONE, auth_pre_pass, FALSE, FALSE, CL_AUTH }, { CMD, C_PASS, G_NONE, auth_pass, FALSE, FALSE, CL_AUTH }, { POST_CMD, C_PASS, G_NONE, auth_post_pass, FALSE, FALSE, CL_AUTH }, { LOG_CMD, C_PASS, G_NONE, auth_log_pass, FALSE, FALSE }, { LOG_CMD_ERR,C_PASS, G_NONE, auth_err_pass, FALSE, FALSE }, { CMD, C_ACCT, G_NONE, auth_acct, FALSE, FALSE, CL_AUTH }, { CMD, C_REIN, G_NONE, auth_rein, FALSE, FALSE, CL_AUTH }, /* For the automatic robots.txt handling */ { PRE_CMD, C_RETR, G_NONE, auth_pre_retr, FALSE, FALSE }, { POST_CMD, C_RETR, G_NONE, auth_post_retr, FALSE, FALSE }, { POST_CMD_ERR,C_RETR,G_NONE, auth_post_retr, FALSE, FALSE }, { 0, NULL } }; /* Module interface */ module auth_module = { NULL, NULL, /* Module API version */ 0x20, /* Module name */ "auth", /* Module configuration directive table */ auth_conftab, /* Module command handler table */ auth_cmdtab, /* Module authentication handler table */ NULL, /* Module initialization function */ auth_init, /* Session initialization function */ auth_sess_init };
./CrossVul/dataset_final_sorted/CWE-59/c/bad_3263_0
crossvul-cpp_data_bad_436_3
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: DBus server thread for VRRP * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2016-2017 Alexandre Cassen, <acassen@gmail.com> */ /* See https://git.gnome.org/browse/glib/tree/gio/tests/fdbus-example-server.c * and https://developer.gnome.org/gio/stable/GDBusConnection.html#gdbus-server * for examples of coding. * * Create a general /org/keepalived/Vrrp1/Vrrp DBus * object and a /org/keepalived/Vrrp1/Instance/#interface#/#group# object for * each VRRP instance. * Interface org.keepalived.Vrrp1.Vrrp implements methods PrintData, * PrintStats and signal VrrpStopped. * Interface com.keepalived.Vrrp1.Instance implements method SendGarp * (sends a single Gratuitous ARP from the given Instance), * signal VrrpStatusChange, and properties Name and State (retrievable * through calls to org.freedesktop.DBus.Properties.Get) * * Interface files need to be installed in /usr/share/dbus-1/interfaces/ * A policy file, which determines who has access to the service, is * installed in /etc/dbus-1/system.d/. Sources for the policy and interface * files are in keepalived/dbus. * * To test the DBus service run a command like: dbus-send --system --dest=org.keepalived.Vrrp1 --print-reply object interface.method type:argument * e.g. * dbus-send --system --dest=org.keepalived.Vrrp1 --print-reply /org/keepalived/Vrrp1/Vrrp org.keepalived.Vrrp1.Vrrp.PrintData * or * dbus-send --system --dest=org.keepalived.Vrrp1 --print-reply /org/keepalived/Vrrp1/Instance/eth0/1/IPv4 org.freedesktop.DBus.Properties.Get string:'org.keepalived.Vrrp1.Instance' string:'State' * * To monitor signals, run: * dbus-monitor --system type='signal' * * d-feet is a useful program for interfacing with DBus */ #include "config.h" #include <errno.h> #include <pthread.h> #include <semaphore.h> #include <gio/gio.h> #include <ctype.h> #include <fcntl.h> #include <sys/types.h> #include <stdlib.h> #include <stdint.h> #include "vrrp_dbus.h" #include "vrrp_data.h" #include "vrrp_print.h" #include "global_data.h" #include "main.h" #include "logger.h" #include "utils.h" #ifdef THREAD_DUMP #include "scheduler.h" #endif typedef enum dbus_action { DBUS_ACTION_NONE, DBUS_PRINT_DATA, DBUS_PRINT_STATS, DBUS_RELOAD, #ifdef _WITH_DBUS_CREATE_INSTANCE_ DBUS_CREATE_INSTANCE, DBUS_DESTROY_INSTANCE, #endif DBUS_SEND_GARP, DBUS_GET_NAME, DBUS_GET_STATUS, } dbus_action_t; typedef enum dbus_error { DBUS_SUCCESS, DBUS_INTERFACE_NOT_FOUND, DBUS_OBJECT_ALREADY_EXISTS, DBUS_INTERFACE_TOO_LONG, DBUS_INSTANCE_NOT_FOUND, } dbus_error_t; typedef struct dbus_queue_ent { dbus_action_t action; dbus_error_t reply; char *ifname; uint8_t vrid; uint8_t family; GVariant *args; } dbus_queue_ent_t; /* Global file variables */ static GDBusNodeInfo *vrrp_introspection_data = NULL; static GDBusNodeInfo *vrrp_instance_introspection_data = NULL; static GDBusConnection *global_connection; static GHashTable *objects; static GMainLoop *loop; /* Data passing between main vrrp thread and dbus thread */ dbus_queue_ent_t *ent_ptr; static int dbus_in_pipe[2], dbus_out_pipe[2]; static sem_t thread_end; /* The only characters that are valid in a dbus path are A-Z, a-z, 0-9, _ */ static char * set_valid_path(char *valid_path, const char *path) { const char *str_in; char *str_out; for (str_in = path, str_out = valid_path; *str_in; str_in++, str_out++) { if (!isalnum(*str_in)) *str_out = '_'; else *str_out = *str_in; } *str_out = '\0'; return valid_path; } static bool valid_path_cmp(const char *path, const char *valid_path) { for ( ; *path && *valid_path; path++, valid_path++) { if (!isalnum(*path)) { if (*valid_path != '_') return true; } else if (*path != *valid_path) return true; } return *path != *valid_path; } static const char * family_str(int family) { if (family == AF_INET) return "IPv4"; if (family == AF_INET6) return "IPv6"; return "None"; } static const char * state_str(int state) { switch (state) { case VRRP_STATE_INIT: return "Init"; case VRRP_STATE_BACK: return "Backup"; case VRRP_STATE_MAST: return "Master"; case VRRP_STATE_FAULT: return "Fault"; } return "Unknown"; } static vrrp_t * get_vrrp_instance(const char *ifname, int vrid, int family) { element e; vrrp_t *vrrp; if (LIST_ISEMPTY(vrrp_data->vrrp)) return NULL; for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { vrrp = ELEMENT_DATA(e); if (vrrp->vrid == vrid && vrrp->family == family && !valid_path_cmp(IF_BASE_IFP(vrrp->ifp)->ifname, ifname)) return vrrp; } return NULL; } static gboolean unregister_object(gpointer key, gpointer value, __attribute__((unused)) gpointer user_data) { if (g_hash_table_remove(objects, key)) return g_dbus_connection_unregister_object(global_connection, GPOINTER_TO_UINT(value)); return false; } static gchar * dbus_object_create_path_vrrp(void) { return g_strconcat(DBUS_VRRP_OBJECT_ROOT, #if HAVE_DECL_CLONE_NEWNET global_data->network_namespace ? "/" : "", global_data->network_namespace ? global_data->network_namespace : "", #endif global_data->instance_name ? "/" : "", global_data->instance_name ? global_data->instance_name : "", "/Vrrp", NULL); } static gchar * dbus_object_create_path_instance(const gchar *interface, int vrid, sa_family_t family) { gchar *object_path; char standardized_name[sizeof ((vrrp_t*)NULL)->ifp->ifname]; gchar *vrid_str = g_strdup_printf("%d", vrid); set_valid_path(standardized_name, interface); object_path = g_strconcat(DBUS_VRRP_OBJECT_ROOT, #if HAVE_DECL_CLONE_NEWNET global_data->network_namespace ? "/" : "", global_data->network_namespace ? global_data->network_namespace : "", #endif global_data->instance_name ? "/" : "", global_data->instance_name ? global_data->instance_name : "", "/Instance/", standardized_name, "/", vrid_str, "/", family_str(family), NULL); g_free(vrid_str); return object_path; } static dbus_queue_ent_t * process_method_call(dbus_queue_ent_t *ent) { ssize_t ret; if (!ent) return NULL; /* Tell the main thread that a queue entry is waiting. Any data works */ ent_ptr = ent; if (write(dbus_in_pipe[1], ent, 1) != 1) log_message(LOG_INFO, "Write from DBus thread to main thread failed"); /* Wait for a response */ while ((ret = read(dbus_out_pipe[0], ent, 1)) == -1 && errno == EINTR) { log_message(LOG_INFO, "dbus_out_pipe read returned EINTR"); } if (ret == -1) log_message(LOG_INFO, "DBus response read error - errno = %d", errno); #ifdef DBUS_DEBUG if (ent->reply != DBUS_SUCCESS) { char *iname; if (ent->reply == DBUS_INTERFACE_NOT_FOUND) log_message(LOG_INFO, "Unable to find DBus requested instance %s/%d/%s", ent->ifname, ent->vrid, family_str(ent->family)); else if (ent->reply == DBUS_OBJECT_ALREADY_EXISTS) log_message(LOG_INFO, "Unable to create DBus requested object with instance %s/%d/%s", ent->ifname, ent->vrid, family_str(ent->family)); else if (ent->reply == DBUS_INSTANCE_NOT_FOUND) { g_variant_get(ent->args, "(s)", &iname); log_message(LOG_INFO, "Unable to find DBus requested instance %s", iname); } else log_message(LOG_INFO, "Unknown DBus reply %d", ent->reply); } #endif return ent; } static void get_interface_ids(const gchar *object_path, gchar *interface, uint8_t *vrid, uint8_t *family) { int path_length = DBUS_VRRP_INSTANCE_PATH_DEFAULT_LENGTH; gchar **dirs; char *endptr; #if HAVE_DECL_CLONE_NEWNET if(global_data->network_namespace) path_length++; #endif if(global_data->instance_name) path_length++; /* object_path will have interface, vrid and family as * the third to last, second to last and last levels */ dirs = g_strsplit(object_path, "/", path_length); strcpy(interface, dirs[path_length-3]); *vrid = (uint8_t)strtoul(dirs[path_length-2], &endptr, 10); if (*endptr) log_message(LOG_INFO, "Dbus unexpected characters '%s' at end of number '%s'", endptr, dirs[path_length-2]); *family = !g_strcmp0(dirs[path_length-1], "IPv4") ? AF_INET : !g_strcmp0(dirs[path_length-1], "IPv6") ? AF_INET6 : AF_UNSPEC; /* We are finished with all the object_path strings now */ g_strfreev(dirs); } /* handles reply to org.freedesktop.DBus.Properties.Get method on any object*/ static GVariant * handle_get_property(__attribute__((unused)) GDBusConnection *connection, __attribute__((unused)) const gchar *sender, const gchar *object_path, const gchar *interface_name, const gchar *property_name, GError **error, __attribute__((unused)) gpointer user_data) { GVariant *ret = NULL; dbus_queue_ent_t ent; char ifname_str[sizeof ((vrrp_t*)NULL)->ifp->ifname]; int action; if (g_strcmp0(interface_name, DBUS_VRRP_INSTANCE_INTERFACE)) { log_message(LOG_INFO, "Interface %s has not been implemented yet", interface_name); return NULL; } if (!g_strcmp0(property_name, "Name")) action = DBUS_GET_NAME; else if (!g_strcmp0(property_name, "State")) action = DBUS_GET_STATUS; else { log_message(LOG_INFO, "Property %s does not exist", property_name); return NULL; } get_interface_ids(object_path, ifname_str, &ent.vrid, &ent.family); ent.action = action; ent.ifname = ifname_str; ent.args = NULL; process_method_call(&ent); if (ent.reply == DBUS_SUCCESS) ret = ent.args; else g_set_error(error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Instance '%s/%d/%s' not found", ifname_str, ent.vrid, family_str(ent.family)); return ret; } /* handles method_calls on any object */ static void handle_method_call(__attribute__((unused)) GDBusConnection *connection, __attribute__((unused)) const gchar *sender, const gchar *object_path, const gchar *interface_name, const gchar *method_name, #ifndef _WITH_DBUS_CREATE_INSTANCE_ __attribute__((unused)) #endif GVariant *parameters, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { #ifdef _WITH_DBUS_CREATE_INSTANCE_ char *iname; char *ifname; size_t len; unsigned family; #endif dbus_queue_ent_t ent; char ifname_str[sizeof ((vrrp_t*)NULL)->ifp->ifname]; if (!g_strcmp0(interface_name, DBUS_VRRP_INTERFACE)) { if (!g_strcmp0(method_name, "PrintData")) { ent.action = DBUS_PRINT_DATA; process_method_call(&ent); g_dbus_method_invocation_return_value(invocation, NULL); } else if (g_strcmp0(method_name, "PrintStats") == 0) { ent.action = DBUS_PRINT_STATS; process_method_call(&ent); g_dbus_method_invocation_return_value(invocation, NULL); } else if (g_strcmp0(method_name, "ReloadConfig") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); kill(getppid(), SIGHUP); } #ifdef _WITH_DBUS_CREATE_INSTANCE_ else if (g_strcmp0(method_name, "CreateInstance") == 0) { g_variant_get(parameters, "(ssuu)", &iname, &ifname, &ent.vrid, &family); len = strlen(ifname); if (len == 0 || len >= IFNAMSIZ) { log_message(LOG_INFO, "Interface name '%s' too long for CreateInstance", ifname); g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Interface name empty or too long"); return; } ent.action = DBUS_CREATE_INSTANCE; ent.ifname = ifname; ent.family = family == 4 ? AF_INET : family == 6 ? AF_INET6 : AF_UNSPEC; ent.args = g_variant_new("(s)", iname); process_method_call(&ent); g_variant_unref(ent.args); g_dbus_method_invocation_return_value(invocation, NULL); } else if (g_strcmp0(method_name, "DestroyInstance") == 0) { // TODO - this should be on the instance ent.action = DBUS_DESTROY_INSTANCE; ent.args = parameters; process_method_call(&ent); if (ent.reply == DBUS_INSTANCE_NOT_FOUND) { g_variant_get(parameters, "(s)", &iname); g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Instance '%s' not found", iname); } else g_dbus_method_invocation_return_value(invocation, NULL); } #endif else { log_message(LOG_INFO, "Method %s has not been implemented yet", method_name); g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_MATCH_RULE_NOT_FOUND, "Method not implemented"); } return; } if (!g_strcmp0(interface_name, DBUS_VRRP_INSTANCE_INTERFACE)) { if (!g_strcmp0(method_name, "SendGarp")) { get_interface_ids(object_path, ifname_str, &ent.vrid, &ent.family); ent.action = DBUS_SEND_GARP; ent.ifname = ifname_str; process_method_call(&ent); if (ent.reply == DBUS_INTERFACE_NOT_FOUND) g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Instance '%s/%d/%s' not found", ifname_str, ent.vrid, family_str(ent.family)); else g_dbus_method_invocation_return_value(invocation, NULL); } else { log_message(LOG_INFO, "Method %s has not been implemented yet", method_name); g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_MATCH_RULE_NOT_FOUND, "Method not implemented"); } return; } log_message(LOG_INFO, "Interface %s has not been implemented yet", interface_name); g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_MATCH_RULE_NOT_FOUND, "Interface not implemented"); } static const GDBusInterfaceVTable interface_vtable = { handle_method_call, handle_get_property, NULL, /* handle_set_property is null because we have no writeable property */ {} }; static int dbus_create_object_params(char *instance_name, const char *interface_name, int vrid, sa_family_t family, bool log_success) { gchar *object_path; GError *local_error = NULL; if (g_hash_table_lookup(objects, instance_name)) { log_message(LOG_INFO, "An object for instance %s already exists", instance_name); return DBUS_OBJECT_ALREADY_EXISTS; } object_path = dbus_object_create_path_instance(interface_name, vrid, family); guint instance = g_dbus_connection_register_object(global_connection, object_path, vrrp_instance_introspection_data->interfaces[0], &interface_vtable, NULL, NULL, &local_error); if (local_error != NULL) { log_message(LOG_INFO, "Registering DBus object on %s failed: %s", object_path, local_error->message); g_clear_error(&local_error); } if (instance) { g_hash_table_insert(objects, instance_name, GUINT_TO_POINTER(instance)); if (log_success) log_message(LOG_INFO, "Added DBus object for instance %s on path %s", instance_name, object_path); } g_free(object_path); return DBUS_SUCCESS; } static void dbus_create_object(vrrp_t *vrrp) { dbus_create_object_params(vrrp->iname, IF_NAME(IF_BASE_IFP(vrrp->ifp)), vrrp->vrid, vrrp->family, false); } static bool dbus_emit_signal(GDBusConnection *connection, const gchar *object_path, const gchar *interface_name, const gchar *signal_name, GVariant *parameters) { GError *local_error = NULL; g_dbus_connection_emit_signal(connection, NULL, object_path, interface_name, signal_name, parameters, &local_error); if (local_error != NULL) { log_message(LOG_INFO, "Emitting DBus signal %s.%s on %s failed: %s", interface_name, signal_name, object_path, local_error->message); g_clear_error(&local_error); return false; } return true; } /* first function to be run when trying to own bus, * exports objects to the bus */ static void on_bus_acquired(GDBusConnection *connection, const gchar *name, __attribute__((unused)) gpointer user_data) { global_connection = connection; gchar *path; element e; GError *local_error = NULL; log_message(LOG_INFO, "Acquired DBus bus %s", name); /* register VRRP object */ path = dbus_object_create_path_vrrp(); guint vrrp = g_dbus_connection_register_object(connection, path, vrrp_introspection_data->interfaces[0], &interface_vtable, NULL, NULL, &local_error); g_hash_table_insert(objects, "__Vrrp__", GUINT_TO_POINTER(vrrp)); g_free(path); if (local_error != NULL) { log_message(LOG_INFO, "Registering VRRP object on %s failed: %s", path, local_error->message); g_clear_error(&local_error); } /* for each available VRRP instance, register an object */ if (LIST_ISEMPTY(vrrp_data->vrrp)) return; for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { vrrp_t * vrrp = ELEMENT_DATA(e); dbus_create_object(vrrp); } /* Send a signal to say we have started */ path = dbus_object_create_path_vrrp(); dbus_emit_signal(global_connection, path, DBUS_VRRP_INTERFACE, "VrrpStarted", NULL); g_free(path); /* Notify DBus of the state of our instances */ for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { vrrp_t * vrrp = ELEMENT_DATA(e); dbus_send_state_signal(vrrp); } } /* run if bus name is acquired successfully */ static void on_name_acquired(__attribute__((unused)) GDBusConnection *connection, const gchar *name, __attribute__((unused)) gpointer user_data) { log_message(LOG_INFO, "Acquired the name %s on the session bus", name); } /* run if bus name or connection are lost */ static void on_name_lost(GDBusConnection *connection, const gchar *name, __attribute__((unused)) gpointer user_data) { log_message(LOG_INFO, "Lost the name %s on the session bus", name); global_connection = connection; g_hash_table_foreach_remove(objects, unregister_object, NULL); objects = NULL; global_connection = NULL; } static gchar* read_file(gchar* filepath) { FILE * f; size_t length; gchar *ret = NULL; f = fopen(filepath, "rb"); if (f) { fseek(f, 0, SEEK_END); length = (size_t)ftell(f); fseek(f, 0, SEEK_SET); /* We can't use MALLOC since it isn't thread safe */ ret = MALLOC(length + 1); if (ret) { if (fread(ret, length, 1, f) != 1) { log_message(LOG_INFO, "Failed to read all of %s", filepath); } ret[length] = '\0'; } else log_message(LOG_INFO, "Unable to read Dbus file %s", filepath); fclose(f); } return ret; } static void * dbus_main(__attribute__ ((unused)) void *unused) { gchar *introspection_xml; guint owner_id; const char *service_name; objects = g_hash_table_new(g_str_hash, g_str_equal); /* DBus service org.keepalived.Vrrp1 exposes two interfaces, Vrrp and Instance. * Vrrp is implemented by a single VRRP object for general purposes, such as printing * data or signaling that the VRRP process has been stopped. * Instance is implemented by an Instance object for every VRRP Instance in vrrp_data. * It exposes instance specific methods and properties. */ #ifdef DBUS_NEED_G_TYPE_INIT g_type_init(); #endif GError *error = NULL; /* read service interface data from xml files */ introspection_xml = read_file(DBUS_VRRP_INTERFACE_FILE_PATH); if (!introspection_xml) return NULL; vrrp_introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, &error); FREE(introspection_xml); if (error != NULL) { log_message(LOG_INFO, "Parsing DBus interface %s from file %s failed: %s", DBUS_VRRP_INTERFACE, DBUS_VRRP_INTERFACE_FILE_PATH, error->message); g_clear_error(&error); return NULL; } introspection_xml = read_file(DBUS_VRRP_INSTANCE_INTERFACE_FILE_PATH); if (!introspection_xml) return NULL; vrrp_instance_introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, &error); FREE(introspection_xml); if (error != NULL) { log_message(LOG_INFO, "Parsing DBus interface %s from file %s failed: %s", DBUS_VRRP_INSTANCE_INTERFACE, DBUS_VRRP_INSTANCE_INTERFACE_FILE_PATH, error->message); g_clear_error(&error); return NULL; } service_name = global_data->dbus_service_name ? global_data->dbus_service_name : DBUS_SERVICE_NAME; owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM, service_name, G_BUS_NAME_OWNER_FLAGS_NONE, on_bus_acquired, on_name_acquired, on_name_lost, NULL, /* user_data */ NULL); /* user_data_free_func */ loop = g_main_loop_new(NULL, FALSE); g_main_loop_run(loop); /* cleanup after loop terminates */ g_main_loop_unref(loop); g_bus_unown_name(owner_id); global_connection = NULL; sem_post(&thread_end); pthread_exit(0); } /* The following functions are run in the context of the main vrrp thread */ /* send signal VrrpStatusChange * containing the new state of vrrp */ void dbus_send_state_signal(vrrp_t *vrrp) { gchar *object_path; GVariant *args; /* the interface will go through the initial state changes before * the main loop can be started and global_connection initialised */ if (global_connection == NULL) return; object_path = dbus_object_create_path_instance(IF_NAME(IF_BASE_IFP(vrrp->ifp)), vrrp->vrid, vrrp->family); args = g_variant_new("(u)", vrrp->state); dbus_emit_signal(global_connection, object_path, DBUS_VRRP_INSTANCE_INTERFACE, "VrrpStatusChange", args); g_free(object_path); } /* send signal VrrpRestarted */ static void dbus_send_reload_signal(void) { gchar *path; if (global_connection == NULL) return; path = dbus_object_create_path_vrrp(); dbus_emit_signal(global_connection, path, DBUS_VRRP_INTERFACE, "VrrpReloaded", NULL); g_free(path); } static gboolean dbus_unregister_object(char *str) { gboolean ret = false; gpointer value = g_hash_table_lookup(objects, str); if (value) { ret = unregister_object(str, value, NULL); log_message(LOG_INFO, "Deleted DBus object for instance %s", str); } #ifdef DBUS_DEBUG else log_message(LOG_INFO, "DBus object not found for instance %s", str); #endif return ret; } void dbus_remove_object(vrrp_t *vrrp) { dbus_unregister_object(vrrp->iname); } static int handle_dbus_msg(__attribute__((unused)) thread_t *thread) { dbus_queue_ent_t *ent; char recv_buf; vrrp_t *vrrp; #ifdef _WITH_DBUS_CREATE_INSTANCE_ gchar *name; #endif if (read(dbus_in_pipe[0], &recv_buf, 1) != 1) log_message(LOG_INFO, "Read from DBus thread to vrrp thread failed"); if ((ent = ent_ptr) != NULL) { ent->reply = DBUS_SUCCESS; if (ent->action == DBUS_PRINT_DATA) { log_message(LOG_INFO, "Printing VRRP data on DBus request"); vrrp_print_data(); } else if (ent->action == DBUS_PRINT_STATS) { log_message(LOG_INFO, "Printing VRRP stats on DBus request"); vrrp_print_stats(); } #ifdef _WITH_DBUS_CREATE_INSTANCE_ else if (ent->action == DBUS_CREATE_INSTANCE) { g_variant_get(ent->args, "(s)", &name); ent->reply = dbus_create_object_params(name, ent->ifname, ent->vrid, ent->family, true); } else if (ent->action == DBUS_DESTROY_INSTANCE) { g_variant_get(ent->args, "(s)", &name); if (!dbus_unregister_object(name)) ent->reply = DBUS_INSTANCE_NOT_FOUND; } #endif else if (ent->action == DBUS_SEND_GARP) { ent->reply = DBUS_INTERFACE_NOT_FOUND; vrrp = get_vrrp_instance(ent->ifname, ent->vrid, ent->family); if (vrrp) { log_message(LOG_INFO, "Sending garps on %s on DBus request", vrrp->iname); vrrp_send_link_update(vrrp, 1); ent->reply = DBUS_SUCCESS; } } else if (ent->action == DBUS_GET_NAME || ent->action == DBUS_GET_STATUS) { /* we look for the vrrp instance object that corresponds to our interface and group */ ent->reply = DBUS_INTERFACE_NOT_FOUND; vrrp = get_vrrp_instance(ent->ifname, ent->vrid, ent->family); if (vrrp) { /* the property_name argument is the property we want to Get */ if (ent->action == DBUS_GET_NAME) ent->args = g_variant_new("(s)", vrrp->iname); else if (ent->action == DBUS_GET_STATUS) ent->args = g_variant_new("(us)", vrrp->state, state_str(vrrp->state)); else ent->args = NULL; /* How did we get here? */ ent->reply = DBUS_SUCCESS; } } if (write(dbus_out_pipe[1], ent, 1) != 1) log_message(LOG_INFO, "Write from main thread to DBus thread failed"); } thread_add_read(master, handle_dbus_msg, NULL, dbus_in_pipe[0], TIMER_NEVER); return 0; } void dbus_reload(list o, list n) { element e1, e2, e3; vrrp_t *vrrp_n, *vrrp_o, *vrrp_n3; if (!LIST_ISEMPTY(n)) { for (e1 = LIST_HEAD(n); e1; ELEMENT_NEXT(e1)) { char *n_name; bool match_found; vrrp_n = ELEMENT_DATA(e1); if (LIST_ISEMPTY(o)) { dbus_create_object(vrrp_n); continue; } n_name = IF_BASE_IFP(vrrp_n->ifp)->ifname; /* Try an find an instance with same vrid/family/interface that existed before and now */ for (e2 = LIST_HEAD(o), match_found = false; e2 && !match_found; ELEMENT_NEXT(e2)) { vrrp_o = ELEMENT_DATA(e2); if (vrrp_n->vrid == vrrp_o->vrid && vrrp_n->family == vrrp_o->family && !strcmp(n_name, IF_BASE_IFP(vrrp_o->ifp)->ifname)) { /* If the old instance exists in the new config, * then the dbus object will exist */ if (!strcmp(vrrp_n->iname, vrrp_o->iname)) { match_found = true; break; } /* Check if the old instance name we found still exists * (but has a different vrid/family/interface) */ for (e3 = LIST_HEAD(n); e3; ELEMENT_NEXT(e3)) { vrrp_n3 = ELEMENT_DATA(e3); if (!strcmp(vrrp_o->iname, vrrp_n3->iname)) { match_found = true; break; } } } } if (match_found) continue; dbus_create_object(vrrp_n); } } /* Signal we have reloaded */ dbus_send_reload_signal(); /* We need to reinstate the read thread */ thread_add_read(master, handle_dbus_msg, NULL, dbus_in_pipe[0], TIMER_NEVER); } bool dbus_start(void) { pthread_t dbus_thread; sigset_t sigset, cursigset; if (open_pipe(dbus_in_pipe)) { log_message(LOG_INFO, "Unable to create inbound dbus pipe - disabling DBus"); return false; } if (open_pipe(dbus_out_pipe)) { log_message(LOG_INFO, "Unable to create outbound dbus pipe - disabling DBus"); close(dbus_in_pipe[0]); close(dbus_in_pipe[1]); return false; } /* We don't want the main thread to block when using the pipes, * but the other side of the pipes should block. */ fcntl(dbus_in_pipe[1], F_SETFL, fcntl(dbus_in_pipe[1], F_GETFL) & ~O_NONBLOCK); fcntl(dbus_out_pipe[0], F_SETFL, fcntl(dbus_out_pipe[0], F_GETFL) & ~O_NONBLOCK); thread_add_read(master, handle_dbus_msg, NULL, dbus_in_pipe[0], TIMER_NEVER); /* Initialise the thread termination semaphore */ sem_init(&thread_end, 0, 0); /* Block signals (all) we don't want the new thread to process */ sigfillset(&sigset); pthread_sigmask(SIG_SETMASK, &sigset, &cursigset); /* Now create the dbus thread */ pthread_create(&dbus_thread, NULL, &dbus_main, NULL); /* Reenable our signals */ pthread_sigmask(SIG_SETMASK, &cursigset, NULL); return true; } void dbus_stop(void) { struct timespec thread_end_wait; int ret; gchar *path; if (global_connection != NULL) { path = dbus_object_create_path_vrrp(); dbus_emit_signal(global_connection, path, DBUS_VRRP_INTERFACE, "VrrpStopped", NULL); g_free(path); } g_main_loop_quit(loop); g_dbus_node_info_unref(vrrp_introspection_data); g_dbus_node_info_unref(vrrp_instance_introspection_data); clock_gettime(CLOCK_REALTIME, &thread_end_wait); thread_end_wait.tv_sec += 1; while ((ret = sem_timedwait(&thread_end, &thread_end_wait)) == -1 && errno == EINTR) ; if (ret == -1 ) { if (errno == ETIMEDOUT) log_message(LOG_INFO, "DBus thread termination timed out"); else log_message(LOG_INFO, "sem_timewait error %d", errno); } else { log_message(LOG_INFO, "Released DBus"); sem_destroy(&thread_end); } } #ifdef THREAD_DUMP void register_vrrp_dbus_addresses(void) { register_thread_address("handle_dbus_msg", handle_dbus_msg); } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_3
crossvul-cpp_data_bad_589_4
/* $Id: main.c,v 1.270 2010/08/24 10:11:51 htrb Exp $ */ #define MAINPROGRAM #include "fm.h" #include <stdio.h> #include <signal.h> #include <setjmp.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #if defined(HAVE_WAITPID) || defined(HAVE_WAIT3) #include <sys/wait.h> #endif #include <time.h> #if defined(__CYGWIN__) && defined(USE_BINMODE_STREAM) #include <io.h> #endif #include "terms.h" #include "myctype.h" #include "regex.h" #ifdef USE_M17N #include "wc.h" #include "wtf.h" #ifdef USE_UNICODE #include "ucs.h" #endif #endif #ifdef USE_MOUSE #ifdef USE_GPM #include <gpm.h> #endif /* USE_GPM */ #if defined(USE_GPM) || defined(USE_SYSMOUSE) extern int do_getch(); #define getch() do_getch() #endif /* defined(USE_GPM) || defined(USE_SYSMOUSE) */ #endif #ifdef __MINGW32_VERSION #include <winsock.h> WSADATA WSAData; #endif #define DSTR_LEN 256 Hist *LoadHist; Hist *SaveHist; Hist *URLHist; Hist *ShellHist; Hist *TextHist; typedef struct _Event { int cmd; void *data; struct _Event *next; } Event; static Event *CurrentEvent = NULL; static Event *LastEvent = NULL; #ifdef USE_ALARM static AlarmEvent DefaultAlarm = { 0, AL_UNSET, FUNCNAME_nulcmd, NULL }; static AlarmEvent *CurrentAlarm = &DefaultAlarm; static MySignalHandler SigAlarm(SIGNAL_ARG); #endif #ifdef SIGWINCH static int need_resize_screen = FALSE; static MySignalHandler resize_hook(SIGNAL_ARG); static void resize_screen(void); #endif #ifdef SIGPIPE static MySignalHandler SigPipe(SIGNAL_ARG); #endif #ifdef USE_MARK static char *MarkString = NULL; #endif static char *SearchString = NULL; int (*searchRoutine) (Buffer *, char *); #ifndef __MINGW32_VERSION JMP_BUF IntReturn; #else _JBTYPE IntReturn[_JBLEN]; #endif /* __MINGW32_VERSION */ static void delBuffer(Buffer *buf); static void cmd_loadfile(char *path); static void cmd_loadURL(char *url, ParsedURL *current, char *referer, FormList *request); static void cmd_loadBuffer(Buffer *buf, int prop, int linkid); static void keyPressEventProc(int c); int show_params_p = 0; void show_params(FILE * fp); static char *getCurWord(Buffer *buf, int *spos, int *epos); static int display_ok = FALSE; static void do_dump(Buffer *); int prec_num = 0; int prev_key = -1; int on_target = 1; static int add_download_list = FALSE; void set_buffer_environ(Buffer *); static void save_buffer_position(Buffer *buf); static void _followForm(int); static void _goLine(char *); static void _newT(void); static void followTab(TabBuffer * tab); static void moveTab(TabBuffer * t, TabBuffer * t2, int right); static void _nextA(int); static void _prevA(int); static int check_target = TRUE; #define PREC_NUM (prec_num ? prec_num : 1) #define PREC_LIMIT 10000 static int searchKeyNum(void); #define help() fusage(stdout, 0) #define usage() fusage(stderr, 1) int enable_inline_image; /* 1 == mlterm OSC 5379, 2 == sixel */ static void fversion(FILE * f) { fprintf(f, "w3m version %s, options %s\n", w3m_version, #if LANG == JA "lang=ja" #else "lang=en" #endif #ifdef USE_M17N ",m17n" #endif #ifdef USE_IMAGE ",image" #endif #ifdef USE_COLOR ",color" #ifdef USE_ANSI_COLOR ",ansi-color" #endif #endif #ifdef USE_MOUSE ",mouse" #ifdef USE_GPM ",gpm" #endif #ifdef USE_SYSMOUSE ",sysmouse" #endif #endif #ifdef USE_MENU ",menu" #endif #ifdef USE_COOKIE ",cookie" #endif #ifdef USE_SSL ",ssl" #ifdef USE_SSL_VERIFY ",ssl-verify" #endif #endif #ifdef USE_EXTERNAL_URI_LOADER ",external-uri-loader" #endif #ifdef USE_W3MMAILER ",w3mmailer" #endif #ifdef USE_NNTP ",nntp" #endif #ifdef USE_GOPHER ",gopher" #endif #ifdef INET6 ",ipv6" #endif #ifdef USE_ALARM ",alarm" #endif #ifdef USE_MARK ",mark" #endif #ifdef USE_MIGEMO ",migemo" #endif ); } static void fusage(FILE * f, int err) { fversion(f); /* FIXME: gettextize? */ fprintf(f, "usage: w3m [options] [URL or filename]\noptions:\n"); fprintf(f, " -t tab set tab width\n"); fprintf(f, " -r ignore backspace effect\n"); fprintf(f, " -l line # of preserved line (default 10000)\n"); #ifdef USE_M17N fprintf(f, " -I charset document charset\n"); fprintf(f, " -O charset display/output charset\n"); #if 0 /* use -O{s|j|e} instead */ fprintf(f, " -e EUC-JP\n"); fprintf(f, " -s Shift_JIS\n"); fprintf(f, " -j JIS\n"); #endif #endif fprintf(f, " -B load bookmark\n"); fprintf(f, " -bookmark file specify bookmark file\n"); fprintf(f, " -T type specify content-type\n"); fprintf(f, " -m internet message mode\n"); fprintf(f, " -v visual startup mode\n"); #ifdef USE_COLOR fprintf(f, " -M monochrome display\n"); #endif /* USE_COLOR */ fprintf(f, " -N open URL of command line on each new tab\n"); fprintf(f, " -F automatically render frames\n"); fprintf(f, " -cols width specify column width (used with -dump)\n"); fprintf(f, " -ppc count specify the number of pixels per character (4.0...32.0)\n"); #ifdef USE_IMAGE fprintf(f, " -ppl count specify the number of pixels per line (4.0...64.0)\n"); #endif fprintf(f, " -dump dump formatted page into stdout\n"); fprintf(f, " -dump_head dump response of HEAD request into stdout\n"); fprintf(f, " -dump_source dump page source into stdout\n"); fprintf(f, " -dump_both dump HEAD and source into stdout\n"); fprintf(f, " -dump_extra dump HEAD, source, and extra information into stdout\n"); fprintf(f, " -post file use POST method with file content\n"); fprintf(f, " -header string insert string as a header\n"); fprintf(f, " +<num> goto <num> line\n"); fprintf(f, " -num show line number\n"); fprintf(f, " -no-proxy don't use proxy\n"); #ifdef INET6 fprintf(f, " -4 IPv4 only (-o dns_order=4)\n"); fprintf(f, " -6 IPv6 only (-o dns_order=6)\n"); #endif #ifdef USE_MOUSE fprintf(f, " -no-mouse don't use mouse\n"); #endif /* USE_MOUSE */ #ifdef USE_COOKIE fprintf(f, " -cookie use cookie (-no-cookie: don't use cookie)\n"); #endif /* USE_COOKIE */ fprintf(f, " -graph use DEC special graphics for border of table and menu\n"); fprintf(f, " -no-graph use ASCII character for border of table and menu\n"); #if 1 /* pager requires -s */ fprintf(f, " -s squeeze multiple blank lines\n"); #else fprintf(f, " -S squeeze multiple blank lines\n"); #endif fprintf(f, " -W toggle search wrap mode\n"); fprintf(f, " -X don't use termcap init/deinit\n"); fprintf(f, " -title[=TERM] set buffer name to terminal title string\n"); fprintf(f, " -o opt=value assign value to config option\n"); fprintf(f, " -show-option print all config options\n"); fprintf(f, " -config file specify config file\n"); fprintf(f, " -help print this usage message\n"); fprintf(f, " -version print w3m version\n"); fprintf(f, " -reqlog write request logfile\n"); fprintf(f, " -debug DO NOT USE\n"); if (show_params_p) show_params(f); exit(err); } #ifdef USE_M17N #ifdef __EMX__ static char *getCodePage(void); #endif #endif static GC_warn_proc orig_GC_warn_proc = NULL; #define GC_WARN_KEEP_MAX (20) static void wrap_GC_warn_proc(char *msg, GC_word arg) { if (fmInitialized) { /* *INDENT-OFF* */ static struct { char *msg; GC_word arg; } msg_ring[GC_WARN_KEEP_MAX]; /* *INDENT-ON* */ static int i = 0; static int n = 0; static int lock = 0; int j; j = (i + n) % (sizeof(msg_ring) / sizeof(msg_ring[0])); msg_ring[j].msg = msg; msg_ring[j].arg = arg; if (n < sizeof(msg_ring) / sizeof(msg_ring[0])) ++n; else ++i; if (!lock) { lock = 1; for (; n > 0; --n, ++i) { i %= sizeof(msg_ring) / sizeof(msg_ring[0]); printf(msg_ring[i].msg, (unsigned long)msg_ring[i].arg); sleep_till_anykey(1, 1); } lock = 0; } } else if (orig_GC_warn_proc) orig_GC_warn_proc(msg, arg); else fprintf(stderr, msg, (unsigned long)arg); } #ifdef SIGCHLD static void sig_chld(int signo) { int p_stat; pid_t pid; #ifdef HAVE_WAITPID while ((pid = waitpid(-1, &p_stat, WNOHANG)) > 0) #elif HAVE_WAIT3 while ((pid = wait3(&p_stat, WNOHANG, NULL)) > 0) #else if ((pid = wait(&p_stat)) > 0) #endif { DownloadList *d; if (WIFEXITED(p_stat)) { for (d = FirstDL; d != NULL; d = d->next) { if (d->pid == pid) { d->err = WEXITSTATUS(p_stat); break; } } } } mySignal(SIGCHLD, sig_chld); return; } #endif Str make_optional_header_string(char *s) { char *p; Str hs; if (strchr(s, '\n') || strchr(s, '\r')) return NULL; for (p = s; *p && *p != ':'; p++) ; if (*p != ':' || p == s) return NULL; hs = Strnew_size(strlen(s) + 3); Strcopy_charp_n(hs, s, p - s); if (!Strcasecmp_charp(hs, "content-type")) override_content_type = TRUE; Strcat_charp(hs, ": "); if (*(++p)) { /* not null header */ SKIP_BLANKS(p); /* skip white spaces */ Strcat_charp(hs, p); } Strcat_charp(hs, "\r\n"); return hs; } static void * die_oom(size_t bytes) { fprintf(stderr, "Out of memory: %lu bytes unavailable!\n", (unsigned long)bytes); exit(1); } int main(int argc, char **argv, char **envp) { Buffer *newbuf = NULL; char *p, c; int i; InputStream redin; char *line_str = NULL; char **load_argv; FormList *request; int load_argc = 0; int load_bookmark = FALSE; int visual_start = FALSE; int open_new_tab = FALSE; char search_header = FALSE; char *default_type = NULL; char *post_file = NULL; Str err_msg; #ifdef USE_M17N char *Locale = NULL; wc_uint8 auto_detect; #ifdef __EMX__ wc_ces CodePage; #endif #endif #if defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) char **getimage_args = NULL; #endif /* defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) */ GC_INIT(); #if (GC_VERSION_MAJOR>7) || ((GC_VERSION_MAJOR==7) && (GC_VERSION_MINOR>=2)) GC_set_oom_fn(die_oom); #else GC_oom_fn = die_oom; #endif #if defined(ENABLE_NLS) || (defined(USE_M17N) && defined(HAVE_LANGINFO_CODESET)) setlocale(LC_ALL, ""); #endif #ifdef ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif #ifndef HAVE_SYS_ERRLIST prepare_sys_errlist(); #endif /* not HAVE_SYS_ERRLIST */ NO_proxy_domains = newTextList(); fileToDelete = newTextList(); load_argv = New_N(char *, argc - 1); load_argc = 0; CurrentDir = currentdir(); CurrentPid = (int)getpid(); #if defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) if (argv[0] && *argv[0]) MyProgramName = argv[0]; #endif /* defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) */ BookmarkFile = NULL; config_file = NULL; /* argument search 1 */ for (i = 1; i < argc; i++) { if (*argv[i] == '-') { if (!strcmp("-config", argv[i])) { argv[i] = "-dummy"; if (++i >= argc) usage(); config_file = argv[i]; argv[i] = "-dummy"; } else if (!strcmp("-h", argv[i]) || !strcmp("-help", argv[i])) help(); else if (!strcmp("-V", argv[i]) || !strcmp("-version", argv[i])) { fversion(stdout); exit(0); } } } #ifdef USE_M17N if (non_null(Locale = getenv("LC_ALL")) || non_null(Locale = getenv("LC_CTYPE")) || non_null(Locale = getenv("LANG"))) { DisplayCharset = wc_guess_locale_charset(Locale, DisplayCharset); DocumentCharset = wc_guess_locale_charset(Locale, DocumentCharset); SystemCharset = wc_guess_locale_charset(Locale, SystemCharset); } #ifdef __EMX__ CodePage = wc_guess_charset(getCodePage(), 0); if (CodePage) DisplayCharset = DocumentCharset = SystemCharset = CodePage; #endif #endif /* initializations */ init_rc(); LoadHist = newHist(); SaveHist = newHist(); ShellHist = newHist(); TextHist = newHist(); URLHist = newHist(); #ifdef USE_M17N if (FollowLocale && Locale) { DisplayCharset = wc_guess_locale_charset(Locale, DisplayCharset); SystemCharset = wc_guess_locale_charset(Locale, SystemCharset); } auto_detect = WcOption.auto_detect; BookmarkCharset = DocumentCharset; #endif if (!non_null(HTTP_proxy) && ((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy")) || (p = getenv("HTTP_proxy")))) HTTP_proxy = p; #ifdef USE_SSL if (!non_null(HTTPS_proxy) && ((p = getenv("HTTPS_PROXY")) || (p = getenv("https_proxy")) || (p = getenv("HTTPS_proxy")))) HTTPS_proxy = p; if (HTTPS_proxy == NULL && non_null(HTTP_proxy)) HTTPS_proxy = HTTP_proxy; #endif /* USE_SSL */ #ifdef USE_GOPHER if (!non_null(GOPHER_proxy) && ((p = getenv("GOPHER_PROXY")) || (p = getenv("gopher_proxy")) || (p = getenv("GOPHER_proxy")))) GOPHER_proxy = p; #endif /* USE_GOPHER */ if (!non_null(FTP_proxy) && ((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) || (p = getenv("FTP_proxy")))) FTP_proxy = p; if (!non_null(NO_proxy) && ((p = getenv("NO_PROXY")) || (p = getenv("no_proxy")) || (p = getenv("NO_proxy")))) NO_proxy = p; #ifdef USE_NNTP if (!non_null(NNTP_server) && (p = getenv("NNTPSERVER")) != NULL) NNTP_server = p; if (!non_null(NNTP_mode) && (p = getenv("NNTPMODE")) != NULL) NNTP_mode = p; #endif if (!non_null(Editor) && (p = getenv("EDITOR")) != NULL) Editor = p; if (!non_null(Mailer) && (p = getenv("MAILER")) != NULL) Mailer = p; /* argument search 2 */ i = 1; while (i < argc) { if (*argv[i] == '-') { if (!strcmp("-t", argv[i])) { if (++i >= argc) usage(); if (atoi(argv[i]) > 0) Tabstop = atoi(argv[i]); } else if (!strcmp("-r", argv[i])) ShowEffect = FALSE; else if (!strcmp("-l", argv[i])) { if (++i >= argc) usage(); if (atoi(argv[i]) > 0) PagerMax = atoi(argv[i]); } #ifdef USE_M17N #if 0 /* use -O{s|j|e} instead */ else if (!strcmp("-s", argv[i])) DisplayCharset = WC_CES_SHIFT_JIS; else if (!strcmp("-j", argv[i])) DisplayCharset = WC_CES_ISO_2022_JP; else if (!strcmp("-e", argv[i])) DisplayCharset = WC_CES_EUC_JP; #endif else if (!strncmp("-I", argv[i], 2)) { if (argv[i][2] != '\0') p = argv[i] + 2; else { if (++i >= argc) usage(); p = argv[i]; } DocumentCharset = wc_guess_charset_short(p, DocumentCharset); WcOption.auto_detect = WC_OPT_DETECT_OFF; UseContentCharset = FALSE; } else if (!strncmp("-O", argv[i], 2)) { if (argv[i][2] != '\0') p = argv[i] + 2; else { if (++i >= argc) usage(); p = argv[i]; } DisplayCharset = wc_guess_charset_short(p, DisplayCharset); } #endif else if (!strcmp("-graph", argv[i])) UseGraphicChar = GRAPHIC_CHAR_DEC; else if (!strcmp("-no-graph", argv[i])) UseGraphicChar = GRAPHIC_CHAR_ASCII; else if (!strcmp("-T", argv[i])) { if (++i >= argc) usage(); DefaultType = default_type = argv[i]; } else if (!strcmp("-m", argv[i])) SearchHeader = search_header = TRUE; else if (!strcmp("-v", argv[i])) visual_start = TRUE; else if (!strcmp("-N", argv[i])) open_new_tab = TRUE; #ifdef USE_COLOR else if (!strcmp("-M", argv[i])) useColor = FALSE; #endif /* USE_COLOR */ else if (!strcmp("-B", argv[i])) load_bookmark = TRUE; else if (!strcmp("-bookmark", argv[i])) { if (++i >= argc) usage(); BookmarkFile = argv[i]; if (BookmarkFile[0] != '~' && BookmarkFile[0] != '/') { Str tmp = Strnew_charp(CurrentDir); if (Strlastchar(tmp) != '/') Strcat_char(tmp, '/'); Strcat_charp(tmp, BookmarkFile); BookmarkFile = cleanupName(tmp->ptr); } } else if (!strcmp("-F", argv[i])) RenderFrame = TRUE; else if (!strcmp("-W", argv[i])) { if (WrapDefault) WrapDefault = FALSE; else WrapDefault = TRUE; } else if (!strcmp("-dump", argv[i])) w3m_dump = DUMP_BUFFER; else if (!strcmp("-dump_source", argv[i])) w3m_dump = DUMP_SOURCE; else if (!strcmp("-dump_head", argv[i])) w3m_dump = DUMP_HEAD; else if (!strcmp("-dump_both", argv[i])) w3m_dump = (DUMP_HEAD | DUMP_SOURCE); else if (!strcmp("-dump_extra", argv[i])) w3m_dump = (DUMP_HEAD | DUMP_SOURCE | DUMP_EXTRA); else if (!strcmp("-halfdump", argv[i])) w3m_dump = DUMP_HALFDUMP; else if (!strcmp("-halfload", argv[i])) { w3m_dump = 0; w3m_halfload = TRUE; DefaultType = default_type = "text/html"; } else if (!strcmp("-backend", argv[i])) { w3m_backend = TRUE; } else if (!strcmp("-backend_batch", argv[i])) { w3m_backend = TRUE; if (++i >= argc) usage(); if (!backend_batch_commands) backend_batch_commands = newTextList(); pushText(backend_batch_commands, argv[i]); } else if (!strcmp("-cols", argv[i])) { if (++i >= argc) usage(); COLS = atoi(argv[i]); if (COLS > MAXIMUM_COLS) { COLS = MAXIMUM_COLS; } } else if (!strcmp("-ppc", argv[i])) { double ppc; if (++i >= argc) usage(); ppc = atof(argv[i]); if (ppc >= MINIMUM_PIXEL_PER_CHAR && ppc <= MAXIMUM_PIXEL_PER_CHAR) { pixel_per_char = ppc; set_pixel_per_char = TRUE; } } #ifdef USE_IMAGE else if (!strcmp("-ppl", argv[i])) { double ppc; if (++i >= argc) usage(); ppc = atof(argv[i]); if (ppc >= MINIMUM_PIXEL_PER_CHAR && ppc <= MAXIMUM_PIXEL_PER_CHAR * 2) { pixel_per_line = ppc; set_pixel_per_line = TRUE; } } #endif else if (!strcmp("-ri", argv[i])) { enable_inline_image = 1; } else if (!strcmp("-sixel", argv[i])) { enable_inline_image = 2; } else if (!strcmp("-num", argv[i])) showLineNum = TRUE; else if (!strcmp("-no-proxy", argv[i])) use_proxy = FALSE; #ifdef INET6 else if (!strcmp("-4", argv[i]) || !strcmp("-6", argv[i])) set_param_option(Sprintf("dns_order=%c", argv[i][1])->ptr); #endif else if (!strcmp("-post", argv[i])) { if (++i >= argc) usage(); post_file = argv[i]; } else if (!strcmp("-header", argv[i])) { Str hs; if (++i >= argc) usage(); if ((hs = make_optional_header_string(argv[i])) != NULL) { if (header_string == NULL) header_string = hs; else Strcat(header_string, hs); } while (argv[i][0]) { argv[i][0] = '\0'; argv[i]++; } } #ifdef USE_MOUSE else if (!strcmp("-no-mouse", argv[i])) { use_mouse = FALSE; } #endif /* USE_MOUSE */ #ifdef USE_COOKIE else if (!strcmp("-no-cookie", argv[i])) { use_cookie = FALSE; accept_cookie = FALSE; } else if (!strcmp("-cookie", argv[i])) { use_cookie = TRUE; accept_cookie = TRUE; } #endif /* USE_COOKIE */ #if 1 /* pager requires -s */ else if (!strcmp("-s", argv[i])) #else else if (!strcmp("-S", argv[i])) #endif squeezeBlankLine = TRUE; else if (!strcmp("-X", argv[i])) Do_not_use_ti_te = TRUE; else if (!strcmp("-title", argv[i])) displayTitleTerm = getenv("TERM"); else if (!strncmp("-title=", argv[i], 7)) displayTitleTerm = argv[i] + 7; else if (!strcmp("-o", argv[i]) || !strcmp("-show-option", argv[i])) { if (!strcmp("-show-option", argv[i]) || ++i >= argc || !strcmp(argv[i], "?")) { show_params(stdout); exit(0); } if (!set_param_option(argv[i])) { /* option set failed */ /* FIXME: gettextize? */ fprintf(stderr, "%s: bad option\n", argv[i]); show_params_p = 1; usage(); } } else if (!strcmp("-dummy", argv[i])) { /* do nothing */ } else if (!strcmp("-debug", argv[i])) { w3m_debug = TRUE; } else if (!strcmp("-reqlog",argv[i])) { w3m_reqlog=rcFile("request.log"); } #if defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) else if (!strcmp("-$$getimage", argv[i])) { ++i; getimage_args = argv + i; i += 4; if (i > argc) usage(); } #endif /* defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) */ else { usage(); } } else if (*argv[i] == '+') { line_str = argv[i] + 1; } else { load_argv[load_argc++] = argv[i]; } i++; } #ifdef __WATT32__ if (w3m_debug) dbug_init(); sock_init(); #endif #ifdef __MINGW32_VERSION { int err; WORD wVerReq; wVerReq = MAKEWORD(1, 1); err = WSAStartup(wVerReq, &WSAData); if (err != 0) { fprintf(stderr, "Can't find winsock\n"); return 1; } _fmode = _O_BINARY; } #endif FirstTab = NULL; LastTab = NULL; nTab = 0; CurrentTab = NULL; CurrentKey = -1; if (BookmarkFile == NULL) BookmarkFile = rcFile(BOOKMARK); if (!isatty(1) && !w3m_dump) { /* redirected output */ w3m_dump = DUMP_BUFFER; } if (w3m_dump) { if (COLS == 0) COLS = DEFAULT_COLS; } #ifdef USE_BINMODE_STREAM setmode(fileno(stdout), O_BINARY); #endif if (!w3m_dump && !w3m_backend) { fmInit(); #ifdef SIGWINCH mySignal(SIGWINCH, resize_hook); #else /* not SIGWINCH */ setlinescols(); setupscreen(); #endif /* not SIGWINCH */ } #ifdef USE_IMAGE else if (w3m_halfdump && displayImage) activeImage = TRUE; #endif sync_with_option(); #ifdef USE_COOKIE initCookie(); #endif /* USE_COOKIE */ #ifdef USE_HISTORY if (UseHistory) loadHistory(URLHist); #endif /* not USE_HISTORY */ #ifdef USE_M17N wtf_init(DocumentCharset, DisplayCharset); /* if (w3m_dump) * WcOption.pre_conv = WC_TRUE; */ #endif if (w3m_backend) backend(); #if defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) if (getimage_args) { char *image_url = conv_from_system(getimage_args[0]); char *base_url = conv_from_system(getimage_args[1]); ParsedURL base_pu; parseURL2(base_url, &base_pu, NULL); image_source = getimage_args[2]; newbuf = loadGeneralFile(image_url, &base_pu, NULL, 0, NULL); if (!newbuf || !newbuf->real_type || strncasecmp(newbuf->real_type, "image/", 6)) unlink(getimage_args[2]); #if defined(HAVE_SYMLINK) && defined(HAVE_LSTAT) symlink(getimage_args[2], getimage_args[3]); #else { FILE *f = fopen(getimage_args[3], "w"); if (f) fclose(f); } #endif w3m_exit(0); } #endif /* defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) */ if (w3m_dump) mySignal(SIGINT, SIG_IGN); #ifdef SIGCHLD mySignal(SIGCHLD, sig_chld); #endif #ifdef SIGPIPE mySignal(SIGPIPE, SigPipe); #endif #if (GC_VERSION_MAJOR>7) || ((GC_VERSION_MAJOR==7) && (GC_VERSION_MINOR>=2)) orig_GC_warn_proc = GC_get_warn_proc(); GC_set_warn_proc(wrap_GC_warn_proc); #else orig_GC_warn_proc = GC_set_warn_proc(wrap_GC_warn_proc); #endif err_msg = Strnew(); if (load_argc == 0) { /* no URL specified */ if (!isatty(0)) { redin = newFileStream(fdopen(dup(0), "rb"), (void (*)())pclose); newbuf = openGeneralPagerBuffer(redin); dup2(1, 0); } else if (load_bookmark) { newbuf = loadGeneralFile(BookmarkFile, NULL, NO_REFERER, 0, NULL); if (newbuf == NULL) Strcat_charp(err_msg, "w3m: Can't load bookmark.\n"); } else if (visual_start) { /* FIXME: gettextize? */ Str s_page; s_page = Strnew_charp ("<title>W3M startup page</title><center><b>Welcome to "); Strcat_charp(s_page, "<a href='http://w3m.sourceforge.net/'>"); Strcat_m_charp(s_page, "w3m</a>!<p><p>This is w3m version ", w3m_version, "<br>Written by <a href='mailto:aito@fw.ipsj.or.jp'>Akinori Ito</a>", NULL); newbuf = loadHTMLString(s_page); if (newbuf == NULL) Strcat_charp(err_msg, "w3m: Can't load string.\n"); else if (newbuf != NO_BUFFER) newbuf->bufferprop |= (BP_INTERNAL | BP_NO_URL); } else if ((p = getenv("HTTP_HOME")) != NULL || (p = getenv("WWW_HOME")) != NULL) { newbuf = loadGeneralFile(p, NULL, NO_REFERER, 0, NULL); if (newbuf == NULL) Strcat(err_msg, Sprintf("w3m: Can't load %s.\n", p)); else if (newbuf != NO_BUFFER) pushHashHist(URLHist, parsedURL2Str(&newbuf->currentURL)->ptr); } else { if (fmInitialized) fmTerm(); usage(); } if (newbuf == NULL) { if (fmInitialized) fmTerm(); if (err_msg->length) fprintf(stderr, "%s", err_msg->ptr); w3m_exit(2); } i = -1; } else { i = 0; } for (; i < load_argc; i++) { if (i >= 0) { SearchHeader = search_header; DefaultType = default_type; char *url; url = load_argv[i]; if (getURLScheme(&url) == SCM_MISSING && !ArgvIsURL) url = file_to_url(load_argv[i]); else url = url_encode(conv_from_system(load_argv[i]), NULL, 0); if (w3m_dump == DUMP_HEAD) { request = New(FormList); request->method = FORM_METHOD_HEAD; newbuf = loadGeneralFile(url, NULL, NO_REFERER, 0, request); } else { if (post_file && i == 0) { FILE *fp; Str body; if (!strcmp(post_file, "-")) fp = stdin; else fp = fopen(post_file, "r"); if (fp == NULL) { /* FIXME: gettextize? */ Strcat(err_msg, Sprintf("w3m: Can't open %s.\n", post_file)); continue; } body = Strfgetall(fp); if (fp != stdin) fclose(fp); request = newFormList(NULL, "post", NULL, NULL, NULL, NULL, NULL); request->body = body->ptr; request->boundary = NULL; request->length = body->length; } else { request = NULL; } newbuf = loadGeneralFile(url, NULL, NO_REFERER, 0, request); } if (newbuf == NULL) { /* FIXME: gettextize? */ Strcat(err_msg, Sprintf("w3m: Can't load %s.\n", load_argv[i])); continue; } else if (newbuf == NO_BUFFER) continue; switch (newbuf->real_scheme) { case SCM_MAILTO: break; case SCM_LOCAL: case SCM_LOCAL_CGI: unshiftHist(LoadHist, url); default: pushHashHist(URLHist, parsedURL2Str(&newbuf->currentURL)->ptr); break; } } else if (newbuf == NO_BUFFER) continue; if (newbuf->pagerSource || (newbuf->real_scheme == SCM_LOCAL && newbuf->header_source && newbuf->currentURL.file && strcmp(newbuf->currentURL.file, "-"))) newbuf->search_header = search_header; if (CurrentTab == NULL) { FirstTab = LastTab = CurrentTab = newTab(); nTab = 1; Firstbuf = Currentbuf = newbuf; } else if (open_new_tab) { _newT(); Currentbuf->nextBuffer = newbuf; delBuffer(Currentbuf); } else { Currentbuf->nextBuffer = newbuf; Currentbuf = newbuf; } if (!w3m_dump || w3m_dump == DUMP_BUFFER) { if (Currentbuf->frameset != NULL && RenderFrame) rFrame(); } if (w3m_dump) do_dump(Currentbuf); else { Currentbuf = newbuf; #ifdef USE_BUFINFO saveBufferInfo(); #endif } } if (w3m_dump) { if (err_msg->length) fprintf(stderr, "%s", err_msg->ptr); #ifdef USE_COOKIE save_cookies(); #endif /* USE_COOKIE */ w3m_exit(0); } if (add_download_list) { add_download_list = FALSE; CurrentTab = LastTab; if (!FirstTab) { FirstTab = LastTab = CurrentTab = newTab(); nTab = 1; } if (!Firstbuf || Firstbuf == NO_BUFFER) { Firstbuf = Currentbuf = newBuffer(INIT_BUFFER_WIDTH); Currentbuf->bufferprop = BP_INTERNAL | BP_NO_URL; Currentbuf->buffername = DOWNLOAD_LIST_TITLE; } else Currentbuf = Firstbuf; ldDL(); } else CurrentTab = FirstTab; if (!FirstTab || !Firstbuf || Firstbuf == NO_BUFFER) { if (newbuf == NO_BUFFER) { if (fmInitialized) /* FIXME: gettextize? */ inputChar("Hit any key to quit w3m:"); } if (fmInitialized) fmTerm(); if (err_msg->length) fprintf(stderr, "%s", err_msg->ptr); if (newbuf == NO_BUFFER) { #ifdef USE_COOKIE save_cookies(); #endif /* USE_COOKIE */ if (!err_msg->length) w3m_exit(0); } w3m_exit(2); } if (err_msg->length) disp_message_nsec(err_msg->ptr, FALSE, 1, TRUE, FALSE); SearchHeader = FALSE; DefaultType = NULL; #ifdef USE_M17N UseContentCharset = TRUE; WcOption.auto_detect = auto_detect; #endif Currentbuf = Firstbuf; displayBuffer(Currentbuf, B_FORCE_REDRAW); if (line_str) { _goLine(line_str); } for (;;) { if (add_download_list) { add_download_list = FALSE; ldDL(); } if (Currentbuf->submit) { Anchor *a = Currentbuf->submit; Currentbuf->submit = NULL; gotoLine(Currentbuf, a->start.line); Currentbuf->pos = a->start.pos; _followForm(TRUE); continue; } /* event processing */ if (CurrentEvent) { CurrentKey = -1; CurrentKeyData = NULL; CurrentCmdData = (char *)CurrentEvent->data; w3mFuncList[CurrentEvent->cmd].func(); CurrentCmdData = NULL; CurrentEvent = CurrentEvent->next; continue; } /* get keypress event */ #ifdef USE_ALARM if (Currentbuf->event) { if (Currentbuf->event->status != AL_UNSET) { CurrentAlarm = Currentbuf->event; if (CurrentAlarm->sec == 0) { /* refresh (0sec) */ Currentbuf->event = NULL; CurrentKey = -1; CurrentKeyData = NULL; CurrentCmdData = (char *)CurrentAlarm->data; w3mFuncList[CurrentAlarm->cmd].func(); CurrentCmdData = NULL; continue; } } else Currentbuf->event = NULL; } if (!Currentbuf->event) CurrentAlarm = &DefaultAlarm; #endif #ifdef USE_MOUSE mouse_action.in_action = FALSE; if (use_mouse) mouse_active(); #endif /* USE_MOUSE */ #ifdef USE_ALARM if (CurrentAlarm->sec > 0) { mySignal(SIGALRM, SigAlarm); alarm(CurrentAlarm->sec); } #endif #ifdef SIGWINCH mySignal(SIGWINCH, resize_hook); #endif #ifdef USE_IMAGE if (activeImage && displayImage && Currentbuf->img && !Currentbuf->image_loaded) { do { #ifdef SIGWINCH if (need_resize_screen) resize_screen(); #endif loadImage(Currentbuf, IMG_FLAG_NEXT); } while (sleep_till_anykey(1, 0) <= 0); } #ifdef SIGWINCH else #endif #endif #ifdef SIGWINCH { do { if (need_resize_screen) resize_screen(); } while (sleep_till_anykey(1, 0) <= 0); } #endif c = getch(); #ifdef USE_ALARM if (CurrentAlarm->sec > 0) { alarm(0); } #endif #ifdef USE_MOUSE if (use_mouse) mouse_inactive(); #endif /* USE_MOUSE */ if (IS_ASCII(c)) { /* Ascii */ if (('0' <= c) && (c <= '9') && (prec_num || (GlobalKeymap[c] == FUNCNAME_nulcmd))) { prec_num = prec_num * 10 + (int)(c - '0'); if (prec_num > PREC_LIMIT) prec_num = PREC_LIMIT; } else { set_buffer_environ(Currentbuf); save_buffer_position(Currentbuf); keyPressEventProc((int)c); prec_num = 0; } } prev_key = CurrentKey; CurrentKey = -1; CurrentKeyData = NULL; } } static void keyPressEventProc(int c) { CurrentKey = c; w3mFuncList[(int)GlobalKeymap[c]].func(); } void pushEvent(int cmd, void *data) { Event *event; event = New(Event); event->cmd = cmd; event->data = data; event->next = NULL; if (CurrentEvent) LastEvent->next = event; else CurrentEvent = event; LastEvent = event; } static void dump_source(Buffer *buf) { FILE *f; int c; if (buf->sourcefile == NULL) return; f = fopen(buf->sourcefile, "r"); if (f == NULL) return; while ((c = fgetc(f)) != EOF) { putchar(c); } fclose(f); } static void dump_head(Buffer *buf) { TextListItem *ti; if (buf->document_header == NULL) { if (w3m_dump & DUMP_EXTRA) printf("\n"); return; } for (ti = buf->document_header->first; ti; ti = ti->next) { #ifdef USE_M17N printf("%s", wc_conv_strict(ti->ptr, InnerCharset, buf->document_charset)->ptr); #else printf("%s", ti->ptr); #endif } puts(""); } static void dump_extra(Buffer *buf) { printf("W3m-current-url: %s\n", parsedURL2Str(&buf->currentURL)->ptr); if (buf->baseURL) printf("W3m-base-url: %s\n", parsedURL2Str(buf->baseURL)->ptr); #ifdef USE_M17N printf("W3m-document-charset: %s\n", wc_ces_to_charset(buf->document_charset)); #endif #ifdef USE_SSL if (buf->ssl_certificate) { Str tmp = Strnew(); char *p; for (p = buf->ssl_certificate; *p; p++) { Strcat_char(tmp, *p); if (*p == '\n') { for (; *(p + 1) == '\n'; p++) ; if (*(p + 1)) Strcat_char(tmp, '\t'); } } if (Strlastchar(tmp) != '\n') Strcat_char(tmp, '\n'); printf("W3m-ssl-certificate: %s", tmp->ptr); } #endif } static int cmp_anchor_hseq(const void *a, const void *b) { return (*((const Anchor **) a))->hseq - (*((const Anchor **) b))->hseq; } static void do_dump(Buffer *buf) { MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL; prevtrap = mySignal(SIGINT, intTrap); if (SETJMP(IntReturn) != 0) { mySignal(SIGINT, prevtrap); return; } if (w3m_dump & DUMP_EXTRA) dump_extra(buf); if (w3m_dump & DUMP_HEAD) dump_head(buf); if (w3m_dump & DUMP_SOURCE) dump_source(buf); if (w3m_dump == DUMP_BUFFER) { int i; saveBuffer(buf, stdout, FALSE); if (displayLinkNumber && buf->href) { int nanchor = buf->href->nanchor; printf("\nReferences:\n\n"); Anchor **in_order = New_N(Anchor *, buf->href->nanchor); for (i = 0; i < nanchor; i++) in_order[i] = buf->href->anchors + i; qsort(in_order, nanchor, sizeof(Anchor *), cmp_anchor_hseq); for (i = 0; i < nanchor; i++) { ParsedURL pu; char *url; if (in_order[i]->slave) continue; parseURL2(in_order[i]->url, &pu, baseURL(buf)); url = url_decode2(parsedURL2Str(&pu)->ptr, Currentbuf); printf("[%d] %s\n", in_order[i]->hseq + 1, url); } } } mySignal(SIGINT, prevtrap); } DEFUN(nulcmd, NOTHING NULL @@@, "Do nothing") { /* do nothing */ } #ifdef __EMX__ DEFUN(pcmap, PCMAP, "pcmap") { w3mFuncList[(int)PcKeymap[(int)getch()]].func(); } #else /* not __EMX__ */ void pcmap(void) { } #endif static void escKeyProc(int c, int esc, unsigned char *map) { if (CurrentKey >= 0 && CurrentKey & K_MULTI) { unsigned char **mmap; mmap = (unsigned char **)getKeyData(MULTI_KEY(CurrentKey)); if (!mmap) return; switch (esc) { case K_ESCD: map = mmap[3]; break; case K_ESCB: map = mmap[2]; break; case K_ESC: map = mmap[1]; break; default: map = mmap[0]; break; } esc |= (CurrentKey & ~0xFFFF); } CurrentKey = esc | c; w3mFuncList[(int)map[c]].func(); } DEFUN(escmap, ESCMAP, "ESC map") { char c; c = getch(); if (IS_ASCII(c)) escKeyProc((int)c, K_ESC, EscKeymap); } DEFUN(escbmap, ESCBMAP, "ESC [ map") { char c; c = getch(); if (IS_DIGIT(c)) { escdmap(c); return; } if (IS_ASCII(c)) escKeyProc((int)c, K_ESCB, EscBKeymap); } void escdmap(char c) { int d; d = (int)c - (int)'0'; c = getch(); if (IS_DIGIT(c)) { d = d * 10 + (int)c - (int)'0'; c = getch(); } if (c == '~') escKeyProc((int)d, K_ESCD, EscDKeymap); } DEFUN(multimap, MULTIMAP, "multimap") { char c; c = getch(); if (IS_ASCII(c)) { CurrentKey = K_MULTI | (CurrentKey << 16) | c; escKeyProc((int)c, 0, NULL); } } void tmpClearBuffer(Buffer *buf) { if (buf->pagerSource == NULL && writeBufferCache(buf) == 0) { buf->firstLine = NULL; buf->topLine = NULL; buf->currentLine = NULL; buf->lastLine = NULL; } } static Str currentURL(void); #ifdef USE_BUFINFO void saveBufferInfo() { FILE *fp; if (w3m_dump) return; if ((fp = fopen(rcFile("bufinfo"), "w")) == NULL) { return; } fprintf(fp, "%s\n", currentURL()->ptr); fclose(fp); } #endif static void pushBuffer(Buffer *buf) { Buffer *b; #ifdef USE_IMAGE deleteImage(Currentbuf); #endif if (clear_buffer) tmpClearBuffer(Currentbuf); if (Firstbuf == Currentbuf) { buf->nextBuffer = Firstbuf; Firstbuf = Currentbuf = buf; } else if ((b = prevBuffer(Firstbuf, Currentbuf)) != NULL) { b->nextBuffer = buf; buf->nextBuffer = Currentbuf; Currentbuf = buf; } #ifdef USE_BUFINFO saveBufferInfo(); #endif } static void delBuffer(Buffer *buf) { if (buf == NULL) return; if (Currentbuf == buf) Currentbuf = buf->nextBuffer; Firstbuf = deleteBuffer(Firstbuf, buf); if (!Currentbuf) Currentbuf = Firstbuf; } static void repBuffer(Buffer *oldbuf, Buffer *buf) { Firstbuf = replaceBuffer(Firstbuf, oldbuf, buf); Currentbuf = buf; } MySignalHandler intTrap(SIGNAL_ARG) { /* Interrupt catcher */ LONGJMP(IntReturn, 0); SIGNAL_RETURN; } #ifdef SIGWINCH static MySignalHandler resize_hook(SIGNAL_ARG) { need_resize_screen = TRUE; mySignal(SIGWINCH, resize_hook); SIGNAL_RETURN; } static void resize_screen(void) { need_resize_screen = FALSE; setlinescols(); setupscreen(); if (CurrentTab) displayBuffer(Currentbuf, B_FORCE_REDRAW); } #endif /* SIGWINCH */ #ifdef SIGPIPE static MySignalHandler SigPipe(SIGNAL_ARG) { #ifdef USE_MIGEMO init_migemo(); #endif mySignal(SIGPIPE, SigPipe); SIGNAL_RETURN; } #endif /* * Command functions: These functions are called with a keystroke. */ static void nscroll(int n, int mode) { Buffer *buf = Currentbuf; Line *top = buf->topLine, *cur = buf->currentLine; int lnum, tlnum, llnum, diff_n; if (buf->firstLine == NULL) return; lnum = cur->linenumber; buf->topLine = lineSkip(buf, top, n, FALSE); if (buf->topLine == top) { lnum += n; if (lnum < buf->topLine->linenumber) lnum = buf->topLine->linenumber; else if (lnum > buf->lastLine->linenumber) lnum = buf->lastLine->linenumber; } else { tlnum = buf->topLine->linenumber; llnum = buf->topLine->linenumber + buf->LINES - 1; if (nextpage_topline) diff_n = 0; else diff_n = n - (tlnum - top->linenumber); if (lnum < tlnum) lnum = tlnum + diff_n; if (lnum > llnum) lnum = llnum + diff_n; } gotoLine(buf, lnum); arrangeLine(buf); if (n > 0) { if (buf->currentLine->bpos && buf->currentLine->bwidth >= buf->currentColumn + buf->visualpos) cursorDown(buf, 1); else { while (buf->currentLine->next && buf->currentLine->next->bpos && buf->currentLine->bwidth + buf->currentLine->width < buf->currentColumn + buf->visualpos) cursorDown0(buf, 1); } } else { if (buf->currentLine->bwidth + buf->currentLine->width < buf->currentColumn + buf->visualpos) cursorUp(buf, 1); else { while (buf->currentLine->prev && buf->currentLine->bpos && buf->currentLine->bwidth >= buf->currentColumn + buf->visualpos) cursorUp0(buf, 1); } } displayBuffer(buf, mode); } /* Move page forward */ DEFUN(pgFore, NEXT_PAGE, "Scroll down one page") { if (vi_prec_num) nscroll(searchKeyNum() * (Currentbuf->LINES - 1), B_NORMAL); else nscroll(prec_num ? searchKeyNum() : searchKeyNum() * (Currentbuf->LINES - 1), prec_num ? B_SCROLL : B_NORMAL); } /* Move page backward */ DEFUN(pgBack, PREV_PAGE, "Scroll up one page") { if (vi_prec_num) nscroll(-searchKeyNum() * (Currentbuf->LINES - 1), B_NORMAL); else nscroll(-(prec_num ? searchKeyNum() : searchKeyNum() * (Currentbuf->LINES - 1)), prec_num ? B_SCROLL : B_NORMAL); } /* Move half page forward */ DEFUN(hpgFore, NEXT_HALF_PAGE, "Scroll down half a page") { nscroll(searchKeyNum() * (Currentbuf->LINES / 2 - 1), B_NORMAL); } /* Move half page backward */ DEFUN(hpgBack, PREV_HALF_PAGE, "Scroll up half a page") { nscroll(-searchKeyNum() * (Currentbuf->LINES / 2 - 1), B_NORMAL); } /* 1 line up */ DEFUN(lup1, UP, "Scroll the screen up one line") { nscroll(searchKeyNum(), B_SCROLL); } /* 1 line down */ DEFUN(ldown1, DOWN, "Scroll the screen down one line") { nscroll(-searchKeyNum(), B_SCROLL); } /* move cursor position to the center of screen */ DEFUN(ctrCsrV, CENTER_V, "Center on cursor line") { int offsety; if (Currentbuf->firstLine == NULL) return; offsety = Currentbuf->LINES / 2 - Currentbuf->cursorY; if (offsety != 0) { #if 0 Currentbuf->currentLine = lineSkip(Currentbuf, Currentbuf->currentLine, offsety, FALSE); #endif Currentbuf->topLine = lineSkip(Currentbuf, Currentbuf->topLine, -offsety, FALSE); arrangeLine(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } } DEFUN(ctrCsrH, CENTER_H, "Center on cursor column") { int offsetx; if (Currentbuf->firstLine == NULL) return; offsetx = Currentbuf->cursorX - Currentbuf->COLS / 2; if (offsetx != 0) { columnSkip(Currentbuf, offsetx); arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } } /* Redraw screen */ DEFUN(rdrwSc, REDRAW, "Draw the screen anew") { clear(); arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } static void clear_mark(Line *l) { int pos; if (!l) return; for (pos = 0; pos < l->size; pos++) l->propBuf[pos] &= ~PE_MARK; } /* search by regular expression */ static int srchcore(char *volatile str, int (*func) (Buffer *, char *)) { MySignalHandler(*prevtrap) (); volatile int i, result = SR_NOTFOUND; if (str != NULL && str != SearchString) SearchString = str; if (SearchString == NULL || *SearchString == '\0') return SR_NOTFOUND; str = conv_search_string(SearchString, DisplayCharset); prevtrap = mySignal(SIGINT, intTrap); crmode(); if (SETJMP(IntReturn) == 0) { for (i = 0; i < PREC_NUM; i++) { result = func(Currentbuf, str); if (i < PREC_NUM - 1 && result & SR_FOUND) clear_mark(Currentbuf->currentLine); } } mySignal(SIGINT, prevtrap); term_raw(); return result; } static void disp_srchresult(int result, char *prompt, char *str) { if (str == NULL) str = ""; if (result & SR_NOTFOUND) disp_message(Sprintf("Not found: %s", str)->ptr, TRUE); else if (result & SR_WRAPPED) disp_message(Sprintf("Search wrapped: %s", str)->ptr, TRUE); else if (show_srch_str) disp_message(Sprintf("%s%s", prompt, str)->ptr, TRUE); } static int dispincsrch(int ch, Str buf, Lineprop *prop) { static Buffer sbuf; static Line *currentLine; static int pos; char *str; int do_next_search = FALSE; if (ch == 0 && buf == NULL) { SAVE_BUFPOSITION(&sbuf); /* search starting point */ currentLine = sbuf.currentLine; pos = sbuf.pos; return -1; } str = buf->ptr; switch (ch) { case 022: /* C-r */ searchRoutine = backwardSearch; do_next_search = TRUE; break; case 023: /* C-s */ searchRoutine = forwardSearch; do_next_search = TRUE; break; #ifdef USE_MIGEMO case 034: migemo_active = -migemo_active; goto done; #endif default: if (ch >= 0) return ch; /* use InputKeymap */ } if (do_next_search) { if (*str) { if (searchRoutine == forwardSearch) Currentbuf->pos += 1; SAVE_BUFPOSITION(&sbuf); if (srchcore(str, searchRoutine) == SR_NOTFOUND && searchRoutine == forwardSearch) { Currentbuf->pos -= 1; SAVE_BUFPOSITION(&sbuf); } arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); clear_mark(Currentbuf->currentLine); return -1; } else return 020; /* _prev completion for C-s C-s */ } else if (*str) { RESTORE_BUFPOSITION(&sbuf); arrangeCursor(Currentbuf); srchcore(str, searchRoutine); arrangeCursor(Currentbuf); currentLine = Currentbuf->currentLine; pos = Currentbuf->pos; } displayBuffer(Currentbuf, B_FORCE_REDRAW); clear_mark(Currentbuf->currentLine); #ifdef USE_MIGEMO done: while (*str++ != '\0') { if (migemo_active > 0) *prop++ |= PE_UNDER; else *prop++ &= ~PE_UNDER; } #endif return -1; } void isrch(int (*func) (Buffer *, char *), char *prompt) { char *str; Buffer sbuf; SAVE_BUFPOSITION(&sbuf); dispincsrch(0, NULL, NULL); /* initialize incremental search state */ searchRoutine = func; str = inputLineHistSearch(prompt, NULL, IN_STRING, TextHist, dispincsrch); if (str == NULL) { RESTORE_BUFPOSITION(&sbuf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } void srch(int (*func) (Buffer *, char *), char *prompt) { char *str; int result; int disp = FALSE; int pos; str = searchKeyData(); if (str == NULL || *str == '\0') { str = inputStrHist(prompt, NULL, TextHist); if (str != NULL && *str == '\0') str = SearchString; if (str == NULL) { displayBuffer(Currentbuf, B_NORMAL); return; } disp = TRUE; } pos = Currentbuf->pos; if (func == forwardSearch) Currentbuf->pos += 1; result = srchcore(str, func); if (result & SR_FOUND) clear_mark(Currentbuf->currentLine); else Currentbuf->pos = pos; displayBuffer(Currentbuf, B_NORMAL); if (disp) disp_srchresult(result, prompt, str); searchRoutine = func; } /* Search regular expression forward */ DEFUN(srchfor, SEARCH SEARCH_FORE WHEREIS, "Search forward") { srch(forwardSearch, "Forward: "); } DEFUN(isrchfor, ISEARCH, "Incremental search forward") { isrch(forwardSearch, "I-search: "); } /* Search regular expression backward */ DEFUN(srchbak, SEARCH_BACK, "Search backward") { srch(backwardSearch, "Backward: "); } DEFUN(isrchbak, ISEARCH_BACK, "Incremental search backward") { isrch(backwardSearch, "I-search backward: "); } static void srch_nxtprv(int reverse) { int result; /* *INDENT-OFF* */ static int (*routine[2]) (Buffer *, char *) = { forwardSearch, backwardSearch }; /* *INDENT-ON* */ if (searchRoutine == NULL) { /* FIXME: gettextize? */ disp_message("No previous regular expression", TRUE); return; } if (reverse != 0) reverse = 1; if (searchRoutine == backwardSearch) reverse ^= 1; if (reverse == 0) Currentbuf->pos += 1; result = srchcore(SearchString, routine[reverse]); if (result & SR_FOUND) clear_mark(Currentbuf->currentLine); else { if (reverse == 0) Currentbuf->pos -= 1; } displayBuffer(Currentbuf, B_NORMAL); disp_srchresult(result, (reverse ? "Backward: " : "Forward: "), SearchString); } /* Search next matching */ DEFUN(srchnxt, SEARCH_NEXT, "Continue search forward") { srch_nxtprv(0); } /* Search previous matching */ DEFUN(srchprv, SEARCH_PREV, "Continue search backward") { srch_nxtprv(1); } static void shiftvisualpos(Buffer *buf, int shift) { Line *l = buf->currentLine; buf->visualpos -= shift; if (buf->visualpos - l->bwidth >= buf->COLS) buf->visualpos = l->bwidth + buf->COLS - 1; else if (buf->visualpos - l->bwidth < 0) buf->visualpos = l->bwidth; arrangeLine(buf); if (buf->visualpos - l->bwidth == -shift && buf->cursorX == 0) buf->visualpos = l->bwidth; } /* Shift screen left */ DEFUN(shiftl, SHIFT_LEFT, "Shift screen left") { int column; if (Currentbuf->firstLine == NULL) return; column = Currentbuf->currentColumn; columnSkip(Currentbuf, searchKeyNum() * (-Currentbuf->COLS + 1) + 1); shiftvisualpos(Currentbuf, Currentbuf->currentColumn - column); displayBuffer(Currentbuf, B_NORMAL); } /* Shift screen right */ DEFUN(shiftr, SHIFT_RIGHT, "Shift screen right") { int column; if (Currentbuf->firstLine == NULL) return; column = Currentbuf->currentColumn; columnSkip(Currentbuf, searchKeyNum() * (Currentbuf->COLS - 1) - 1); shiftvisualpos(Currentbuf, Currentbuf->currentColumn - column); displayBuffer(Currentbuf, B_NORMAL); } DEFUN(col1R, RIGHT, "Shift screen one column right") { Buffer *buf = Currentbuf; Line *l = buf->currentLine; int j, column, n = searchKeyNum(); if (l == NULL) return; for (j = 0; j < n; j++) { column = buf->currentColumn; columnSkip(Currentbuf, 1); if (column == buf->currentColumn) break; shiftvisualpos(Currentbuf, 1); } displayBuffer(Currentbuf, B_NORMAL); } DEFUN(col1L, LEFT, "Shift screen one column left") { Buffer *buf = Currentbuf; Line *l = buf->currentLine; int j, n = searchKeyNum(); if (l == NULL) return; for (j = 0; j < n; j++) { if (buf->currentColumn == 0) break; columnSkip(Currentbuf, -1); shiftvisualpos(Currentbuf, -1); } displayBuffer(Currentbuf, B_NORMAL); } DEFUN(setEnv, SETENV, "Set environment variable") { char *env; char *var, *value; CurrentKeyData = NULL; /* not allowed in w3m-control: */ env = searchKeyData(); if (env == NULL || *env == '\0' || strchr(env, '=') == NULL) { if (env != NULL && *env != '\0') env = Sprintf("%s=", env)->ptr; env = inputStrHist("Set environ: ", env, TextHist); if (env == NULL || *env == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } } if ((value = strchr(env, '=')) != NULL && value > env) { var = allocStr(env, value - env); value++; set_environ(var, value); } displayBuffer(Currentbuf, B_NORMAL); } DEFUN(pipeBuf, PIPE_BUF, "Pipe current buffer through a shell command and display output") { Buffer *buf; char *cmd, *tmpf; FILE *f; CurrentKeyData = NULL; /* not allowed in w3m-control: */ cmd = searchKeyData(); if (cmd == NULL || *cmd == '\0') { /* FIXME: gettextize? */ cmd = inputLineHist("Pipe buffer to: ", "", IN_COMMAND, ShellHist); } if (cmd != NULL) cmd = conv_to_system(cmd); if (cmd == NULL || *cmd == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } tmpf = tmpfname(TMPF_DFL, NULL)->ptr; f = fopen(tmpf, "w"); if (f == NULL) { /* FIXME: gettextize? */ disp_message(Sprintf("Can't save buffer to %s", cmd)->ptr, TRUE); return; } saveBuffer(Currentbuf, f, TRUE); fclose(f); buf = getpipe(myExtCommand(cmd, shell_quote(tmpf), TRUE)->ptr); if (buf == NULL) { disp_message("Execution failed", TRUE); return; } else { buf->filename = cmd; buf->buffername = Sprintf("%s %s", PIPEBUFFERNAME, conv_from_system(cmd))->ptr; buf->bufferprop |= (BP_INTERNAL | BP_NO_URL); if (buf->type == NULL) buf->type = "text/plain"; buf->currentURL.file = "-"; pushBuffer(buf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Execute shell command and read output ac pipe. */ DEFUN(pipesh, PIPE_SHELL, "Execute shell command and display output") { Buffer *buf; char *cmd; CurrentKeyData = NULL; /* not allowed in w3m-control: */ cmd = searchKeyData(); if (cmd == NULL || *cmd == '\0') { cmd = inputLineHist("(read shell[pipe])!", "", IN_COMMAND, ShellHist); } if (cmd != NULL) cmd = conv_to_system(cmd); if (cmd == NULL || *cmd == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } buf = getpipe(cmd); if (buf == NULL) { disp_message("Execution failed", TRUE); return; } else { buf->bufferprop |= (BP_INTERNAL | BP_NO_URL); if (buf->type == NULL) buf->type = "text/plain"; pushBuffer(buf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Execute shell command and load entire output to buffer */ DEFUN(readsh, READ_SHELL, "Execute shell command and display output") { Buffer *buf; MySignalHandler(*prevtrap) (); char *cmd; CurrentKeyData = NULL; /* not allowed in w3m-control: */ cmd = searchKeyData(); if (cmd == NULL || *cmd == '\0') { cmd = inputLineHist("(read shell)!", "", IN_COMMAND, ShellHist); } if (cmd != NULL) cmd = conv_to_system(cmd); if (cmd == NULL || *cmd == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } prevtrap = mySignal(SIGINT, intTrap); crmode(); buf = getshell(cmd); mySignal(SIGINT, prevtrap); term_raw(); if (buf == NULL) { /* FIXME: gettextize? */ disp_message("Execution failed", TRUE); return; } else { buf->bufferprop |= (BP_INTERNAL | BP_NO_URL); if (buf->type == NULL) buf->type = "text/plain"; pushBuffer(buf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Execute shell command */ DEFUN(execsh, EXEC_SHELL SHELL, "Execute shell command and display output") { char *cmd; CurrentKeyData = NULL; /* not allowed in w3m-control: */ cmd = searchKeyData(); if (cmd == NULL || *cmd == '\0') { cmd = inputLineHist("(exec shell)!", "", IN_COMMAND, ShellHist); } if (cmd != NULL) cmd = conv_to_system(cmd); if (cmd != NULL && *cmd != '\0') { fmTerm(); printf("\n"); system(cmd); /* FIXME: gettextize? */ printf("\n[Hit any key]"); fflush(stdout); fmInit(); getch(); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Load file */ DEFUN(ldfile, LOAD, "Open local file in a new buffer") { char *fn; fn = searchKeyData(); if (fn == NULL || *fn == '\0') { /* FIXME: gettextize? */ fn = inputFilenameHist("(Load)Filename? ", NULL, LoadHist); } if (fn != NULL) fn = conv_to_system(fn); if (fn == NULL || *fn == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } cmd_loadfile(fn); } /* Load help file */ DEFUN(ldhelp, HELP, "Show help panel") { #ifdef USE_HELP_CGI char *lang; int n; Str tmp; lang = AcceptLang; n = strcspn(lang, ";, \t"); tmp = Sprintf("file:///$LIB/" HELP_CGI CGI_EXTENSION "?version=%s&lang=%s", Str_form_quote(Strnew_charp(w3m_version))->ptr, Str_form_quote(Strnew_charp_n(lang, n))->ptr); cmd_loadURL(tmp->ptr, NULL, NO_REFERER, NULL); #else cmd_loadURL(helpFile(HELP_FILE), NULL, NO_REFERER, NULL); #endif } static void cmd_loadfile(char *fn) { Buffer *buf; buf = loadGeneralFile(file_to_url(fn), NULL, NO_REFERER, 0, NULL); if (buf == NULL) { /* FIXME: gettextize? */ char *emsg = Sprintf("%s not found", conv_from_system(fn))->ptr; disp_err_message(emsg, FALSE); } else if (buf != NO_BUFFER) { pushBuffer(buf); if (RenderFrame && Currentbuf->frameset != NULL) rFrame(); } displayBuffer(Currentbuf, B_NORMAL); } /* Move cursor left */ static void _movL(int n) { int i, m = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; for (i = 0; i < m; i++) cursorLeft(Currentbuf, n); displayBuffer(Currentbuf, B_NORMAL); } DEFUN(movL, MOVE_LEFT, "Cursor left") { _movL(Currentbuf->COLS / 2); } DEFUN(movL1, MOVE_LEFT1, "Cursor left. With edge touched, slide") { _movL(1); } /* Move cursor downward */ static void _movD(int n) { int i, m = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; for (i = 0; i < m; i++) cursorDown(Currentbuf, n); displayBuffer(Currentbuf, B_NORMAL); } DEFUN(movD, MOVE_DOWN, "Cursor down") { _movD((Currentbuf->LINES + 1) / 2); } DEFUN(movD1, MOVE_DOWN1, "Cursor down. With edge touched, slide") { _movD(1); } /* move cursor upward */ static void _movU(int n) { int i, m = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; for (i = 0; i < m; i++) cursorUp(Currentbuf, n); displayBuffer(Currentbuf, B_NORMAL); } DEFUN(movU, MOVE_UP, "Cursor up") { _movU((Currentbuf->LINES + 1) / 2); } DEFUN(movU1, MOVE_UP1, "Cursor up. With edge touched, slide") { _movU(1); } /* Move cursor right */ static void _movR(int n) { int i, m = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; for (i = 0; i < m; i++) cursorRight(Currentbuf, n); displayBuffer(Currentbuf, B_NORMAL); } DEFUN(movR, MOVE_RIGHT, "Cursor right") { _movR(Currentbuf->COLS / 2); } DEFUN(movR1, MOVE_RIGHT1, "Cursor right. With edge touched, slide") { _movR(1); } /* movLW, movRW */ /* * From: Takashi Nishimoto <g96p0935@mse.waseda.ac.jp> Date: Mon, 14 Jun * 1999 09:29:56 +0900 */ #if defined(USE_M17N) && defined(USE_UNICODE) #define nextChar(s, l) do { (s)++; } while ((s) < (l)->len && (l)->propBuf[s] & PC_WCHAR2) #define prevChar(s, l) do { (s)--; } while ((s) > 0 && (l)->propBuf[s] & PC_WCHAR2) static wc_uint32 getChar(char *p) { return wc_any_to_ucs(wtf_parse1((wc_uchar **)&p)); } static int is_wordchar(wc_uint32 c) { return wc_is_ucs_alnum(c); } #else #define nextChar(s, l) (s)++ #define prevChar(s, l) (s)-- #define getChar(p) ((int)*(p)) static int is_wordchar(int c) { return IS_ALNUM(c); } #endif static int prev_nonnull_line(Line *line) { Line *l; for (l = line; l != NULL && l->len == 0; l = l->prev) ; if (l == NULL || l->len == 0) return -1; Currentbuf->currentLine = l; if (l != line) Currentbuf->pos = Currentbuf->currentLine->len; return 0; } DEFUN(movLW, PREV_WORD, "Move to the previous word") { char *lb; Line *pline, *l; int ppos; int i, n = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; for (i = 0; i < n; i++) { pline = Currentbuf->currentLine; ppos = Currentbuf->pos; if (prev_nonnull_line(Currentbuf->currentLine) < 0) goto end; while (1) { l = Currentbuf->currentLine; lb = l->lineBuf; while (Currentbuf->pos > 0) { int tmp = Currentbuf->pos; prevChar(tmp, l); if (is_wordchar(getChar(&lb[tmp]))) break; Currentbuf->pos = tmp; } if (Currentbuf->pos > 0) break; if (prev_nonnull_line(Currentbuf->currentLine->prev) < 0) { Currentbuf->currentLine = pline; Currentbuf->pos = ppos; goto end; } Currentbuf->pos = Currentbuf->currentLine->len; } l = Currentbuf->currentLine; lb = l->lineBuf; while (Currentbuf->pos > 0) { int tmp = Currentbuf->pos; prevChar(tmp, l); if (!is_wordchar(getChar(&lb[tmp]))) break; Currentbuf->pos = tmp; } } end: arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } static int next_nonnull_line(Line *line) { Line *l; for (l = line; l != NULL && l->len == 0; l = l->next) ; if (l == NULL || l->len == 0) return -1; Currentbuf->currentLine = l; if (l != line) Currentbuf->pos = 0; return 0; } DEFUN(movRW, NEXT_WORD, "Move to the next word") { char *lb; Line *pline, *l; int ppos; int i, n = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; for (i = 0; i < n; i++) { pline = Currentbuf->currentLine; ppos = Currentbuf->pos; if (next_nonnull_line(Currentbuf->currentLine) < 0) goto end; l = Currentbuf->currentLine; lb = l->lineBuf; while (Currentbuf->pos < l->len && is_wordchar(getChar(&lb[Currentbuf->pos]))) nextChar(Currentbuf->pos, l); while (1) { while (Currentbuf->pos < l->len && !is_wordchar(getChar(&lb[Currentbuf->pos]))) nextChar(Currentbuf->pos, l); if (Currentbuf->pos < l->len) break; if (next_nonnull_line(Currentbuf->currentLine->next) < 0) { Currentbuf->currentLine = pline; Currentbuf->pos = ppos; goto end; } Currentbuf->pos = 0; l = Currentbuf->currentLine; lb = l->lineBuf; } } end: arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } static void _quitfm(int confirm) { char *ans = "y"; if (checkDownloadList()) /* FIXME: gettextize? */ ans = inputChar("Download process retains. " "Do you want to exit w3m? (y/n)"); else if (confirm) /* FIXME: gettextize? */ ans = inputChar("Do you want to exit w3m? (y/n)"); if (!(ans && TOLOWER(*ans) == 'y')) { displayBuffer(Currentbuf, B_NORMAL); return; } term_title(""); /* XXX */ #ifdef USE_IMAGE if (activeImage) termImage(); #endif fmTerm(); #ifdef USE_COOKIE save_cookies(); #endif /* USE_COOKIE */ #ifdef USE_HISTORY if (UseHistory && SaveURLHist) saveHistory(URLHist, URLHistSize); #endif /* USE_HISTORY */ w3m_exit(0); } /* Quit */ DEFUN(quitfm, ABORT EXIT, "Quit at once") { _quitfm(FALSE); } /* Question and Quit */ DEFUN(qquitfm, QUIT, "Quit with confirmation request") { _quitfm(confirm_on_quit); } /* Select buffer */ DEFUN(selBuf, SELECT, "Display buffer-stack panel") { Buffer *buf; int ok; char cmd; ok = FALSE; do { buf = selectBuffer(Firstbuf, Currentbuf, &cmd); switch (cmd) { case 'B': ok = TRUE; break; case '\n': case ' ': Currentbuf = buf; ok = TRUE; break; case 'D': delBuffer(buf); if (Firstbuf == NULL) { /* No more buffer */ Firstbuf = nullBuffer(); Currentbuf = Firstbuf; } break; case 'q': qquitfm(); break; case 'Q': quitfm(); break; } } while (!ok); for (buf = Firstbuf; buf != NULL; buf = buf->nextBuffer) { if (buf == Currentbuf) continue; #ifdef USE_IMAGE deleteImage(buf); #endif if (clear_buffer) tmpClearBuffer(buf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Suspend (on BSD), or run interactive shell (on SysV) */ DEFUN(susp, INTERRUPT SUSPEND, "Suspend w3m to background") { #ifndef SIGSTOP char *shell; #endif /* not SIGSTOP */ move(LASTLINE, 0); clrtoeolx(); refresh(); fmTerm(); #ifndef SIGSTOP shell = getenv("SHELL"); if (shell == NULL) shell = "/bin/sh"; system(shell); #else /* SIGSTOP */ #ifdef SIGTSTP signal(SIGTSTP, SIG_DFL); /* just in case */ /* * Note: If susp() was called from SIGTSTP handler, * unblocking SIGTSTP would be required here. * Currently not. */ kill(0, SIGTSTP); /* stop whole job, not a single process */ #else kill((pid_t) 0, SIGSTOP); #endif #endif /* SIGSTOP */ fmInit(); displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Go to specified line */ static void _goLine(char *l) { if (l == NULL || *l == '\0' || Currentbuf->currentLine == NULL) { displayBuffer(Currentbuf, B_FORCE_REDRAW); return; } Currentbuf->pos = 0; if (((*l == '^') || (*l == '$')) && prec_num) { gotoRealLine(Currentbuf, prec_num); } else if (*l == '^') { Currentbuf->topLine = Currentbuf->currentLine = Currentbuf->firstLine; } else if (*l == '$') { Currentbuf->topLine = lineSkip(Currentbuf, Currentbuf->lastLine, -(Currentbuf->LINES + 1) / 2, TRUE); Currentbuf->currentLine = Currentbuf->lastLine; } else gotoRealLine(Currentbuf, atoi(l)); arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(goLine, GOTO_LINE, "Go to the specified line") { char *str = searchKeyData(); if (prec_num) _goLine("^"); else if (str) _goLine(str); else /* FIXME: gettextize? */ _goLine(inputStr("Goto line: ", "")); } DEFUN(goLineF, BEGIN, "Go to the first line") { _goLine("^"); } DEFUN(goLineL, END, "Go to the last line") { _goLine("$"); } /* Go to the beginning of the line */ DEFUN(linbeg, LINE_BEGIN, "Go to the beginning of the line") { if (Currentbuf->firstLine == NULL) return; while (Currentbuf->currentLine->prev && Currentbuf->currentLine->bpos) cursorUp0(Currentbuf, 1); Currentbuf->pos = 0; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* Go to the bottom of the line */ DEFUN(linend, LINE_END, "Go to the end of the line") { if (Currentbuf->firstLine == NULL) return; while (Currentbuf->currentLine->next && Currentbuf->currentLine->next->bpos) cursorDown0(Currentbuf, 1); Currentbuf->pos = Currentbuf->currentLine->len - 1; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } static int cur_real_linenumber(Buffer *buf) { Line *l, *cur = buf->currentLine; int n; if (!cur) return 1; n = cur->real_linenumber ? cur->real_linenumber : 1; for (l = buf->firstLine; l && l != cur && l->real_linenumber == 0; l = l->next) { /* header */ if (l->bpos == 0) n++; } return n; } /* Run editor on the current buffer */ DEFUN(editBf, EDIT, "Edit local source") { char *fn = Currentbuf->filename; Str cmd; if (fn == NULL || Currentbuf->pagerSource != NULL || /* Behaving as a pager */ (Currentbuf->type == NULL && Currentbuf->edit == NULL) || /* Reading shell */ Currentbuf->real_scheme != SCM_LOCAL || !strcmp(Currentbuf->currentURL.file, "-") || /* file is std input */ Currentbuf->bufferprop & BP_FRAME) { /* Frame */ disp_err_message("Can't edit other than local file", TRUE); return; } if (Currentbuf->edit) cmd = unquote_mailcap(Currentbuf->edit, Currentbuf->real_type, fn, checkHeader(Currentbuf, "Content-Type:"), NULL); else cmd = myEditor(Editor, shell_quote(fn), cur_real_linenumber(Currentbuf)); fmTerm(); system(cmd->ptr); fmInit(); displayBuffer(Currentbuf, B_FORCE_REDRAW); reload(); } /* Run editor on the current screen */ DEFUN(editScr, EDIT_SCREEN, "Edit rendered copy of document") { char *tmpf; FILE *f; tmpf = tmpfname(TMPF_DFL, NULL)->ptr; f = fopen(tmpf, "w"); if (f == NULL) { /* FIXME: gettextize? */ disp_err_message(Sprintf("Can't open %s", tmpf)->ptr, TRUE); return; } saveBuffer(Currentbuf, f, TRUE); fclose(f); fmTerm(); system(myEditor(Editor, shell_quote(tmpf), cur_real_linenumber(Currentbuf))->ptr); fmInit(); unlink(tmpf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } #ifdef USE_MARK /* Set / unset mark */ DEFUN(_mark, MARK, "Set/unset mark") { Line *l; if (!use_mark) return; if (Currentbuf->firstLine == NULL) return; l = Currentbuf->currentLine; l->propBuf[Currentbuf->pos] ^= PE_MARK; displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Go to next mark */ DEFUN(nextMk, NEXT_MARK, "Go to the next mark") { Line *l; int i; if (!use_mark) return; if (Currentbuf->firstLine == NULL) return; i = Currentbuf->pos + 1; l = Currentbuf->currentLine; if (i >= l->len) { i = 0; l = l->next; } while (l != NULL) { for (; i < l->len; i++) { if (l->propBuf[i] & PE_MARK) { Currentbuf->currentLine = l; Currentbuf->pos = i; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); return; } } l = l->next; i = 0; } /* FIXME: gettextize? */ disp_message("No mark exist after here", TRUE); } /* Go to previous mark */ DEFUN(prevMk, PREV_MARK, "Go to the previous mark") { Line *l; int i; if (!use_mark) return; if (Currentbuf->firstLine == NULL) return; i = Currentbuf->pos - 1; l = Currentbuf->currentLine; if (i < 0) { l = l->prev; if (l != NULL) i = l->len - 1; } while (l != NULL) { for (; i >= 0; i--) { if (l->propBuf[i] & PE_MARK) { Currentbuf->currentLine = l; Currentbuf->pos = i; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); return; } } l = l->prev; if (l != NULL) i = l->len - 1; } /* FIXME: gettextize? */ disp_message("No mark exist before here", TRUE); } /* Mark place to which the regular expression matches */ DEFUN(reMark, REG_MARK, "Mark all occurences of a pattern") { Line *l; char *str; char *p, *p1, *p2; if (!use_mark) return; str = searchKeyData(); if (str == NULL || *str == '\0') { str = inputStrHist("(Mark)Regexp: ", MarkString, TextHist); if (str == NULL || *str == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } } str = conv_search_string(str, DisplayCharset); if ((str = regexCompile(str, 1)) != NULL) { disp_message(str, TRUE); return; } MarkString = str; for (l = Currentbuf->firstLine; l != NULL; l = l->next) { p = l->lineBuf; for (;;) { if (regexMatch(p, &l->lineBuf[l->len] - p, p == l->lineBuf) == 1) { matchedPosition(&p1, &p2); l->propBuf[p1 - l->lineBuf] |= PE_MARK; p = p2; } else break; } } displayBuffer(Currentbuf, B_FORCE_REDRAW); } #endif /* USE_MARK */ static Buffer * loadNormalBuf(Buffer *buf, int renderframe) { pushBuffer(buf); if (renderframe && RenderFrame && Currentbuf->frameset != NULL) rFrame(); return buf; } static Buffer * loadLink(char *url, char *target, char *referer, FormList *request) { Buffer *buf, *nfbuf; union frameset_element *f_element = NULL; int flag = 0; ParsedURL *base, pu; const int *no_referer_ptr; message(Sprintf("loading %s", url)->ptr, 0, 0); refresh(); no_referer_ptr = query_SCONF_NO_REFERER_FROM(&Currentbuf->currentURL); base = baseURL(Currentbuf); if ((no_referer_ptr && *no_referer_ptr) || base == NULL || base->scheme == SCM_LOCAL || base->scheme == SCM_LOCAL_CGI) referer = NO_REFERER; if (referer == NULL) referer = parsedURL2Str(&Currentbuf->currentURL)->ptr; buf = loadGeneralFile(url, baseURL(Currentbuf), referer, flag, request); if (buf == NULL) { char *emsg = Sprintf("Can't load %s", url)->ptr; disp_err_message(emsg, FALSE); return NULL; } parseURL2(url, &pu, base); pushHashHist(URLHist, parsedURL2Str(&pu)->ptr); if (buf == NO_BUFFER) { return NULL; } if (!on_target) /* open link as an indivisual page */ return loadNormalBuf(buf, TRUE); if (do_download) /* download (thus no need to render frames) */ return loadNormalBuf(buf, FALSE); if (target == NULL || /* no target specified (that means this page is not a frame page) */ !strcmp(target, "_top") || /* this link is specified to be opened as an indivisual * page */ !(Currentbuf->bufferprop & BP_FRAME) /* This page is not a frame page */ ) { return loadNormalBuf(buf, TRUE); } nfbuf = Currentbuf->linkBuffer[LB_N_FRAME]; if (nfbuf == NULL) { /* original page (that contains <frameset> tag) doesn't exist */ return loadNormalBuf(buf, TRUE); } f_element = search_frame(nfbuf->frameset, target); if (f_element == NULL) { /* specified target doesn't exist in this frameset */ return loadNormalBuf(buf, TRUE); } /* frame page */ /* stack current frameset */ pushFrameTree(&(nfbuf->frameQ), copyFrameSet(nfbuf->frameset), Currentbuf); /* delete frame view buffer */ delBuffer(Currentbuf); Currentbuf = nfbuf; /* nfbuf->frameset = copyFrameSet(nfbuf->frameset); */ resetFrameElement(f_element, buf, referer, request); discardBuffer(buf); rFrame(); { Anchor *al = NULL; char *label = pu.label; if (label && f_element->element->attr == F_BODY) { al = searchAnchor(f_element->body->nameList, label); } if (!al) { label = Strnew_m_charp("_", target, NULL)->ptr; al = searchURLLabel(Currentbuf, label); } if (al) { gotoLine(Currentbuf, al->start.line); if (label_topline) Currentbuf->topLine = lineSkip(Currentbuf, Currentbuf->topLine, Currentbuf->currentLine-> linenumber - Currentbuf->topLine->linenumber, FALSE); Currentbuf->pos = al->start.pos; arrangeCursor(Currentbuf); } } displayBuffer(Currentbuf, B_NORMAL); return buf; } static void gotoLabel(char *label) { Buffer *buf; Anchor *al; int i; al = searchURLLabel(Currentbuf, label); if (al == NULL) { /* FIXME: gettextize? */ disp_message(Sprintf("%s is not found", label)->ptr, TRUE); return; } buf = newBuffer(Currentbuf->width); copyBuffer(buf, Currentbuf); for (i = 0; i < MAX_LB; i++) buf->linkBuffer[i] = NULL; buf->currentURL.label = allocStr(label, -1); pushHashHist(URLHist, parsedURL2Str(&buf->currentURL)->ptr); (*buf->clone)++; pushBuffer(buf); gotoLine(Currentbuf, al->start.line); if (label_topline) Currentbuf->topLine = lineSkip(Currentbuf, Currentbuf->topLine, Currentbuf->currentLine->linenumber - Currentbuf->topLine->linenumber, FALSE); Currentbuf->pos = al->start.pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); return; } static int handleMailto(char *url) { Str to; char *pos; if (strncasecmp(url, "mailto:", 7)) return 0; #ifdef USE_W3MMAILER if (! non_null(Mailer) || MailtoOptions == MAILTO_OPTIONS_USE_W3MMAILER) return 0; #else if (!non_null(Mailer)) { /* FIXME: gettextize? */ disp_err_message("no mailer is specified", TRUE); return 1; } #endif /* invoke external mailer */ if (MailtoOptions == MAILTO_OPTIONS_USE_MAILTO_URL) { to = Strnew_charp(html_unquote(url)); } else { to = Strnew_charp(url + 7); if ((pos = strchr(to->ptr, '?')) != NULL) Strtruncate(to, pos - to->ptr); } fmTerm(); system(myExtCommand(Mailer, shell_quote(file_unquote(to->ptr)), FALSE)->ptr); fmInit(); displayBuffer(Currentbuf, B_FORCE_REDRAW); pushHashHist(URLHist, url); return 1; } /* follow HREF link */ DEFUN(followA, GOTO_LINK, "Follow current hyperlink in a new buffer") { Anchor *a; ParsedURL u; #ifdef USE_IMAGE int x = 0, y = 0, map = 0; #endif char *url; if (Currentbuf->firstLine == NULL) return; #ifdef USE_IMAGE a = retrieveCurrentImg(Currentbuf); if (a && a->image && a->image->map) { _followForm(FALSE); return; } if (a && a->image && a->image->ismap) { getMapXY(Currentbuf, a, &x, &y); map = 1; } #else a = retrieveCurrentMap(Currentbuf); if (a) { _followForm(FALSE); return; } #endif a = retrieveCurrentAnchor(Currentbuf); if (a == NULL) { _followForm(FALSE); return; } if (*a->url == '#') { /* index within this buffer */ gotoLabel(a->url + 1); return; } parseURL2(a->url, &u, baseURL(Currentbuf)); if (Strcmp(parsedURL2Str(&u), parsedURL2Str(&Currentbuf->currentURL)) == 0) { /* index within this buffer */ if (u.label) { gotoLabel(u.label); return; } } if (handleMailto(a->url)) return; #if 0 else if (!strncasecmp(a->url, "news:", 5) && strchr(a->url, '@') == NULL) { /* news:newsgroup is not supported */ /* FIXME: gettextize? */ disp_err_message("news:newsgroup_name is not supported", TRUE); return; } #endif /* USE_NNTP */ url = a->url; #ifdef USE_IMAGE if (map) url = Sprintf("%s?%d,%d", a->url, x, y)->ptr; #endif if (check_target && open_tab_blank && a->target && (!strcasecmp(a->target, "_new") || !strcasecmp(a->target, "_blank"))) { Buffer *buf; _newT(); buf = Currentbuf; loadLink(url, a->target, a->referer, NULL); if (buf != Currentbuf) delBuffer(buf); else deleteTab(CurrentTab); displayBuffer(Currentbuf, B_FORCE_REDRAW); return; } loadLink(url, a->target, a->referer, NULL); displayBuffer(Currentbuf, B_NORMAL); } /* follow HREF link in the buffer */ void bufferA(void) { on_target = FALSE; followA(); on_target = TRUE; } /* view inline image */ DEFUN(followI, VIEW_IMAGE, "Display image in viewer") { Anchor *a; Buffer *buf; if (Currentbuf->firstLine == NULL) return; a = retrieveCurrentImg(Currentbuf); if (a == NULL) return; /* FIXME: gettextize? */ message(Sprintf("loading %s", a->url)->ptr, 0, 0); refresh(); buf = loadGeneralFile(a->url, baseURL(Currentbuf), NULL, 0, NULL); if (buf == NULL) { /* FIXME: gettextize? */ char *emsg = Sprintf("Can't load %s", a->url)->ptr; disp_err_message(emsg, FALSE); } else if (buf != NO_BUFFER) { pushBuffer(buf); } displayBuffer(Currentbuf, B_NORMAL); } static FormItemList * save_submit_formlist(FormItemList *src) { FormList *list; FormList *srclist; FormItemList *srcitem; FormItemList *item; FormItemList *ret = NULL; #ifdef MENU_SELECT FormSelectOptionItem *opt; FormSelectOptionItem *curopt; FormSelectOptionItem *srcopt; #endif /* MENU_SELECT */ if (src == NULL) return NULL; srclist = src->parent; list = New(FormList); list->method = srclist->method; list->action = Strdup(srclist->action); #ifdef USE_M17N list->charset = srclist->charset; #endif list->enctype = srclist->enctype; list->nitems = srclist->nitems; list->body = srclist->body; list->boundary = srclist->boundary; list->length = srclist->length; for (srcitem = srclist->item; srcitem; srcitem = srcitem->next) { item = New(FormItemList); item->type = srcitem->type; item->name = Strdup(srcitem->name); item->value = Strdup(srcitem->value); item->checked = srcitem->checked; item->accept = srcitem->accept; item->size = srcitem->size; item->rows = srcitem->rows; item->maxlength = srcitem->maxlength; item->readonly = srcitem->readonly; #ifdef MENU_SELECT opt = curopt = NULL; for (srcopt = srcitem->select_option; srcopt; srcopt = srcopt->next) { if (!srcopt->checked) continue; opt = New(FormSelectOptionItem); opt->value = Strdup(srcopt->value); opt->label = Strdup(srcopt->label); opt->checked = srcopt->checked; if (item->select_option == NULL) { item->select_option = curopt = opt; } else { curopt->next = opt; curopt = curopt->next; } } item->select_option = opt; if (srcitem->label) item->label = Strdup(srcitem->label); #endif /* MENU_SELECT */ item->parent = list; item->next = NULL; if (list->lastitem == NULL) { list->item = list->lastitem = item; } else { list->lastitem->next = item; list->lastitem = item; } if (srcitem == src) ret = item; } return ret; } #ifdef USE_M17N static Str conv_form_encoding(Str val, FormItemList *fi, Buffer *buf) { wc_ces charset = SystemCharset; if (fi->parent->charset) charset = fi->parent->charset; else if (buf->document_charset && buf->document_charset != WC_CES_US_ASCII) charset = buf->document_charset; return wc_Str_conv_strict(val, InnerCharset, charset); } #else #define conv_form_encoding(val, fi, buf) (val) #endif static void query_from_followform(Str *query, FormItemList *fi, int multipart) { FormItemList *f2; FILE *body = NULL; if (multipart) { *query = tmpfname(TMPF_DFL, NULL); body = fopen((*query)->ptr, "w"); if (body == NULL) { return; } fi->parent->body = (*query)->ptr; fi->parent->boundary = Sprintf("------------------------------%d%ld%ld%ld", CurrentPid, fi->parent, fi->parent->body, fi->parent->boundary)->ptr; } *query = Strnew(); for (f2 = fi->parent->item; f2; f2 = f2->next) { if (f2->name == NULL) continue; /* <ISINDEX> is translated into single text form */ if (f2->name->length == 0 && (multipart || f2->type != FORM_INPUT_TEXT)) continue; switch (f2->type) { case FORM_INPUT_RESET: /* do nothing */ continue; case FORM_INPUT_SUBMIT: case FORM_INPUT_IMAGE: if (f2 != fi || f2->value == NULL) continue; break; case FORM_INPUT_RADIO: case FORM_INPUT_CHECKBOX: if (!f2->checked) continue; } if (multipart) { if (f2->type == FORM_INPUT_IMAGE) { int x = 0, y = 0; #ifdef USE_IMAGE getMapXY(Currentbuf, retrieveCurrentImg(Currentbuf), &x, &y); #endif *query = Strdup(conv_form_encoding(f2->name, fi, Currentbuf)); Strcat_charp(*query, ".x"); form_write_data(body, fi->parent->boundary, (*query)->ptr, Sprintf("%d", x)->ptr); *query = Strdup(conv_form_encoding(f2->name, fi, Currentbuf)); Strcat_charp(*query, ".y"); form_write_data(body, fi->parent->boundary, (*query)->ptr, Sprintf("%d", y)->ptr); } else if (f2->name && f2->name->length > 0 && f2->value != NULL) { /* not IMAGE */ *query = conv_form_encoding(f2->value, fi, Currentbuf); if (f2->type == FORM_INPUT_FILE) form_write_from_file(body, fi->parent->boundary, conv_form_encoding(f2->name, fi, Currentbuf)->ptr, (*query)->ptr, Str_conv_to_system(f2->value)->ptr); else form_write_data(body, fi->parent->boundary, conv_form_encoding(f2->name, fi, Currentbuf)->ptr, (*query)->ptr); } } else { /* not multipart */ if (f2->type == FORM_INPUT_IMAGE) { int x = 0, y = 0; #ifdef USE_IMAGE getMapXY(Currentbuf, retrieveCurrentImg(Currentbuf), &x, &y); #endif Strcat(*query, Str_form_quote(conv_form_encoding (f2->name, fi, Currentbuf))); Strcat(*query, Sprintf(".x=%d&", x)); Strcat(*query, Str_form_quote(conv_form_encoding (f2->name, fi, Currentbuf))); Strcat(*query, Sprintf(".y=%d", y)); } else { /* not IMAGE */ if (f2->name && f2->name->length > 0) { Strcat(*query, Str_form_quote(conv_form_encoding (f2->name, fi, Currentbuf))); Strcat_char(*query, '='); } if (f2->value != NULL) { if (fi->parent->method == FORM_METHOD_INTERNAL) Strcat(*query, Str_form_quote(f2->value)); else { Strcat(*query, Str_form_quote(conv_form_encoding (f2->value, fi, Currentbuf))); } } } if (f2->next) Strcat_char(*query, '&'); } } if (multipart) { fprintf(body, "--%s--\r\n", fi->parent->boundary); fclose(body); } else { /* remove trailing & */ while (Strlastchar(*query) == '&') Strshrink(*query, 1); } } /* submit form */ DEFUN(submitForm, SUBMIT, "Submit form") { _followForm(TRUE); } /* process form */ void followForm(void) { _followForm(FALSE); } static void _followForm(int submit) { Anchor *a, *a2; char *p; FormItemList *fi, *f2; Str tmp, tmp2; int multipart = 0, i; if (Currentbuf->firstLine == NULL) return; a = retrieveCurrentForm(Currentbuf); if (a == NULL) return; fi = (FormItemList *)a->url; switch (fi->type) { case FORM_INPUT_TEXT: if (submit) goto do_submit; if (fi->readonly) /* FIXME: gettextize? */ disp_message_nsec("Read only field!", FALSE, 1, TRUE, FALSE); /* FIXME: gettextize? */ p = inputStrHist("TEXT:", fi->value ? fi->value->ptr : NULL, TextHist); if (p == NULL || fi->readonly) break; fi->value = Strnew_charp(p); formUpdateBuffer(a, Currentbuf, fi); if (fi->accept || fi->parent->nitems == 1) goto do_submit; break; case FORM_INPUT_FILE: if (submit) goto do_submit; if (fi->readonly) /* FIXME: gettextize? */ disp_message_nsec("Read only field!", FALSE, 1, TRUE, FALSE); /* FIXME: gettextize? */ p = inputFilenameHist("Filename:", fi->value ? fi->value->ptr : NULL, NULL); if (p == NULL || fi->readonly) break; fi->value = Strnew_charp(p); formUpdateBuffer(a, Currentbuf, fi); if (fi->accept || fi->parent->nitems == 1) goto do_submit; break; case FORM_INPUT_PASSWORD: if (submit) goto do_submit; if (fi->readonly) { /* FIXME: gettextize? */ disp_message_nsec("Read only field!", FALSE, 1, TRUE, FALSE); break; } /* FIXME: gettextize? */ p = inputLine("Password:", fi->value ? fi->value->ptr : NULL, IN_PASSWORD); if (p == NULL) break; fi->value = Strnew_charp(p); formUpdateBuffer(a, Currentbuf, fi); if (fi->accept) goto do_submit; break; case FORM_TEXTAREA: if (submit) goto do_submit; if (fi->readonly) /* FIXME: gettextize? */ disp_message_nsec("Read only field!", FALSE, 1, TRUE, FALSE); input_textarea(fi); formUpdateBuffer(a, Currentbuf, fi); break; case FORM_INPUT_RADIO: if (submit) goto do_submit; if (fi->readonly) { /* FIXME: gettextize? */ disp_message_nsec("Read only field!", FALSE, 1, TRUE, FALSE); break; } formRecheckRadio(a, Currentbuf, fi); break; case FORM_INPUT_CHECKBOX: if (submit) goto do_submit; if (fi->readonly) { /* FIXME: gettextize? */ disp_message_nsec("Read only field!", FALSE, 1, TRUE, FALSE); break; } fi->checked = !fi->checked; formUpdateBuffer(a, Currentbuf, fi); break; #ifdef MENU_SELECT case FORM_SELECT: if (submit) goto do_submit; if (!formChooseOptionByMenu(fi, Currentbuf->cursorX - Currentbuf->pos + a->start.pos + Currentbuf->rootX, Currentbuf->cursorY + Currentbuf->rootY)) break; formUpdateBuffer(a, Currentbuf, fi); if (fi->parent->nitems == 1) goto do_submit; break; #endif /* MENU_SELECT */ case FORM_INPUT_IMAGE: case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: do_submit: tmp = Strnew(); multipart = (fi->parent->method == FORM_METHOD_POST && fi->parent->enctype == FORM_ENCTYPE_MULTIPART); query_from_followform(&tmp, fi, multipart); tmp2 = Strdup(fi->parent->action); if (!Strcmp_charp(tmp2, "!CURRENT_URL!")) { /* It means "current URL" */ tmp2 = parsedURL2Str(&Currentbuf->currentURL); if ((p = strchr(tmp2->ptr, '?')) != NULL) Strshrink(tmp2, (tmp2->ptr + tmp2->length) - p); } if (fi->parent->method == FORM_METHOD_GET) { if ((p = strchr(tmp2->ptr, '?')) != NULL) Strshrink(tmp2, (tmp2->ptr + tmp2->length) - p); Strcat_charp(tmp2, "?"); Strcat(tmp2, tmp); loadLink(tmp2->ptr, a->target, NULL, NULL); } else if (fi->parent->method == FORM_METHOD_POST) { Buffer *buf; if (multipart) { struct stat st; stat(fi->parent->body, &st); fi->parent->length = st.st_size; } else { fi->parent->body = tmp->ptr; fi->parent->length = tmp->length; } buf = loadLink(tmp2->ptr, a->target, NULL, fi->parent); if (multipart) { unlink(fi->parent->body); } if (buf && !(buf->bufferprop & BP_REDIRECTED)) { /* buf must be Currentbuf */ /* BP_REDIRECTED means that the buffer is obtained through * Location: header. In this case, buf->form_submit must not be set * because the page is not loaded by POST method but GET method. */ buf->form_submit = save_submit_formlist(fi); } } else if ((fi->parent->method == FORM_METHOD_INTERNAL && (!Strcmp_charp(fi->parent->action, "map") || !Strcmp_charp(fi->parent->action, "none"))) || Currentbuf->bufferprop & BP_INTERNAL) { /* internal */ do_internal(tmp2->ptr, tmp->ptr); } else { disp_err_message("Can't send form because of illegal method.", FALSE); } break; case FORM_INPUT_RESET: for (i = 0; i < Currentbuf->formitem->nanchor; i++) { a2 = &Currentbuf->formitem->anchors[i]; f2 = (FormItemList *)a2->url; if (f2->parent == fi->parent && f2->name && f2->value && f2->type != FORM_INPUT_SUBMIT && f2->type != FORM_INPUT_HIDDEN && f2->type != FORM_INPUT_RESET) { f2->value = f2->init_value; f2->checked = f2->init_checked; #ifdef MENU_SELECT f2->label = f2->init_label; f2->selected = f2->init_selected; #endif /* MENU_SELECT */ formUpdateBuffer(a2, Currentbuf, f2); } } break; case FORM_INPUT_HIDDEN: default: break; } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* go to the top anchor */ DEFUN(topA, LINK_BEGIN, "Move to the first hyperlink") { HmarkerList *hl = Currentbuf->hmarklist; BufferPoint *po; Anchor *an; int hseq = 0; if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; if (prec_num > hl->nmark) hseq = hl->nmark - 1; else if (prec_num > 0) hseq = prec_num - 1; do { if (hseq >= hl->nmark) return; po = hl->marks + hseq; an = retrieveAnchor(Currentbuf->href, po->line, po->pos); if (an == NULL) an = retrieveAnchor(Currentbuf->formitem, po->line, po->pos); hseq++; } while (an == NULL); gotoLine(Currentbuf, po->line); Currentbuf->pos = po->pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the last anchor */ DEFUN(lastA, LINK_END, "Move to the last hyperlink") { HmarkerList *hl = Currentbuf->hmarklist; BufferPoint *po; Anchor *an; int hseq; if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; if (prec_num >= hl->nmark) hseq = 0; else if (prec_num > 0) hseq = hl->nmark - prec_num; else hseq = hl->nmark - 1; do { if (hseq < 0) return; po = hl->marks + hseq; an = retrieveAnchor(Currentbuf->href, po->line, po->pos); if (an == NULL) an = retrieveAnchor(Currentbuf->formitem, po->line, po->pos); hseq--; } while (an == NULL); gotoLine(Currentbuf, po->line); Currentbuf->pos = po->pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the nth anchor */ DEFUN(nthA, LINK_N, "Go to the nth link") { HmarkerList *hl = Currentbuf->hmarklist; BufferPoint *po; Anchor *an; int n = searchKeyNum(); if (n < 0 || n > hl->nmark) return; if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; po = hl->marks + n-1; an = retrieveAnchor(Currentbuf->href, po->line, po->pos); if (an == NULL) an = retrieveAnchor(Currentbuf->formitem, po->line, po->pos); if (an == NULL) return; gotoLine(Currentbuf, po->line); Currentbuf->pos = po->pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the next anchor */ DEFUN(nextA, NEXT_LINK, "Move to the next hyperlink") { _nextA(FALSE); } /* go to the previous anchor */ DEFUN(prevA, PREV_LINK, "Move to the previous hyperlink") { _prevA(FALSE); } /* go to the next visited anchor */ DEFUN(nextVA, NEXT_VISITED, "Move to the next visited hyperlink") { _nextA(TRUE); } /* go to the previous visited anchor */ DEFUN(prevVA, PREV_VISITED, "Move to the previous visited hyperlink") { _prevA(TRUE); } /* go to the next [visited] anchor */ static void _nextA(int visited) { HmarkerList *hl = Currentbuf->hmarklist; BufferPoint *po; Anchor *an, *pan; int i, x, y, n = searchKeyNum(); ParsedURL url; if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; an = retrieveCurrentAnchor(Currentbuf); if (visited != TRUE && an == NULL) an = retrieveCurrentForm(Currentbuf); y = Currentbuf->currentLine->linenumber; x = Currentbuf->pos; if (visited == TRUE) { n = hl->nmark; } for (i = 0; i < n; i++) { pan = an; if (an && an->hseq >= 0) { int hseq = an->hseq + 1; do { if (hseq >= hl->nmark) { if (visited == TRUE) return; an = pan; goto _end; } po = &hl->marks[hseq]; an = retrieveAnchor(Currentbuf->href, po->line, po->pos); if (visited != TRUE && an == NULL) an = retrieveAnchor(Currentbuf->formitem, po->line, po->pos); hseq++; if (visited == TRUE && an) { parseURL2(an->url, &url, baseURL(Currentbuf)); if (getHashHist(URLHist, parsedURL2Str(&url)->ptr)) { goto _end; } } } while (an == NULL || an == pan); } else { an = closest_next_anchor(Currentbuf->href, NULL, x, y); if (visited != TRUE) an = closest_next_anchor(Currentbuf->formitem, an, x, y); if (an == NULL) { if (visited == TRUE) return; an = pan; break; } x = an->start.pos; y = an->start.line; if (visited == TRUE) { parseURL2(an->url, &url, baseURL(Currentbuf)); if (getHashHist(URLHist, parsedURL2Str(&url)->ptr)) { goto _end; } } } } if (visited == TRUE) return; _end: if (an == NULL || an->hseq < 0) return; po = &hl->marks[an->hseq]; gotoLine(Currentbuf, po->line); Currentbuf->pos = po->pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the previous anchor */ static void _prevA(int visited) { HmarkerList *hl = Currentbuf->hmarklist; BufferPoint *po; Anchor *an, *pan; int i, x, y, n = searchKeyNum(); ParsedURL url; if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; an = retrieveCurrentAnchor(Currentbuf); if (visited != TRUE && an == NULL) an = retrieveCurrentForm(Currentbuf); y = Currentbuf->currentLine->linenumber; x = Currentbuf->pos; if (visited == TRUE) { n = hl->nmark; } for (i = 0; i < n; i++) { pan = an; if (an && an->hseq >= 0) { int hseq = an->hseq - 1; do { if (hseq < 0) { if (visited == TRUE) return; an = pan; goto _end; } po = hl->marks + hseq; an = retrieveAnchor(Currentbuf->href, po->line, po->pos); if (visited != TRUE && an == NULL) an = retrieveAnchor(Currentbuf->formitem, po->line, po->pos); hseq--; if (visited == TRUE && an) { parseURL2(an->url, &url, baseURL(Currentbuf)); if (getHashHist(URLHist, parsedURL2Str(&url)->ptr)) { goto _end; } } } while (an == NULL || an == pan); } else { an = closest_prev_anchor(Currentbuf->href, NULL, x, y); if (visited != TRUE) an = closest_prev_anchor(Currentbuf->formitem, an, x, y); if (an == NULL) { if (visited == TRUE) return; an = pan; break; } x = an->start.pos; y = an->start.line; if (visited == TRUE && an) { parseURL2(an->url, &url, baseURL(Currentbuf)); if (getHashHist(URLHist, parsedURL2Str(&url)->ptr)) { goto _end; } } } } if (visited == TRUE) return; _end: if (an == NULL || an->hseq < 0) return; po = hl->marks + an->hseq; gotoLine(Currentbuf, po->line); Currentbuf->pos = po->pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the next left/right anchor */ static void nextX(int d, int dy) { HmarkerList *hl = Currentbuf->hmarklist; Anchor *an, *pan; Line *l; int i, x, y, n = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; an = retrieveCurrentAnchor(Currentbuf); if (an == NULL) an = retrieveCurrentForm(Currentbuf); l = Currentbuf->currentLine; x = Currentbuf->pos; y = l->linenumber; pan = NULL; for (i = 0; i < n; i++) { if (an) x = (d > 0) ? an->end.pos : an->start.pos - 1; an = NULL; while (1) { for (; x >= 0 && x < l->len; x += d) { an = retrieveAnchor(Currentbuf->href, y, x); if (!an) an = retrieveAnchor(Currentbuf->formitem, y, x); if (an) { pan = an; break; } } if (!dy || an) break; l = (dy > 0) ? l->next : l->prev; if (!l) break; x = (d > 0) ? 0 : l->len - 1; y = l->linenumber; } if (!an) break; } if (pan == NULL) return; gotoLine(Currentbuf, y); Currentbuf->pos = pan->start.pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the next downward/upward anchor */ static void nextY(int d) { HmarkerList *hl = Currentbuf->hmarklist; Anchor *an, *pan; int i, x, y, n = searchKeyNum(); int hseq; if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; an = retrieveCurrentAnchor(Currentbuf); if (an == NULL) an = retrieveCurrentForm(Currentbuf); x = Currentbuf->pos; y = Currentbuf->currentLine->linenumber + d; pan = NULL; hseq = -1; for (i = 0; i < n; i++) { if (an) hseq = abs(an->hseq); an = NULL; for (; y >= 0 && y <= Currentbuf->lastLine->linenumber; y += d) { an = retrieveAnchor(Currentbuf->href, y, x); if (!an) an = retrieveAnchor(Currentbuf->formitem, y, x); if (an && hseq != abs(an->hseq)) { pan = an; break; } } if (!an) break; } if (pan == NULL) return; gotoLine(Currentbuf, pan->start.line); arrangeLine(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the next left anchor */ DEFUN(nextL, NEXT_LEFT, "Move left to the next hyperlink") { nextX(-1, 0); } /* go to the next left-up anchor */ DEFUN(nextLU, NEXT_LEFT_UP, "Move left or upward to the next hyperlink") { nextX(-1, -1); } /* go to the next right anchor */ DEFUN(nextR, NEXT_RIGHT, "Move right to the next hyperlink") { nextX(1, 0); } /* go to the next right-down anchor */ DEFUN(nextRD, NEXT_RIGHT_DOWN, "Move right or downward to the next hyperlink") { nextX(1, 1); } /* go to the next downward anchor */ DEFUN(nextD, NEXT_DOWN, "Move downward to the next hyperlink") { nextY(1); } /* go to the next upward anchor */ DEFUN(nextU, NEXT_UP, "Move upward to the next hyperlink") { nextY(-1); } /* go to the next bufferr */ DEFUN(nextBf, NEXT, "Switch to the next buffer") { Buffer *buf; int i; for (i = 0; i < PREC_NUM; i++) { buf = prevBuffer(Firstbuf, Currentbuf); if (!buf) { if (i == 0) return; break; } Currentbuf = buf; } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* go to the previous bufferr */ DEFUN(prevBf, PREV, "Switch to the previous buffer") { Buffer *buf; int i; for (i = 0; i < PREC_NUM; i++) { buf = Currentbuf->nextBuffer; if (!buf) { if (i == 0) return; break; } Currentbuf = buf; } displayBuffer(Currentbuf, B_FORCE_REDRAW); } static int checkBackBuffer(Buffer *buf) { Buffer *fbuf = buf->linkBuffer[LB_N_FRAME]; if (fbuf) { if (fbuf->frameQ) return TRUE; /* Currentbuf has stacked frames */ /* when no frames stacked and next is frame source, try next's * nextBuffer */ if (RenderFrame && fbuf == buf->nextBuffer) { if (fbuf->nextBuffer != NULL) return TRUE; else return FALSE; } } if (buf->nextBuffer) return TRUE; return FALSE; } /* delete current buffer and back to the previous buffer */ DEFUN(backBf, BACK, "Close current buffer and return to the one below in stack") { Buffer *buf = Currentbuf->linkBuffer[LB_N_FRAME]; if (!checkBackBuffer(Currentbuf)) { if (close_tab_back && nTab >= 1) { deleteTab(CurrentTab); displayBuffer(Currentbuf, B_FORCE_REDRAW); } else /* FIXME: gettextize? */ disp_message("Can't go back...", TRUE); return; } delBuffer(Currentbuf); if (buf) { if (buf->frameQ) { struct frameset *fs; long linenumber = buf->frameQ->linenumber; long top = buf->frameQ->top_linenumber; int pos = buf->frameQ->pos; int currentColumn = buf->frameQ->currentColumn; AnchorList *formitem = buf->frameQ->formitem; fs = popFrameTree(&(buf->frameQ)); deleteFrameSet(buf->frameset); buf->frameset = fs; if (buf == Currentbuf) { rFrame(); Currentbuf->topLine = lineSkip(Currentbuf, Currentbuf->firstLine, top - 1, FALSE); gotoLine(Currentbuf, linenumber); Currentbuf->pos = pos; Currentbuf->currentColumn = currentColumn; arrangeCursor(Currentbuf); formResetBuffer(Currentbuf, formitem); } } else if (RenderFrame && buf == Currentbuf) { delBuffer(Currentbuf); } } displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(deletePrevBuf, DELETE_PREVBUF, "Delete previous buffer (mainly for local CGI-scripts)") { Buffer *buf = Currentbuf->nextBuffer; if (buf) delBuffer(buf); } static void cmd_loadURL(char *url, ParsedURL *current, char *referer, FormList *request) { Buffer *buf; if (handleMailto(url)) return; #if 0 if (!strncasecmp(url, "news:", 5) && strchr(url, '@') == NULL) { /* news:newsgroup is not supported */ /* FIXME: gettextize? */ disp_err_message("news:newsgroup_name is not supported", TRUE); return; } #endif /* USE_NNTP */ refresh(); buf = loadGeneralFile(url, current, referer, 0, request); if (buf == NULL) { /* FIXME: gettextize? */ char *emsg = Sprintf("Can't load %s", conv_from_system(url))->ptr; disp_err_message(emsg, FALSE); } else if (buf != NO_BUFFER) { pushBuffer(buf); if (RenderFrame && Currentbuf->frameset != NULL) rFrame(); } displayBuffer(Currentbuf, B_NORMAL); } /* go to specified URL */ static void goURL0(char *prompt, int relative) { char *url, *referer; ParsedURL p_url, *current; Buffer *cur_buf = Currentbuf; const int *no_referer_ptr; url = searchKeyData(); if (url == NULL) { Hist *hist = copyHist(URLHist); Anchor *a; current = baseURL(Currentbuf); if (current) { char *c_url = parsedURL2Str(current)->ptr; if (DefaultURLString == DEFAULT_URL_CURRENT) url = url_decode2(c_url, NULL); else pushHist(hist, c_url); } a = retrieveCurrentAnchor(Currentbuf); if (a) { char *a_url; parseURL2(a->url, &p_url, current); a_url = parsedURL2Str(&p_url)->ptr; if (DefaultURLString == DEFAULT_URL_LINK) url = url_decode2(a_url, Currentbuf); else pushHist(hist, a_url); } url = inputLineHist(prompt, url, IN_URL, hist); if (url != NULL) SKIP_BLANKS(url); } if (relative) { no_referer_ptr = query_SCONF_NO_REFERER_FROM(&Currentbuf->currentURL); current = baseURL(Currentbuf); if ((no_referer_ptr && *no_referer_ptr) || current == NULL || current->scheme == SCM_LOCAL || current->scheme == SCM_LOCAL_CGI) referer = NO_REFERER; else referer = parsedURL2Str(&Currentbuf->currentURL)->ptr; url = url_encode(url, current, Currentbuf->document_charset); } else { current = NULL; referer = NULL; url = url_encode(url, NULL, 0); } if (url == NULL || *url == '\0') { displayBuffer(Currentbuf, B_FORCE_REDRAW); return; } if (*url == '#') { gotoLabel(url + 1); return; } parseURL2(url, &p_url, current); pushHashHist(URLHist, parsedURL2Str(&p_url)->ptr); cmd_loadURL(url, current, referer, NULL); if (Currentbuf != cur_buf) /* success */ pushHashHist(URLHist, parsedURL2Str(&Currentbuf->currentURL)->ptr); } DEFUN(goURL, GOTO, "Open specified document in a new buffer") { goURL0("Goto URL: ", FALSE); } DEFUN(gorURL, GOTO_RELATIVE, "Go to relative address") { goURL0("Goto relative URL: ", TRUE); } static void cmd_loadBuffer(Buffer *buf, int prop, int linkid) { if (buf == NULL) { disp_err_message("Can't load string", FALSE); } else if (buf != NO_BUFFER) { buf->bufferprop |= (BP_INTERNAL | prop); if (!(buf->bufferprop & BP_NO_URL)) copyParsedURL(&buf->currentURL, &Currentbuf->currentURL); if (linkid != LB_NOLINK) { buf->linkBuffer[REV_LB[linkid]] = Currentbuf; Currentbuf->linkBuffer[linkid] = buf; } pushBuffer(buf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* load bookmark */ DEFUN(ldBmark, BOOKMARK VIEW_BOOKMARK, "View bookmarks") { cmd_loadURL(BookmarkFile, NULL, NO_REFERER, NULL); } /* Add current to bookmark */ DEFUN(adBmark, ADD_BOOKMARK, "Add current page to bookmarks") { Str tmp; FormList *request; tmp = Sprintf("mode=panel&cookie=%s&bmark=%s&url=%s&title=%s" #ifdef USE_M17N "&charset=%s" #endif , (Str_form_quote(localCookie()))->ptr, (Str_form_quote(Strnew_charp(BookmarkFile)))->ptr, (Str_form_quote(parsedURL2Str(&Currentbuf->currentURL)))-> ptr, #ifdef USE_M17N (Str_form_quote(wc_conv_strict(Currentbuf->buffername, InnerCharset, BookmarkCharset)))->ptr, wc_ces_to_charset(BookmarkCharset)); #else (Str_form_quote(Strnew_charp(Currentbuf->buffername)))->ptr); #endif request = newFormList(NULL, "post", NULL, NULL, NULL, NULL, NULL); request->body = tmp->ptr; request->length = tmp->length; cmd_loadURL("file:///$LIB/" W3MBOOKMARK_CMDNAME, NULL, NO_REFERER, request); } /* option setting */ DEFUN(ldOpt, OPTIONS, "Display options setting panel") { cmd_loadBuffer(load_option_panel(), BP_NO_URL, LB_NOLINK); } /* set an option */ DEFUN(setOpt, SET_OPTION, "Set option") { char *opt; CurrentKeyData = NULL; /* not allowed in w3m-control: */ opt = searchKeyData(); if (opt == NULL || *opt == '\0' || strchr(opt, '=') == NULL) { if (opt != NULL && *opt != '\0') { char *v = get_param_option(opt); opt = Sprintf("%s=%s", opt, v ? v : "")->ptr; } opt = inputStrHist("Set option: ", opt, TextHist); if (opt == NULL || *opt == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } } if (set_param_option(opt)) sync_with_option(); displayBuffer(Currentbuf, B_REDRAW_IMAGE); } /* error message list */ DEFUN(msgs, MSGS, "Display error messages") { cmd_loadBuffer(message_list_panel(), BP_NO_URL, LB_NOLINK); } /* page info */ DEFUN(pginfo, INFO, "Display information about the current document") { Buffer *buf; if ((buf = Currentbuf->linkBuffer[LB_N_INFO]) != NULL) { Currentbuf = buf; displayBuffer(Currentbuf, B_NORMAL); return; } if ((buf = Currentbuf->linkBuffer[LB_INFO]) != NULL) delBuffer(buf); buf = page_info_panel(Currentbuf); cmd_loadBuffer(buf, BP_NORMAL, LB_INFO); } void follow_map(struct parsed_tagarg *arg) { char *name = tag_get_value(arg, "link"); #if defined(MENU_MAP) || defined(USE_IMAGE) Anchor *an; MapArea *a; int x, y; ParsedURL p_url; an = retrieveCurrentImg(Currentbuf); x = Currentbuf->cursorX + Currentbuf->rootX; y = Currentbuf->cursorY + Currentbuf->rootY; a = follow_map_menu(Currentbuf, name, an, x, y); if (a == NULL || a->url == NULL || *(a->url) == '\0') { #endif #ifndef MENU_MAP Buffer *buf = follow_map_panel(Currentbuf, name); if (buf != NULL) cmd_loadBuffer(buf, BP_NORMAL, LB_NOLINK); #endif #if defined(MENU_MAP) || defined(USE_IMAGE) return; } if (*(a->url) == '#') { gotoLabel(a->url + 1); return; } parseURL2(a->url, &p_url, baseURL(Currentbuf)); pushHashHist(URLHist, parsedURL2Str(&p_url)->ptr); if (check_target && open_tab_blank && a->target && (!strcasecmp(a->target, "_new") || !strcasecmp(a->target, "_blank"))) { Buffer *buf; _newT(); buf = Currentbuf; cmd_loadURL(a->url, baseURL(Currentbuf), parsedURL2Str(&Currentbuf->currentURL)->ptr, NULL); if (buf != Currentbuf) delBuffer(buf); else deleteTab(CurrentTab); displayBuffer(Currentbuf, B_FORCE_REDRAW); return; } cmd_loadURL(a->url, baseURL(Currentbuf), parsedURL2Str(&Currentbuf->currentURL)->ptr, NULL); #endif } #ifdef USE_MENU /* link menu */ DEFUN(linkMn, LINK_MENU, "Pop up link element menu") { LinkList *l = link_menu(Currentbuf); ParsedURL p_url; if (!l || !l->url) return; if (*(l->url) == '#') { gotoLabel(l->url + 1); return; } parseURL2(l->url, &p_url, baseURL(Currentbuf)); pushHashHist(URLHist, parsedURL2Str(&p_url)->ptr); cmd_loadURL(l->url, baseURL(Currentbuf), parsedURL2Str(&Currentbuf->currentURL)->ptr, NULL); } static void anchorMn(Anchor *(*menu_func) (Buffer *), int go) { Anchor *a; BufferPoint *po; if (!Currentbuf->href || !Currentbuf->hmarklist) return; a = menu_func(Currentbuf); if (!a || a->hseq < 0) return; po = &Currentbuf->hmarklist->marks[a->hseq]; gotoLine(Currentbuf, po->line); Currentbuf->pos = po->pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); if (go) followA(); } /* accesskey */ DEFUN(accessKey, ACCESSKEY, "Pop up accesskey menu") { anchorMn(accesskey_menu, TRUE); } /* list menu */ DEFUN(listMn, LIST_MENU, "Pop up menu for hyperlinks to browse to") { anchorMn(list_menu, TRUE); } DEFUN(movlistMn, MOVE_LIST_MENU, "Pop up menu to navigate between hyperlinks") { anchorMn(list_menu, FALSE); } #endif /* link,anchor,image list */ DEFUN(linkLst, LIST, "Show all URLs referenced") { Buffer *buf; buf = link_list_panel(Currentbuf); if (buf != NULL) { #ifdef USE_M17N buf->document_charset = Currentbuf->document_charset; #endif cmd_loadBuffer(buf, BP_NORMAL, LB_NOLINK); } } #ifdef USE_COOKIE /* cookie list */ DEFUN(cooLst, COOKIE, "View cookie list") { Buffer *buf; buf = cookie_list_panel(); if (buf != NULL) cmd_loadBuffer(buf, BP_NO_URL, LB_NOLINK); } #endif /* USE_COOKIE */ #ifdef USE_HISTORY /* History page */ DEFUN(ldHist, HISTORY, "Show browsing history") { cmd_loadBuffer(historyBuffer(URLHist), BP_NO_URL, LB_NOLINK); } #endif /* USE_HISTORY */ /* download HREF link */ DEFUN(svA, SAVE_LINK, "Save hyperlink target") { CurrentKeyData = NULL; /* not allowed in w3m-control: */ do_download = TRUE; followA(); do_download = FALSE; } /* download IMG link */ DEFUN(svI, SAVE_IMAGE, "Save inline image") { CurrentKeyData = NULL; /* not allowed in w3m-control: */ do_download = TRUE; followI(); do_download = FALSE; } /* save buffer */ DEFUN(svBuf, PRINT SAVE_SCREEN, "Save rendered document") { char *qfile = NULL, *file; FILE *f; int is_pipe; CurrentKeyData = NULL; /* not allowed in w3m-control: */ file = searchKeyData(); if (file == NULL || *file == '\0') { /* FIXME: gettextize? */ qfile = inputLineHist("Save buffer to: ", NULL, IN_COMMAND, SaveHist); if (qfile == NULL || *qfile == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } } file = conv_to_system(qfile ? qfile : file); if (*file == '|') { is_pipe = TRUE; f = popen(file + 1, "w"); } else { if (qfile) { file = unescape_spaces(Strnew_charp(qfile))->ptr; file = conv_to_system(file); } file = expandPath(file); if (checkOverWrite(file) < 0) { displayBuffer(Currentbuf, B_NORMAL); return; } f = fopen(file, "w"); is_pipe = FALSE; } if (f == NULL) { /* FIXME: gettextize? */ char *emsg = Sprintf("Can't open %s", conv_from_system(file))->ptr; disp_err_message(emsg, TRUE); return; } saveBuffer(Currentbuf, f, TRUE); if (is_pipe) pclose(f); else fclose(f); displayBuffer(Currentbuf, B_NORMAL); } /* save source */ DEFUN(svSrc, DOWNLOAD SAVE, "Save document source") { char *file; if (Currentbuf->sourcefile == NULL) return; CurrentKeyData = NULL; /* not allowed in w3m-control: */ PermitSaveToPipe = TRUE; if (Currentbuf->real_scheme == SCM_LOCAL) file = conv_from_system(guess_save_name(NULL, Currentbuf->currentURL. real_file)); else file = guess_save_name(Currentbuf, Currentbuf->currentURL.file); doFileCopy(Currentbuf->sourcefile, file); PermitSaveToPipe = FALSE; displayBuffer(Currentbuf, B_NORMAL); } static void _peekURL(int only_img) { Anchor *a; ParsedURL pu; static Str s = NULL; #ifdef USE_M17N static Lineprop *p = NULL; Lineprop *pp; #endif static int offset = 0, n; if (Currentbuf->firstLine == NULL) return; if (CurrentKey == prev_key && s != NULL) { if (s->length - offset >= COLS) offset++; else if (s->length <= offset) /* bug ? */ offset = 0; goto disp; } else { offset = 0; } s = NULL; a = (only_img ? NULL : retrieveCurrentAnchor(Currentbuf)); if (a == NULL) { a = (only_img ? NULL : retrieveCurrentForm(Currentbuf)); if (a == NULL) { a = retrieveCurrentImg(Currentbuf); if (a == NULL) return; } else s = Strnew_charp(form2str((FormItemList *)a->url)); } if (s == NULL) { parseURL2(a->url, &pu, baseURL(Currentbuf)); s = parsedURL2Str(&pu); } if (DecodeURL) s = Strnew_charp(url_decode2(s->ptr, Currentbuf)); #ifdef USE_M17N s = checkType(s, &pp, NULL); p = NewAtom_N(Lineprop, s->length); bcopy((void *)pp, (void *)p, s->length * sizeof(Lineprop)); #endif disp: n = searchKeyNum(); if (n > 1 && s->length > (n - 1) * (COLS - 1)) offset = (n - 1) * (COLS - 1); #ifdef USE_M17N while (offset < s->length && p[offset] & PC_WCHAR2) offset++; #endif disp_message_nomouse(&s->ptr[offset], TRUE); } /* peek URL */ DEFUN(peekURL, PEEK_LINK, "Show target address") { _peekURL(0); } /* peek URL of image */ DEFUN(peekIMG, PEEK_IMG, "Show image address") { _peekURL(1); } /* show current URL */ static Str currentURL(void) { if (Currentbuf->bufferprop & BP_INTERNAL) return Strnew_size(0); return parsedURL2Str(&Currentbuf->currentURL); } DEFUN(curURL, PEEK, "Show current address") { static Str s = NULL; #ifdef USE_M17N static Lineprop *p = NULL; Lineprop *pp; #endif static int offset = 0, n; if (Currentbuf->bufferprop & BP_INTERNAL) return; if (CurrentKey == prev_key && s != NULL) { if (s->length - offset >= COLS) offset++; else if (s->length <= offset) /* bug ? */ offset = 0; } else { offset = 0; s = currentURL(); if (DecodeURL) s = Strnew_charp(url_decode2(s->ptr, NULL)); #ifdef USE_M17N s = checkType(s, &pp, NULL); p = NewAtom_N(Lineprop, s->length); bcopy((void *)pp, (void *)p, s->length * sizeof(Lineprop)); #endif } n = searchKeyNum(); if (n > 1 && s->length > (n - 1) * (COLS - 1)) offset = (n - 1) * (COLS - 1); #ifdef USE_M17N while (offset < s->length && p[offset] & PC_WCHAR2) offset++; #endif disp_message_nomouse(&s->ptr[offset], TRUE); } /* view HTML source */ DEFUN(vwSrc, SOURCE VIEW, "Toggle between HTML shown or processed") { Buffer *buf; if (Currentbuf->type == NULL || Currentbuf->bufferprop & BP_FRAME) return; if ((buf = Currentbuf->linkBuffer[LB_SOURCE]) != NULL || (buf = Currentbuf->linkBuffer[LB_N_SOURCE]) != NULL) { Currentbuf = buf; displayBuffer(Currentbuf, B_NORMAL); return; } if (Currentbuf->sourcefile == NULL) { if (Currentbuf->pagerSource && !strcasecmp(Currentbuf->type, "text/plain")) { #ifdef USE_M17N wc_ces old_charset; wc_bool old_fix_width_conv; #endif FILE *f; Str tmpf = tmpfname(TMPF_SRC, NULL); f = fopen(tmpf->ptr, "w"); if (f == NULL) return; #ifdef USE_M17N old_charset = DisplayCharset; old_fix_width_conv = WcOption.fix_width_conv; DisplayCharset = (Currentbuf->document_charset != WC_CES_US_ASCII) ? Currentbuf->document_charset : 0; WcOption.fix_width_conv = WC_FALSE; #endif saveBufferBody(Currentbuf, f, TRUE); #ifdef USE_M17N DisplayCharset = old_charset; WcOption.fix_width_conv = old_fix_width_conv; #endif fclose(f); Currentbuf->sourcefile = tmpf->ptr; } else { return; } } buf = newBuffer(INIT_BUFFER_WIDTH); if (is_html_type(Currentbuf->type)) { buf->type = "text/plain"; if (Currentbuf->real_type && is_html_type(Currentbuf->real_type)) buf->real_type = "text/plain"; else buf->real_type = Currentbuf->real_type; buf->buffername = Sprintf("source of %s", Currentbuf->buffername)->ptr; buf->linkBuffer[LB_N_SOURCE] = Currentbuf; Currentbuf->linkBuffer[LB_SOURCE] = buf; } else if (!strcasecmp(Currentbuf->type, "text/plain")) { buf->type = "text/html"; if (Currentbuf->real_type && !strcasecmp(Currentbuf->real_type, "text/plain")) buf->real_type = "text/html"; else buf->real_type = Currentbuf->real_type; buf->buffername = Sprintf("HTML view of %s", Currentbuf->buffername)->ptr; buf->linkBuffer[LB_SOURCE] = Currentbuf; Currentbuf->linkBuffer[LB_N_SOURCE] = buf; } else { return; } buf->currentURL = Currentbuf->currentURL; buf->real_scheme = Currentbuf->real_scheme; buf->filename = Currentbuf->filename; buf->sourcefile = Currentbuf->sourcefile; buf->header_source = Currentbuf->header_source; buf->search_header = Currentbuf->search_header; #ifdef USE_M17N buf->document_charset = Currentbuf->document_charset; #endif buf->clone = Currentbuf->clone; (*buf->clone)++; buf->need_reshape = TRUE; reshapeBuffer(buf); pushBuffer(buf); displayBuffer(Currentbuf, B_NORMAL); } /* reload */ DEFUN(reload, RELOAD, "Load current document anew") { Buffer *buf, *fbuf = NULL, sbuf; #ifdef USE_M17N wc_ces old_charset; #endif Str url; FormList *request; int multipart; if (Currentbuf->bufferprop & BP_INTERNAL) { if (!strcmp(Currentbuf->buffername, DOWNLOAD_LIST_TITLE)) { ldDL(); return; } /* FIXME: gettextize? */ disp_err_message("Can't reload...", TRUE); return; } if (Currentbuf->currentURL.scheme == SCM_LOCAL && !strcmp(Currentbuf->currentURL.file, "-")) { /* file is std input */ /* FIXME: gettextize? */ disp_err_message("Can't reload stdin", TRUE); return; } copyBuffer(&sbuf, Currentbuf); if (Currentbuf->bufferprop & BP_FRAME && (fbuf = Currentbuf->linkBuffer[LB_N_FRAME])) { if (fmInitialized) { message("Rendering frame", 0, 0); refresh(); } if (!(buf = renderFrame(fbuf, 1))) { displayBuffer(Currentbuf, B_NORMAL); return; } if (fbuf->linkBuffer[LB_FRAME]) { if (buf->sourcefile && fbuf->linkBuffer[LB_FRAME]->sourcefile && !strcmp(buf->sourcefile, fbuf->linkBuffer[LB_FRAME]->sourcefile)) fbuf->linkBuffer[LB_FRAME]->sourcefile = NULL; delBuffer(fbuf->linkBuffer[LB_FRAME]); } fbuf->linkBuffer[LB_FRAME] = buf; buf->linkBuffer[LB_N_FRAME] = fbuf; pushBuffer(buf); Currentbuf = buf; if (Currentbuf->firstLine) { COPY_BUFROOT(Currentbuf, &sbuf); restorePosition(Currentbuf, &sbuf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); return; } else if (Currentbuf->frameset != NULL) fbuf = Currentbuf->linkBuffer[LB_FRAME]; multipart = 0; if (Currentbuf->form_submit) { request = Currentbuf->form_submit->parent; if (request->method == FORM_METHOD_POST && request->enctype == FORM_ENCTYPE_MULTIPART) { Str query; struct stat st; multipart = 1; query_from_followform(&query, Currentbuf->form_submit, multipart); stat(request->body, &st); request->length = st.st_size; } } else { request = NULL; } url = parsedURL2Str(&Currentbuf->currentURL); /* FIXME: gettextize? */ message("Reloading...", 0, 0); refresh(); #ifdef USE_M17N old_charset = DocumentCharset; if (Currentbuf->document_charset != WC_CES_US_ASCII) DocumentCharset = Currentbuf->document_charset; #endif SearchHeader = Currentbuf->search_header; DefaultType = Currentbuf->real_type; buf = loadGeneralFile(url->ptr, NULL, NO_REFERER, RG_NOCACHE, request); #ifdef USE_M17N DocumentCharset = old_charset; #endif SearchHeader = FALSE; DefaultType = NULL; if (multipart) unlink(request->body); if (buf == NULL) { /* FIXME: gettextize? */ disp_err_message("Can't reload...", TRUE); return; } else if (buf == NO_BUFFER) { displayBuffer(Currentbuf, B_NORMAL); return; } if (fbuf != NULL) Firstbuf = deleteBuffer(Firstbuf, fbuf); repBuffer(Currentbuf, buf); if ((buf->type != NULL) && (sbuf.type != NULL) && ((!strcasecmp(buf->type, "text/plain") && is_html_type(sbuf.type)) || (is_html_type(buf->type) && !strcasecmp(sbuf.type, "text/plain")))) { vwSrc(); if (Currentbuf != buf) Firstbuf = deleteBuffer(Firstbuf, buf); } Currentbuf->search_header = sbuf.search_header; Currentbuf->form_submit = sbuf.form_submit; if (Currentbuf->firstLine) { COPY_BUFROOT(Currentbuf, &sbuf); restorePosition(Currentbuf, &sbuf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* reshape */ DEFUN(reshape, RESHAPE, "Re-render document") { Currentbuf->need_reshape = TRUE; reshapeBuffer(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } #ifdef USE_M17N static void _docCSet(wc_ces charset) { if (Currentbuf->bufferprop & BP_INTERNAL) return; if (Currentbuf->sourcefile == NULL) { disp_message("Can't reload...", FALSE); return; } Currentbuf->document_charset = charset; Currentbuf->need_reshape = TRUE; displayBuffer(Currentbuf, B_FORCE_REDRAW); } void change_charset(struct parsed_tagarg *arg) { Buffer *buf = Currentbuf->linkBuffer[LB_N_INFO]; wc_ces charset; if (buf == NULL) return; delBuffer(Currentbuf); Currentbuf = buf; if (Currentbuf->bufferprop & BP_INTERNAL) return; charset = Currentbuf->document_charset; for (; arg; arg = arg->next) { if (!strcmp(arg->arg, "charset")) charset = atoi(arg->value); } _docCSet(charset); } DEFUN(docCSet, CHARSET, "Change the character encoding for the current document") { char *cs; wc_ces charset; cs = searchKeyData(); if (cs == NULL || *cs == '\0') /* FIXME: gettextize? */ cs = inputStr("Document charset: ", wc_ces_to_charset(Currentbuf->document_charset)); charset = wc_guess_charset_short(cs, 0); if (charset == 0) { displayBuffer(Currentbuf, B_NORMAL); return; } _docCSet(charset); } DEFUN(defCSet, DEFAULT_CHARSET, "Change the default character encoding") { char *cs; wc_ces charset; cs = searchKeyData(); if (cs == NULL || *cs == '\0') /* FIXME: gettextize? */ cs = inputStr("Default document charset: ", wc_ces_to_charset(DocumentCharset)); charset = wc_guess_charset_short(cs, 0); if (charset != 0) DocumentCharset = charset; displayBuffer(Currentbuf, B_NORMAL); } #endif /* mark URL-like patterns as anchors */ void chkURLBuffer(Buffer *buf) { static char *url_like_pat[] = { "https?://[a-zA-Z0-9][a-zA-Z0-9:%\\-\\./?=~_\\&+@#,\\$;]*[a-zA-Z0-9_/=\\-]", "file:/[a-zA-Z0-9:%\\-\\./=_\\+@#,\\$;]*", #ifdef USE_GOPHER "gopher://[a-zA-Z0-9][a-zA-Z0-9:%\\-\\./_]*", #endif /* USE_GOPHER */ "ftp://[a-zA-Z0-9][a-zA-Z0-9:%\\-\\./=_+@#,\\$]*[a-zA-Z0-9_/]", #ifdef USE_NNTP "news:[^<> ][^<> ]*", "nntp://[a-zA-Z0-9][a-zA-Z0-9:%\\-\\./_]*", #endif /* USE_NNTP */ #ifndef USE_W3MMAILER /* see also chkExternalURIBuffer() */ "mailto:[^<> ][^<> ]*@[a-zA-Z0-9][a-zA-Z0-9\\-\\._]*[a-zA-Z0-9]", #endif #ifdef INET6 "https?://[a-zA-Z0-9:%\\-\\./_@]*\\[[a-fA-F0-9:][a-fA-F0-9:\\.]*\\][a-zA-Z0-9:%\\-\\./?=~_\\&+@#,\\$;]*", "ftp://[a-zA-Z0-9:%\\-\\./_@]*\\[[a-fA-F0-9:][a-fA-F0-9:\\.]*\\][a-zA-Z0-9:%\\-\\./=_+@#,\\$]*", #endif /* INET6 */ NULL }; int i; for (i = 0; url_like_pat[i]; i++) { reAnchor(buf, url_like_pat[i]); } #ifdef USE_EXTERNAL_URI_LOADER chkExternalURIBuffer(buf); #endif buf->check_url |= CHK_URL; } DEFUN(chkURL, MARK_URL, "Turn URL-like strings into hyperlinks") { chkURLBuffer(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(chkWORD, MARK_WORD, "Turn current word into hyperlink") { char *p; int spos, epos; p = getCurWord(Currentbuf, &spos, &epos); if (p == NULL) return; reAnchorWord(Currentbuf, Currentbuf->currentLine, spos, epos); displayBuffer(Currentbuf, B_FORCE_REDRAW); } #ifdef USE_NNTP /* mark Message-ID-like patterns as NEWS anchors */ void chkNMIDBuffer(Buffer *buf) { static char *url_like_pat[] = { "<[!-;=?-~]+@[a-zA-Z0-9\\.\\-_]+>", NULL, }; int i; for (i = 0; url_like_pat[i]; i++) { reAnchorNews(buf, url_like_pat[i]); } buf->check_url |= CHK_NMID; } DEFUN(chkNMID, MARK_MID, "Turn Message-ID-like strings into hyperlinks") { chkNMIDBuffer(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } #endif /* USE_NNTP */ /* render frames */ DEFUN(rFrame, FRAME, "Toggle rendering HTML frames") { Buffer *buf; if ((buf = Currentbuf->linkBuffer[LB_FRAME]) != NULL) { Currentbuf = buf; displayBuffer(Currentbuf, B_NORMAL); return; } if (Currentbuf->frameset == NULL) { if ((buf = Currentbuf->linkBuffer[LB_N_FRAME]) != NULL) { Currentbuf = buf; displayBuffer(Currentbuf, B_NORMAL); } return; } if (fmInitialized) { message("Rendering frame", 0, 0); refresh(); } buf = renderFrame(Currentbuf, 0); if (buf == NULL) { displayBuffer(Currentbuf, B_NORMAL); return; } buf->linkBuffer[LB_N_FRAME] = Currentbuf; Currentbuf->linkBuffer[LB_FRAME] = buf; pushBuffer(buf); if (fmInitialized && display_ok) displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* spawn external browser */ static void invoke_browser(char *url) { Str cmd; char *browser = NULL; int bg = 0, len; CurrentKeyData = NULL; /* not allowed in w3m-control: */ browser = searchKeyData(); if (browser == NULL || *browser == '\0') { switch (prec_num) { case 0: case 1: browser = ExtBrowser; break; case 2: browser = ExtBrowser2; break; case 3: browser = ExtBrowser3; break; case 4: browser = ExtBrowser4; break; case 5: browser = ExtBrowser5; break; case 6: browser = ExtBrowser6; break; case 7: browser = ExtBrowser7; break; case 8: browser = ExtBrowser8; break; case 9: browser = ExtBrowser9; break; } if (browser == NULL || *browser == '\0') { browser = inputStr("Browse command: ", NULL); if (browser != NULL) browser = conv_to_system(browser); } } else { browser = conv_to_system(browser); } if (browser == NULL || *browser == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } if ((len = strlen(browser)) >= 2 && browser[len - 1] == '&' && browser[len - 2] != '\\') { browser = allocStr(browser, len - 2); bg = 1; } cmd = myExtCommand(browser, shell_quote(url), FALSE); Strremovetrailingspaces(cmd); fmTerm(); mySystem(cmd->ptr, bg); fmInit(); displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(extbrz, EXTERN, "Display using an external browser") { if (Currentbuf->bufferprop & BP_INTERNAL) { /* FIXME: gettextize? */ disp_err_message("Can't browse...", TRUE); return; } if (Currentbuf->currentURL.scheme == SCM_LOCAL && !strcmp(Currentbuf->currentURL.file, "-")) { /* file is std input */ /* FIXME: gettextize? */ disp_err_message("Can't browse stdin", TRUE); return; } invoke_browser(parsedURL2Str(&Currentbuf->currentURL)->ptr); } DEFUN(linkbrz, EXTERN_LINK, "Display target using an external browser") { Anchor *a; ParsedURL pu; if (Currentbuf->firstLine == NULL) return; a = retrieveCurrentAnchor(Currentbuf); if (a == NULL) return; parseURL2(a->url, &pu, baseURL(Currentbuf)); invoke_browser(parsedURL2Str(&pu)->ptr); } /* show current line number and number of lines in the entire document */ DEFUN(curlno, LINE_INFO, "Display current position in document") { Line *l = Currentbuf->currentLine; Str tmp; int cur = 0, all = 0, col = 0, len = 0; if (l != NULL) { cur = l->real_linenumber; col = l->bwidth + Currentbuf->currentColumn + Currentbuf->cursorX + 1; while (l->next && l->next->bpos) l = l->next; if (l->width < 0) l->width = COLPOS(l, l->len); len = l->bwidth + l->width; } if (Currentbuf->lastLine) all = Currentbuf->lastLine->real_linenumber; if (Currentbuf->pagerSource && !(Currentbuf->bufferprop & BP_CLOSE)) tmp = Sprintf("line %d col %d/%d", cur, col, len); else tmp = Sprintf("line %d/%d (%d%%) col %d/%d", cur, all, (int)((double)cur * 100.0 / (double)(all ? all : 1) + 0.5), col, len); #ifdef USE_M17N Strcat_charp(tmp, " "); Strcat_charp(tmp, wc_ces_to_charset_desc(Currentbuf->document_charset)); #endif disp_message(tmp->ptr, FALSE); } #ifdef USE_IMAGE DEFUN(dispI, DISPLAY_IMAGE, "Restart loading and drawing of images") { if (!displayImage) initImage(); if (!activeImage) return; displayImage = TRUE; /* * if (!(Currentbuf->type && is_html_type(Currentbuf->type))) * return; */ Currentbuf->image_flag = IMG_FLAG_AUTO; Currentbuf->need_reshape = TRUE; displayBuffer(Currentbuf, B_REDRAW_IMAGE); } DEFUN(stopI, STOP_IMAGE, "Stop loading and drawing of images") { if (!activeImage) return; /* * if (!(Currentbuf->type && is_html_type(Currentbuf->type))) * return; */ Currentbuf->image_flag = IMG_FLAG_SKIP; displayBuffer(Currentbuf, B_REDRAW_IMAGE); } #endif #ifdef USE_MOUSE static int mouse_scroll_line(void) { if (relative_wheel_scroll) return (relative_wheel_scroll_ratio * LASTLINE + 99) / 100; else return fixed_wheel_scroll_count; } static TabBuffer * posTab(int x, int y) { TabBuffer *tab; if (mouse_action.menu_str && x < mouse_action.menu_width && y == 0) return NO_TABBUFFER; if (y > LastTab->y) return NULL; for (tab = FirstTab; tab; tab = tab->nextTab) { if (tab->x1 <= x && x <= tab->x2 && tab->y == y) return tab; } return NULL; } static void do_mouse_action(int btn, int x, int y) { MouseActionMap *map = NULL; int ny = -1; if (nTab > 1 || mouse_action.menu_str) ny = LastTab->y + 1; switch (btn) { case MOUSE_BTN1_DOWN: btn = 0; break; case MOUSE_BTN2_DOWN: btn = 1; break; case MOUSE_BTN3_DOWN: btn = 2; break; default: return; } if (y < ny) { if (mouse_action.menu_str && x >= 0 && x < mouse_action.menu_width) { if (mouse_action.menu_map[btn]) map = &mouse_action.menu_map[btn][x]; } else map = &mouse_action.tab_map[btn]; } else if (y == LASTLINE) { if (mouse_action.lastline_str && x >= 0 && x < mouse_action.lastline_width) { if (mouse_action.lastline_map[btn]) map = &mouse_action.lastline_map[btn][x]; } } else if (y > ny) { if (y == Currentbuf->cursorY + Currentbuf->rootY && (x == Currentbuf->cursorX + Currentbuf->rootX #ifdef USE_M17N || (WcOption.use_wide && Currentbuf->currentLine != NULL && (CharType(Currentbuf->currentLine->propBuf[Currentbuf->pos]) == PC_KANJI1) && x == Currentbuf->cursorX + Currentbuf->rootX + 1) #endif )) { if (retrieveCurrentAnchor(Currentbuf) || retrieveCurrentForm(Currentbuf)) { map = &mouse_action.active_map[btn]; if (!(map && map->func)) map = &mouse_action.anchor_map[btn]; } } else { int cx = Currentbuf->cursorX, cy = Currentbuf->cursorY; cursorXY(Currentbuf, x - Currentbuf->rootX, y - Currentbuf->rootY); if (y == Currentbuf->cursorY + Currentbuf->rootY && (x == Currentbuf->cursorX + Currentbuf->rootX #ifdef USE_M17N || (WcOption.use_wide && Currentbuf->currentLine != NULL && (CharType(Currentbuf->currentLine-> propBuf[Currentbuf->pos]) == PC_KANJI1) && x == Currentbuf->cursorX + Currentbuf->rootX + 1) #endif ) && (retrieveCurrentAnchor(Currentbuf) || retrieveCurrentForm(Currentbuf))) map = &mouse_action.anchor_map[btn]; cursorXY(Currentbuf, cx, cy); } } else { return; } if (!(map && map->func)) map = &mouse_action.default_map[btn]; if (map && map->func) { mouse_action.in_action = TRUE; mouse_action.cursorX = x; mouse_action.cursorY = y; CurrentKey = -1; CurrentKeyData = NULL; CurrentCmdData = map->data; (*map->func) (); CurrentCmdData = NULL; } } static void process_mouse(int btn, int x, int y) { int delta_x, delta_y, i; static int press_btn = MOUSE_BTN_RESET, press_x, press_y; TabBuffer *t; int ny = -1; if (nTab > 1 || mouse_action.menu_str) ny = LastTab->y + 1; if (btn == MOUSE_BTN_UP) { switch (press_btn) { case MOUSE_BTN1_DOWN: if (press_y == y && press_x == x) do_mouse_action(press_btn, x, y); else if (ny > 0 && y < ny) { if (press_y < ny) { moveTab(posTab(press_x, press_y), posTab(x, y), (press_y == y) ? (press_x < x) : (press_y < y)); return; } else if (press_x >= Currentbuf->rootX) { Buffer *buf = Currentbuf; int cx = Currentbuf->cursorX, cy = Currentbuf->cursorY; t = posTab(x, y); if (t == NULL) return; if (t == NO_TABBUFFER) t = NULL; /* open new tab */ cursorXY(Currentbuf, press_x - Currentbuf->rootX, press_y - Currentbuf->rootY); if (Currentbuf->cursorY == press_y - Currentbuf->rootY && (Currentbuf->cursorX == press_x - Currentbuf->rootX #ifdef USE_M17N || (WcOption.use_wide && Currentbuf->currentLine != NULL && (CharType(Currentbuf->currentLine-> propBuf[Currentbuf->pos]) == PC_KANJI1) && Currentbuf->cursorX == press_x - Currentbuf->rootX - 1) #endif )) { displayBuffer(Currentbuf, B_NORMAL); followTab(t); } if (buf == Currentbuf) cursorXY(Currentbuf, cx, cy); } return; } else { delta_x = x - press_x; delta_y = y - press_y; if (abs(delta_x) < abs(delta_y) / 3) delta_x = 0; if (abs(delta_y) < abs(delta_x) / 3) delta_y = 0; if (reverse_mouse) { delta_y = -delta_y; delta_x = -delta_x; } if (delta_y > 0) { prec_num = delta_y; ldown1(); } else if (delta_y < 0) { prec_num = -delta_y; lup1(); } if (delta_x > 0) { prec_num = delta_x; col1L(); } else if (delta_x < 0) { prec_num = -delta_x; col1R(); } } break; case MOUSE_BTN2_DOWN: case MOUSE_BTN3_DOWN: if (press_y == y && press_x == x) do_mouse_action(press_btn, x, y); break; case MOUSE_BTN4_DOWN_RXVT: for (i = 0; i < mouse_scroll_line(); i++) ldown1(); break; case MOUSE_BTN5_DOWN_RXVT: for (i = 0; i < mouse_scroll_line(); i++) lup1(); break; } } else if (btn == MOUSE_BTN4_DOWN_XTERM) { for (i = 0; i < mouse_scroll_line(); i++) ldown1(); } else if (btn == MOUSE_BTN5_DOWN_XTERM) { for (i = 0; i < mouse_scroll_line(); i++) lup1(); } if (btn != MOUSE_BTN4_DOWN_RXVT || press_btn == MOUSE_BTN_RESET) { press_btn = btn; press_x = x; press_y = y; } else { press_btn = MOUSE_BTN_RESET; } } DEFUN(msToggle, MOUSE_TOGGLE, "Toggle mouse support") { if (use_mouse) { use_mouse = FALSE; } else { use_mouse = TRUE; } displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(mouse, MOUSE, "mouse operation") { int btn, x, y; btn = (unsigned char)getch() - 32; #if defined(__CYGWIN__) && CYGWIN_VERSION_DLL_MAJOR < 1005 if (cygwin_mouse_btn_swapped) { if (btn == MOUSE_BTN2_DOWN) btn = MOUSE_BTN3_DOWN; else if (btn == MOUSE_BTN3_DOWN) btn = MOUSE_BTN2_DOWN; } #endif x = (unsigned char)getch() - 33; if (x < 0) x += 0x100; y = (unsigned char)getch() - 33; if (y < 0) y += 0x100; if (x < 0 || x >= COLS || y < 0 || y > LASTLINE) return; process_mouse(btn, x, y); } DEFUN(sgrmouse, SGRMOUSE, "SGR 1006 mouse operation") { int btn = 0, x = 0, y = 0; unsigned char c; do { c = getch(); if (IS_DIGIT(c)) btn = btn * 10 + c - '0'; else if (c == ';') break; else return; } while (1); #if defined(__CYGWIN__) && CYGWIN_VERSION_DLL_MAJOR < 1005 if (cygwin_mouse_btn_swapped) { if (btn == MOUSE_BTN2_DOWN) btn = MOUSE_BTN3_DOWN; else if (btn == MOUSE_BTN3_DOWN) btn = MOUSE_BTN2_DOWN; }; #endif do { c = getch(); if (IS_DIGIT(c)) x = x * 10 + c - '0'; else if (c == ';') break; else return; } while (1); if (x>0) x--; do { c = getch(); if (IS_DIGIT(c)) y = y * 10 + c - '0'; else if (c == 'M') break; else if (c == 'm') { btn |= 3; break; } else return; } while (1); if (y>0) y--; if (x < 0 || x >= COLS || y < 0 || y > LASTLINE) return; process_mouse(btn, x, y); } #ifdef USE_GPM int gpm_process_mouse(Gpm_Event * event, void *data) { int btn = MOUSE_BTN_RESET, x, y; if (event->type & GPM_UP) btn = MOUSE_BTN_UP; else if (event->type & GPM_DOWN) { switch (event->buttons) { case GPM_B_LEFT: btn = MOUSE_BTN1_DOWN; break; case GPM_B_MIDDLE: btn = MOUSE_BTN2_DOWN; break; case GPM_B_RIGHT: btn = MOUSE_BTN3_DOWN; break; } } else { GPM_DRAWPOINTER(event); return 0; } x = event->x; y = event->y; process_mouse(btn, x - 1, y - 1); return 0; } #endif /* USE_GPM */ #ifdef USE_SYSMOUSE int sysm_process_mouse(int x, int y, int nbs, int obs) { int btn; int bits; if (obs & ~nbs) btn = MOUSE_BTN_UP; else if (nbs & ~obs) { bits = nbs & ~obs; btn = bits & 0x1 ? MOUSE_BTN1_DOWN : (bits & 0x2 ? MOUSE_BTN2_DOWN : (bits & 0x4 ? MOUSE_BTN3_DOWN : 0)); } else /* nbs == obs */ return 0; process_mouse(btn, x, y); return 0; } #endif /* USE_SYSMOUSE */ DEFUN(movMs, MOVE_MOUSE, "Move cursor to mouse pointer") { if (!mouse_action.in_action) return; if ((nTab > 1 || mouse_action.menu_str) && mouse_action.cursorY < LastTab->y + 1) return; else if (mouse_action.cursorX >= Currentbuf->rootX && mouse_action.cursorY < LASTLINE) { cursorXY(Currentbuf, mouse_action.cursorX - Currentbuf->rootX, mouse_action.cursorY - Currentbuf->rootY); } displayBuffer(Currentbuf, B_NORMAL); } #ifdef USE_MENU #ifdef KANJI_SYMBOLS #define FRAME_WIDTH 2 #else #define FRAME_WIDTH 1 #endif DEFUN(menuMs, MENU_MOUSE, "Pop up menu at mouse pointer") { if (!mouse_action.in_action) return; if ((nTab > 1 || mouse_action.menu_str) && mouse_action.cursorY < LastTab->y + 1) mouse_action.cursorX -= FRAME_WIDTH + 1; else if (mouse_action.cursorX >= Currentbuf->rootX && mouse_action.cursorY < LASTLINE) { cursorXY(Currentbuf, mouse_action.cursorX - Currentbuf->rootX, mouse_action.cursorY - Currentbuf->rootY); displayBuffer(Currentbuf, B_NORMAL); } mainMn(); } #endif DEFUN(tabMs, TAB_MOUSE, "Select tab by mouse action") { TabBuffer *tab; if (!mouse_action.in_action) return; tab = posTab(mouse_action.cursorX, mouse_action.cursorY); if (!tab || tab == NO_TABBUFFER) return; CurrentTab = tab; displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(closeTMs, CLOSE_TAB_MOUSE, "Close tab at mouse pointer") { TabBuffer *tab; if (!mouse_action.in_action) return; tab = posTab(mouse_action.cursorX, mouse_action.cursorY); if (!tab || tab == NO_TABBUFFER) return; deleteTab(tab); displayBuffer(Currentbuf, B_FORCE_REDRAW); } #endif /* USE_MOUSE */ DEFUN(dispVer, VERSION, "Display the version of w3m") { disp_message(Sprintf("w3m version %s", w3m_version)->ptr, TRUE); } DEFUN(wrapToggle, WRAP_TOGGLE, "Toggle wrapping mode in searches") { if (WrapSearch) { WrapSearch = FALSE; /* FIXME: gettextize? */ disp_message("Wrap search off", TRUE); } else { WrapSearch = TRUE; /* FIXME: gettextize? */ disp_message("Wrap search on", TRUE); } } static char * getCurWord(Buffer *buf, int *spos, int *epos) { char *p; Line *l = buf->currentLine; int b, e; *spos = 0; *epos = 0; if (l == NULL) return NULL; p = l->lineBuf; e = buf->pos; while (e > 0 && !is_wordchar(getChar(&p[e]))) prevChar(e, l); if (!is_wordchar(getChar(&p[e]))) return NULL; b = e; while (b > 0) { int tmp = b; prevChar(tmp, l); if (!is_wordchar(getChar(&p[tmp]))) break; b = tmp; } while (e < l->len && is_wordchar(getChar(&p[e]))) nextChar(e, l); *spos = b; *epos = e; return &p[b]; } static char * GetWord(Buffer *buf) { int b, e; char *p; if ((p = getCurWord(buf, &b, &e)) != NULL) { return Strnew_charp_n(p, e - b)->ptr; } return NULL; } #ifdef USE_DICT static void execdict(char *word) { char *w, *dictcmd; Buffer *buf; if (!UseDictCommand || word == NULL || *word == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } w = conv_to_system(word); if (*w == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } dictcmd = Sprintf("%s?%s", DictCommand, Str_form_quote(Strnew_charp(w))->ptr)->ptr; buf = loadGeneralFile(dictcmd, NULL, NO_REFERER, 0, NULL); if (buf == NULL) { disp_message("Execution failed", TRUE); return; } else if (buf != NO_BUFFER) { buf->filename = w; buf->buffername = Sprintf("%s %s", DICTBUFFERNAME, word)->ptr; if (buf->type == NULL) buf->type = "text/plain"; pushBuffer(buf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(dictword, DICT_WORD, "Execute dictionary command (see README.dict)") { execdict(inputStr("(dictionary)!", "")); } DEFUN(dictwordat, DICT_WORD_AT, "Execute dictionary command for word at cursor") { execdict(GetWord(Currentbuf)); } #endif /* USE_DICT */ void set_buffer_environ(Buffer *buf) { static Buffer *prev_buf = NULL; static Line *prev_line = NULL; static int prev_pos = -1; Line *l; if (buf == NULL) return; if (buf != prev_buf) { set_environ("W3M_SOURCEFILE", buf->sourcefile); set_environ("W3M_FILENAME", buf->filename); set_environ("W3M_TITLE", buf->buffername); set_environ("W3M_URL", parsedURL2Str(&buf->currentURL)->ptr); set_environ("W3M_TYPE", buf->real_type ? buf->real_type : "unknown"); #ifdef USE_M17N set_environ("W3M_CHARSET", wc_ces_to_charset(buf->document_charset)); #endif } l = buf->currentLine; if (l && (buf != prev_buf || l != prev_line || buf->pos != prev_pos)) { Anchor *a; ParsedURL pu; char *s = GetWord(buf); set_environ("W3M_CURRENT_WORD", s ? s : ""); a = retrieveCurrentAnchor(buf); if (a) { parseURL2(a->url, &pu, baseURL(buf)); set_environ("W3M_CURRENT_LINK", parsedURL2Str(&pu)->ptr); } else set_environ("W3M_CURRENT_LINK", ""); a = retrieveCurrentImg(buf); if (a) { parseURL2(a->url, &pu, baseURL(buf)); set_environ("W3M_CURRENT_IMG", parsedURL2Str(&pu)->ptr); } else set_environ("W3M_CURRENT_IMG", ""); a = retrieveCurrentForm(buf); if (a) set_environ("W3M_CURRENT_FORM", form2str((FormItemList *)a->url)); else set_environ("W3M_CURRENT_FORM", ""); set_environ("W3M_CURRENT_LINE", Sprintf("%ld", l->real_linenumber)->ptr); set_environ("W3M_CURRENT_COLUMN", Sprintf("%d", buf->currentColumn + buf->cursorX + 1)->ptr); } else if (!l) { set_environ("W3M_CURRENT_WORD", ""); set_environ("W3M_CURRENT_LINK", ""); set_environ("W3M_CURRENT_IMG", ""); set_environ("W3M_CURRENT_FORM", ""); set_environ("W3M_CURRENT_LINE", "0"); set_environ("W3M_CURRENT_COLUMN", "0"); } prev_buf = buf; prev_line = l; prev_pos = buf->pos; } char * searchKeyData(void) { char *data = NULL; if (CurrentKeyData != NULL && *CurrentKeyData != '\0') data = CurrentKeyData; else if (CurrentCmdData != NULL && *CurrentCmdData != '\0') data = CurrentCmdData; else if (CurrentKey >= 0) data = getKeyData(CurrentKey); CurrentKeyData = NULL; CurrentCmdData = NULL; if (data == NULL || *data == '\0') return NULL; return allocStr(data, -1); } static int searchKeyNum(void) { char *d; int n = 1; d = searchKeyData(); if (d != NULL) n = atoi(d); return n * PREC_NUM; } #ifdef __EMX__ #ifdef USE_M17N static char * getCodePage(void) { unsigned long CpList[8], CpSize; if (!getenv("WINDOWID") && !DosQueryCp(sizeof(CpList), CpList, &CpSize)) return Sprintf("CP%d", *CpList)->ptr; return NULL; } #endif #endif void deleteFiles() { Buffer *buf; char *f; for (CurrentTab = FirstTab; CurrentTab; CurrentTab = CurrentTab->nextTab) { while (Firstbuf && Firstbuf != NO_BUFFER) { buf = Firstbuf->nextBuffer; discardBuffer(Firstbuf); Firstbuf = buf; } } while ((f = popText(fileToDelete)) != NULL) { unlink(f); if (enable_inline_image == 2 && strcmp(f+strlen(f)-4, ".gif") == 0) { Str firstframe = Strnew_charp(f); Strcat_charp(firstframe, "-1"); unlink(firstframe->ptr); } } } void w3m_exit(int i) { #ifdef USE_MIGEMO init_migemo(); /* close pipe to migemo */ #endif stopDownload(); deleteFiles(); #ifdef USE_SSL free_ssl_ctx(); #endif disconnectFTP(); #ifdef USE_NNTP disconnectNews(); #endif #ifdef __MINGW32_VERSION WSACleanup(); #endif exit(i); } DEFUN(execCmd, COMMAND, "Invoke w3m function(s)") { char *data, *p; int cmd; CurrentKeyData = NULL; /* not allowed in w3m-control: */ data = searchKeyData(); if (data == NULL || *data == '\0') { data = inputStrHist("command [; ...]: ", "", TextHist); if (data == NULL) { displayBuffer(Currentbuf, B_NORMAL); return; } } /* data: FUNC [DATA] [; FUNC [DATA] ...] */ while (*data) { SKIP_BLANKS(data); if (*data == ';') { data++; continue; } p = getWord(&data); cmd = getFuncList(p); if (cmd < 0) break; p = getQWord(&data); CurrentKey = -1; CurrentKeyData = NULL; CurrentCmdData = *p ? p : NULL; #ifdef USE_MOUSE if (use_mouse) mouse_inactive(); #endif w3mFuncList[cmd].func(); #ifdef USE_MOUSE if (use_mouse) mouse_active(); #endif CurrentCmdData = NULL; } displayBuffer(Currentbuf, B_NORMAL); } #ifdef USE_ALARM static MySignalHandler SigAlarm(SIGNAL_ARG) { char *data; if (CurrentAlarm->sec > 0) { CurrentKey = -1; CurrentKeyData = NULL; CurrentCmdData = data = (char *)CurrentAlarm->data; #ifdef USE_MOUSE if (use_mouse) mouse_inactive(); #endif w3mFuncList[CurrentAlarm->cmd].func(); #ifdef USE_MOUSE if (use_mouse) mouse_active(); #endif CurrentCmdData = NULL; if (CurrentAlarm->status == AL_IMPLICIT_ONCE) { CurrentAlarm->sec = 0; CurrentAlarm->status = AL_UNSET; } if (Currentbuf->event) { if (Currentbuf->event->status != AL_UNSET) CurrentAlarm = Currentbuf->event; else Currentbuf->event = NULL; } if (!Currentbuf->event) CurrentAlarm = &DefaultAlarm; if (CurrentAlarm->sec > 0) { mySignal(SIGALRM, SigAlarm); alarm(CurrentAlarm->sec); } } SIGNAL_RETURN; } DEFUN(setAlarm, ALARM, "Set alarm") { char *data; int sec = 0, cmd = -1; CurrentKeyData = NULL; /* not allowed in w3m-control: */ data = searchKeyData(); if (data == NULL || *data == '\0') { data = inputStrHist("(Alarm)sec command: ", "", TextHist); if (data == NULL) { displayBuffer(Currentbuf, B_NORMAL); return; } } if (*data != '\0') { sec = atoi(getWord(&data)); if (sec > 0) cmd = getFuncList(getWord(&data)); } if (cmd >= 0) { data = getQWord(&data); setAlarmEvent(&DefaultAlarm, sec, AL_EXPLICIT, cmd, data); disp_message_nsec(Sprintf("%dsec %s %s", sec, w3mFuncList[cmd].id, data)->ptr, FALSE, 1, FALSE, TRUE); } else { setAlarmEvent(&DefaultAlarm, 0, AL_UNSET, FUNCNAME_nulcmd, NULL); } displayBuffer(Currentbuf, B_NORMAL); } AlarmEvent * setAlarmEvent(AlarmEvent * event, int sec, short status, int cmd, void *data) { if (event == NULL) event = New(AlarmEvent); event->sec = sec; event->status = status; event->cmd = cmd; event->data = data; return event; } #endif DEFUN(reinit, REINIT, "Reload configuration file") { char *resource = searchKeyData(); if (resource == NULL) { init_rc(); sync_with_option(); #ifdef USE_COOKIE initCookie(); #endif displayBuffer(Currentbuf, B_REDRAW_IMAGE); return; } if (!strcasecmp(resource, "CONFIG") || !strcasecmp(resource, "RC")) { init_rc(); sync_with_option(); displayBuffer(Currentbuf, B_REDRAW_IMAGE); return; } #ifdef USE_COOKIE if (!strcasecmp(resource, "COOKIE")) { initCookie(); return; } #endif if (!strcasecmp(resource, "KEYMAP")) { initKeymap(TRUE); return; } if (!strcasecmp(resource, "MAILCAP")) { initMailcap(); return; } #ifdef USE_MOUSE if (!strcasecmp(resource, "MOUSE")) { initMouseAction(); displayBuffer(Currentbuf, B_REDRAW_IMAGE); return; } #endif #ifdef USE_MENU if (!strcasecmp(resource, "MENU")) { initMenu(); return; } #endif if (!strcasecmp(resource, "MIMETYPES")) { initMimeTypes(); return; } #ifdef USE_EXTERNAL_URI_LOADER if (!strcasecmp(resource, "URIMETHODS")) { initURIMethods(); return; } #endif disp_err_message(Sprintf("Don't know how to reinitialize '%s'", resource)-> ptr, FALSE); } DEFUN(defKey, DEFINE_KEY, "Define a binding between a key stroke combination and a command") { char *data; CurrentKeyData = NULL; /* not allowed in w3m-control: */ data = searchKeyData(); if (data == NULL || *data == '\0') { data = inputStrHist("Key definition: ", "", TextHist); if (data == NULL || *data == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } } setKeymap(allocStr(data, -1), -1, TRUE); displayBuffer(Currentbuf, B_NORMAL); } TabBuffer * newTab(void) { TabBuffer *n; n = New(TabBuffer); if (n == NULL) return NULL; n->nextTab = NULL; n->currentBuffer = NULL; n->firstBuffer = NULL; return n; } static void _newT(void) { TabBuffer *tag; Buffer *buf; int i; tag = newTab(); if (!tag) return; buf = newBuffer(Currentbuf->width); copyBuffer(buf, Currentbuf); buf->nextBuffer = NULL; for (i = 0; i < MAX_LB; i++) buf->linkBuffer[i] = NULL; (*buf->clone)++; tag->firstBuffer = tag->currentBuffer = buf; tag->nextTab = CurrentTab->nextTab; tag->prevTab = CurrentTab; if (CurrentTab->nextTab) CurrentTab->nextTab->prevTab = tag; else LastTab = tag; CurrentTab->nextTab = tag; CurrentTab = tag; nTab++; } DEFUN(newT, NEW_TAB, "Open a new tab (with current document)") { _newT(); displayBuffer(Currentbuf, B_REDRAW_IMAGE); } static TabBuffer * numTab(int n) { TabBuffer *tab; int i; if (n == 0) return CurrentTab; if (n == 1) return FirstTab; if (nTab <= 1) return NULL; for (tab = FirstTab, i = 1; tab && i < n; tab = tab->nextTab, i++) ; return tab; } void calcTabPos(void) { TabBuffer *tab; #if 0 int lcol = 0, rcol = 2, col; #else int lcol = 0, rcol = 0, col; #endif int n1, n2, na, nx, ny, ix, iy; #ifdef USE_MOUSE lcol = mouse_action.menu_str ? mouse_action.menu_width : 0; #endif if (nTab <= 0) return; n1 = (COLS - rcol - lcol) / TabCols; if (n1 >= nTab) { n2 = 1; ny = 1; } else { if (n1 < 0) n1 = 0; n2 = COLS / TabCols; if (n2 == 0) n2 = 1; ny = (nTab - n1 - 1) / n2 + 2; } na = n1 + n2 * (ny - 1); n1 -= (na - nTab) / ny; if (n1 < 0) n1 = 0; na = n1 + n2 * (ny - 1); tab = FirstTab; for (iy = 0; iy < ny && tab; iy++) { if (iy == 0) { nx = n1; col = COLS - rcol - lcol; } else { nx = n2 - (na - nTab + (iy - 1)) / (ny - 1); col = COLS; } for (ix = 0; ix < nx && tab; ix++, tab = tab->nextTab) { tab->x1 = col * ix / nx; tab->x2 = col * (ix + 1) / nx - 1; tab->y = iy; if (iy == 0) { tab->x1 += lcol; tab->x2 += lcol; } } } } TabBuffer * deleteTab(TabBuffer * tab) { Buffer *buf, *next; if (nTab <= 1) return FirstTab; if (tab->prevTab) { if (tab->nextTab) tab->nextTab->prevTab = tab->prevTab; else LastTab = tab->prevTab; tab->prevTab->nextTab = tab->nextTab; if (tab == CurrentTab) CurrentTab = tab->prevTab; } else { /* tab == FirstTab */ tab->nextTab->prevTab = NULL; FirstTab = tab->nextTab; if (tab == CurrentTab) CurrentTab = tab->nextTab; } nTab--; buf = tab->firstBuffer; while (buf && buf != NO_BUFFER) { next = buf->nextBuffer; discardBuffer(buf); buf = next; } return FirstTab; } DEFUN(closeT, CLOSE_TAB, "Close tab") { TabBuffer *tab; if (nTab <= 1) return; if (prec_num) tab = numTab(PREC_NUM); else tab = CurrentTab; if (tab) deleteTab(tab); displayBuffer(Currentbuf, B_REDRAW_IMAGE); } DEFUN(nextT, NEXT_TAB, "Switch to the next tab") { int i; if (nTab <= 1) return; for (i = 0; i < PREC_NUM; i++) { if (CurrentTab->nextTab) CurrentTab = CurrentTab->nextTab; else CurrentTab = FirstTab; } displayBuffer(Currentbuf, B_REDRAW_IMAGE); } DEFUN(prevT, PREV_TAB, "Switch to the previous tab") { int i; if (nTab <= 1) return; for (i = 0; i < PREC_NUM; i++) { if (CurrentTab->prevTab) CurrentTab = CurrentTab->prevTab; else CurrentTab = LastTab; } displayBuffer(Currentbuf, B_REDRAW_IMAGE); } static void followTab(TabBuffer * tab) { Buffer *buf; Anchor *a; #ifdef USE_IMAGE a = retrieveCurrentImg(Currentbuf); if (!(a && a->image && a->image->map)) #endif a = retrieveCurrentAnchor(Currentbuf); if (a == NULL) return; if (tab == CurrentTab) { check_target = FALSE; followA(); check_target = TRUE; return; } _newT(); buf = Currentbuf; check_target = FALSE; followA(); check_target = TRUE; if (tab == NULL) { if (buf != Currentbuf) delBuffer(buf); else deleteTab(CurrentTab); } else if (buf != Currentbuf) { /* buf <- p <- ... <- Currentbuf = c */ Buffer *c, *p; c = Currentbuf; p = prevBuffer(c, buf); p->nextBuffer = NULL; Firstbuf = buf; deleteTab(CurrentTab); CurrentTab = tab; for (buf = p; buf; buf = p) { p = prevBuffer(c, buf); pushBuffer(buf); } } displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(tabA, TAB_LINK, "Follow current hyperlink in a new tab") { followTab(prec_num ? numTab(PREC_NUM) : NULL); } static void tabURL0(TabBuffer * tab, char *prompt, int relative) { Buffer *buf; if (tab == CurrentTab) { goURL0(prompt, relative); return; } _newT(); buf = Currentbuf; goURL0(prompt, relative); if (tab == NULL) { if (buf != Currentbuf) delBuffer(buf); else deleteTab(CurrentTab); } else if (buf != Currentbuf) { /* buf <- p <- ... <- Currentbuf = c */ Buffer *c, *p; c = Currentbuf; p = prevBuffer(c, buf); p->nextBuffer = NULL; Firstbuf = buf; deleteTab(CurrentTab); CurrentTab = tab; for (buf = p; buf; buf = p) { p = prevBuffer(c, buf); pushBuffer(buf); } } displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(tabURL, TAB_GOTO, "Open specified document in a new tab") { tabURL0(prec_num ? numTab(PREC_NUM) : NULL, "Goto URL on new tab: ", FALSE); } DEFUN(tabrURL, TAB_GOTO_RELATIVE, "Open relative address in a new tab") { tabURL0(prec_num ? numTab(PREC_NUM) : NULL, "Goto relative URL on new tab: ", TRUE); } static void moveTab(TabBuffer * t, TabBuffer * t2, int right) { if (t2 == NO_TABBUFFER) t2 = FirstTab; if (!t || !t2 || t == t2 || t == NO_TABBUFFER) return; if (t->prevTab) { if (t->nextTab) t->nextTab->prevTab = t->prevTab; else LastTab = t->prevTab; t->prevTab->nextTab = t->nextTab; } else { t->nextTab->prevTab = NULL; FirstTab = t->nextTab; } if (right) { t->nextTab = t2->nextTab; t->prevTab = t2; if (t2->nextTab) t2->nextTab->prevTab = t; else LastTab = t; t2->nextTab = t; } else { t->prevTab = t2->prevTab; t->nextTab = t2; if (t2->prevTab) t2->prevTab->nextTab = t; else FirstTab = t; t2->prevTab = t; } displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(tabR, TAB_RIGHT, "Move right along the tab bar") { TabBuffer *tab; int i; for (tab = CurrentTab, i = 0; tab && i < PREC_NUM; tab = tab->nextTab, i++) ; moveTab(CurrentTab, tab ? tab : LastTab, TRUE); } DEFUN(tabL, TAB_LEFT, "Move left along the tab bar") { TabBuffer *tab; int i; for (tab = CurrentTab, i = 0; tab && i < PREC_NUM; tab = tab->prevTab, i++) ; moveTab(CurrentTab, tab ? tab : FirstTab, FALSE); } void addDownloadList(pid_t pid, char *url, char *save, char *lock, clen_t size) { DownloadList *d; d = New(DownloadList); d->pid = pid; d->url = url; if (save[0] != '/' && save[0] != '~') save = Strnew_m_charp(CurrentDir, "/", save, NULL)->ptr; d->save = expandPath(save); d->lock = lock; d->size = size; d->time = time(0); d->running = TRUE; d->err = 0; d->next = NULL; d->prev = LastDL; if (LastDL) LastDL->next = d; else FirstDL = d; LastDL = d; add_download_list = TRUE; } int checkDownloadList(void) { DownloadList *d; struct stat st; if (!FirstDL) return FALSE; for (d = FirstDL; d != NULL; d = d->next) { if (d->running && !lstat(d->lock, &st)) return TRUE; } return FALSE; } static char * convert_size3(clen_t size) { Str tmp = Strnew(); int n; do { n = size % 1000; size /= 1000; tmp = Sprintf(size ? ",%.3d%s" : "%d%s", n, tmp->ptr); } while (size); return tmp->ptr; } static Buffer * DownloadListBuffer(void) { DownloadList *d; Str src = NULL; struct stat st; time_t cur_time; int duration, rate, eta; size_t size; if (!FirstDL) return NULL; cur_time = time(0); /* FIXME: gettextize? */ src = Strnew_charp("<html><head><title>" DOWNLOAD_LIST_TITLE "</title></head>\n<body><h1 align=center>" DOWNLOAD_LIST_TITLE "</h1>\n" "<form method=internal action=download><hr>\n"); for (d = LastDL; d != NULL; d = d->prev) { if (lstat(d->lock, &st)) d->running = FALSE; Strcat_charp(src, "<pre>\n"); Strcat(src, Sprintf("%s\n --&gt; %s\n ", html_quote(d->url), html_quote(conv_from_system(d->save)))); duration = cur_time - d->time; if (!stat(d->save, &st)) { size = st.st_size; if (!d->running) { if (!d->err) d->size = size; duration = st.st_mtime - d->time; } } else size = 0; if (d->size) { int i, l = COLS - 6; if (size < d->size) i = 1.0 * l * size / d->size; else i = l; l -= i; while (i-- > 0) Strcat_char(src, '#'); while (l-- > 0) Strcat_char(src, '_'); Strcat_char(src, '\n'); } if ((d->running || d->err) && size < d->size) Strcat(src, Sprintf(" %s / %s bytes (%d%%)", convert_size3(size), convert_size3(d->size), (int)(100.0 * size / d->size))); else Strcat(src, Sprintf(" %s bytes loaded", convert_size3(size))); if (duration > 0) { rate = size / duration; Strcat(src, Sprintf(" %02d:%02d:%02d rate %s/sec", duration / (60 * 60), (duration / 60) % 60, duration % 60, convert_size(rate, 1))); if (d->running && size < d->size && rate) { eta = (d->size - size) / rate; Strcat(src, Sprintf(" eta %02d:%02d:%02d", eta / (60 * 60), (eta / 60) % 60, eta % 60)); } } Strcat_char(src, '\n'); if (!d->running) { Strcat(src, Sprintf("<input type=submit name=ok%d value=OK>", d->pid)); switch (d->err) { case 0: if (size < d->size) Strcat_charp(src, " Download ended but probably not complete"); else Strcat_charp(src, " Download complete"); break; case 1: Strcat_charp(src, " Error: could not open destination file"); break; case 2: Strcat_charp(src, " Error: could not write to file (disk full)"); break; default: Strcat_charp(src, " Error: unknown reason"); } } else Strcat(src, Sprintf("<input type=submit name=stop%d value=STOP>", d->pid)); Strcat_charp(src, "\n</pre><hr>\n"); } Strcat_charp(src, "</form></body></html>"); return loadHTMLString(src); } void download_action(struct parsed_tagarg *arg) { DownloadList *d; pid_t pid; for (; arg; arg = arg->next) { if (!strncmp(arg->arg, "stop", 4)) { pid = (pid_t) atoi(&arg->arg[4]); #ifndef __MINGW32_VERSION kill(pid, SIGKILL); #endif } else if (!strncmp(arg->arg, "ok", 2)) pid = (pid_t) atoi(&arg->arg[2]); else continue; for (d = FirstDL; d; d = d->next) { if (d->pid == pid) { unlink(d->lock); if (d->prev) d->prev->next = d->next; else FirstDL = d->next; if (d->next) d->next->prev = d->prev; else LastDL = d->prev; break; } } } ldDL(); } void stopDownload(void) { DownloadList *d; if (!FirstDL) return; for (d = FirstDL; d != NULL; d = d->next) { if (!d->running) continue; #ifndef __MINGW32_VERSION kill(d->pid, SIGKILL); #endif unlink(d->lock); } } /* download panel */ DEFUN(ldDL, DOWNLOAD_LIST, "Display downloads panel") { Buffer *buf; int replace = FALSE, new_tab = FALSE; #ifdef USE_ALARM int reload; #endif if (Currentbuf->bufferprop & BP_INTERNAL && !strcmp(Currentbuf->buffername, DOWNLOAD_LIST_TITLE)) replace = TRUE; if (!FirstDL) { if (replace) { if (Currentbuf == Firstbuf && Currentbuf->nextBuffer == NULL) { if (nTab > 1) deleteTab(CurrentTab); } else delBuffer(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } return; } #ifdef USE_ALARM reload = checkDownloadList(); #endif buf = DownloadListBuffer(); if (!buf) { displayBuffer(Currentbuf, B_NORMAL); return; } buf->bufferprop |= (BP_INTERNAL | BP_NO_URL); if (replace) { COPY_BUFROOT(buf, Currentbuf); restorePosition(buf, Currentbuf); } if (!replace && open_tab_dl_list) { _newT(); new_tab = TRUE; } pushBuffer(buf); if (replace || new_tab) deletePrevBuf(); #ifdef USE_ALARM if (reload) Currentbuf->event = setAlarmEvent(Currentbuf->event, 1, AL_IMPLICIT, FUNCNAME_reload, NULL); #endif displayBuffer(Currentbuf, B_FORCE_REDRAW); } static void save_buffer_position(Buffer *buf) { BufferPos *b = buf->undo; if (!buf->firstLine) return; if (b && b->top_linenumber == TOP_LINENUMBER(buf) && b->cur_linenumber == CUR_LINENUMBER(buf) && b->currentColumn == buf->currentColumn && b->pos == buf->pos) return; b = New(BufferPos); b->top_linenumber = TOP_LINENUMBER(buf); b->cur_linenumber = CUR_LINENUMBER(buf); b->currentColumn = buf->currentColumn; b->pos = buf->pos; b->bpos = buf->currentLine ? buf->currentLine->bpos : 0; b->next = NULL; b->prev = buf->undo; if (buf->undo) buf->undo->next = b; buf->undo = b; } static void resetPos(BufferPos * b) { Buffer buf; Line top, cur; top.linenumber = b->top_linenumber; cur.linenumber = b->cur_linenumber; cur.bpos = b->bpos; buf.topLine = &top; buf.currentLine = &cur; buf.pos = b->pos; buf.currentColumn = b->currentColumn; restorePosition(Currentbuf, &buf); Currentbuf->undo = b; displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(undoPos, UNDO, "Cancel the last cursor movement") { BufferPos *b = Currentbuf->undo; int i; if (!Currentbuf->firstLine) return; if (!b || !b->prev) return; for (i = 0; i < PREC_NUM && b->prev; i++, b = b->prev) ; resetPos(b); } DEFUN(redoPos, REDO, "Cancel the last undo") { BufferPos *b = Currentbuf->undo; int i; if (!Currentbuf->firstLine) return; if (!b || !b->next) return; for (i = 0; i < PREC_NUM && b->next; i++, b = b->next) ; resetPos(b); }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_589_4
crossvul-cpp_data_good_1593_0
/* abrt-hook-ccpp.cpp - the hook for C/C++ crashing program Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com) Copyright (C) 2009 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/utsname.h> #include "libabrt.h" #define DUMP_SUID_UNSAFE 1 #define DUMP_SUID_SAFE 2 /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) static char* malloc_readlink(const char *linkname) { char buf[PATH_MAX + 1]; int len; len = readlink(linkname, buf, sizeof(buf)-1); if (len >= 0) { buf[len] = '\0'; return xstrdup(buf); } return NULL; } /* Custom version of copyfd_xyz, * one which is able to write into two descriptors at once. */ #define CONFIG_FEATURE_COPYBUF_KB 4 static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; //TODO: truncate to 0 or even delete the second file //(currently we delete the file later) } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } /* Global data */ static char *user_pwd; static char *proc_pid_status; static struct dump_dir *dd; static int user_core_fd = -1; /* * %s - signal number * %c - ulimit -c value * %p - pid * %u - uid * %g - gid * %t - UNIX time of dump * %e - executable filename * %h - hostname * %% - output one "%" */ /* Hook must be installed with exactly the same sequence of %c specifiers. * Last one, %h, may be omitted (we can find it out). */ static const char percent_specifiers[] = "%scpugteh"; static char *core_basename = (char*) "core"; /* * Used for error messages only. * It is either the same as core_basename if it is absolute, * or $PWD/core_basename. */ static char *full_core_basename; static char* get_executable(pid_t pid, int *fd_p) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); if (fd_p) *fd_p = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ char *executable = malloc_readlink(buf); if (!executable) return NULL; /* find and cut off " (deleted)" from the path */ char *deleted = executable + strlen(executable) - strlen(" (deleted)"); if (deleted > executable && strcmp(deleted, " (deleted)") == 0) { *deleted = '\0'; log("File '%s' seems to be deleted", executable); } /* find and cut off prelink suffixes from the path */ char *prelink = executable + strlen(executable) - strlen(".#prelink#.XXXXXX"); if (prelink > executable && strncmp(prelink, ".#prelink#.", strlen(".#prelink#.")) == 0) { log("File '%s' seems to be a prelink temporary file", executable); *prelink = '\0'; } return executable; } static char* get_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); return malloc_readlink(buf); } static char* get_rootdir(pid_t pid) { char buf[sizeof("/proc/%lu/root") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/root", (long)pid); return malloc_readlink(buf); } static int get_fsuid(void) { int real, euid, saved; /* if we fail to parse the uid, then make it root only readable to be safe */ int fs_uid = 0; char *line = proc_pid_status; /* never NULL */ for (;;) { if (strncmp(line, "Uid", 3) == 0) { int n = sscanf(line, "Uid:\t%d\t%d\t%d\t%d\n", &real, &euid, &saved, &fs_uid); if (n != 4) { perror_msg_and_die("Can't parse Uid: line"); } break; } line = strchr(line, '\n'); if (!line) break; line++; } return fs_uid; } static int dump_suid_policy() { /* - values are: 0 - don't dump suided programs - in this case the hook is not called by kernel 1 - create coredump readable by fs_uid 2 - create coredump readable by root only */ int c; int suid_dump_policy = 0; const char *filename = "/proc/sys/fs/suid_dumpable"; FILE *f = fopen(filename, "r"); if (!f) { log("Can't open %s", filename); return suid_dump_policy; } c = fgetc(f); fclose(f); if (c != EOF) suid_dump_policy = c - '0'; //log("suid dump policy is: %i", suid_dump_policy); return suid_dump_policy; } static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values) { errno = 0; if (user_pwd == NULL || chdir(user_pwd) != 0 ) { perror_msg("Can't cd to '%s'", user_pwd); return -1; } struct passwd* pw = getpwuid(uid); gid_t gid = pw ? pw->pw_gid : uid; //log("setting uid: %i gid: %i", uid, gid); xsetegid(gid); xseteuid(fsuid); if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } full_core_basename = core_basename; if (core_basename[0] != '/') core_basename = concat_path_file(user_pwd, core_basename); /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ struct stat sb; errno = 0; /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ int user_core_fd = open(core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW, 0600); /* kernel makes 0600 too */ xsetegid(0); xseteuid(0); if (user_core_fd < 0 || fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 /* kernel internal dumper checks this too: if (inode->i_uid != current->fsuid) <fail>, need to mimic? */ ) { if (user_core_fd < 0) perror_msg("Can't open '%s'", full_core_basename); else perror_msg("'%s' is not a regular file with link count 1", full_core_basename); return -1; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' to size 0", full_core_basename); unlink(core_basename); return -1; } return user_core_fd; } static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "wx"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; } /* Like xopen, but on error, unlocks and deletes dd and user core */ static int create_or_die(const char *filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, DEFAULT_DUMP_DIR_MODE); if (fd >= 0) { IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid)); return fd; } int sv_errno = errno; if (dd) dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } errno = sv_errno; perror_msg_and_die("Can't open '%s'", filename); } int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } #endif /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s'", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size); } return 0; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_1593_0
crossvul-cpp_data_good_436_1
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: pidfile utility. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include "logger.h" #include "pidfile.h" #include "main.h" #include "bitops.h" #include "utils.h" const char *pid_directory = PID_DIR PACKAGE; /* Create the directory for non-standard pid files */ void create_pid_dir(void) { if (mkdir(pid_directory, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) && errno != EEXIST) { log_message(LOG_INFO, "Unable to create directory %s", pid_directory); return; } } void remove_pid_dir(void) { if (rmdir(pid_directory) && errno != ENOTEMPTY && errno != EBUSY) log_message(LOG_INFO, "unlink of %s failed - error (%d) '%s'", pid_directory, errno, strerror(errno)); } /* Create the running daemon pidfile */ int pidfile_write(const char *pid_file, int pid) { FILE *pidfile = NULL; int pidfd = open(pid_file, O_NOFOLLOW | O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (pidfd != -1) pidfile = fdopen(pidfd, "w"); if (!pidfile) { log_message(LOG_INFO, "pidfile_write : Cannot open %s pidfile", pid_file); return 0; } fprintf(pidfile, "%d\n", pid); fclose(pidfile); return 1; } /* Remove the running daemon pidfile */ void pidfile_rm(const char *pid_file) { unlink(pid_file); } /* return the daemon running state */ static int process_running(const char *pid_file) { FILE *pidfile = fopen(pid_file, "r"); pid_t pid = 0; int ret; /* No pidfile */ if (!pidfile) return 0; ret = fscanf(pidfile, "%d", &pid); fclose(pidfile); if (ret != 1) { log_message(LOG_INFO, "Error reading pid file %s", pid_file); pid = 0; pidfile_rm(pid_file); } /* What should we return - we don't know if it is running or not. */ if (!pid) return 1; /* If no process is attached to pidfile, remove it */ if (kill(pid, 0)) { log_message(LOG_INFO, "Remove a zombie pid file %s", pid_file); pidfile_rm(pid_file); return 0; } return 1; } /* Return parent process daemon state */ bool keepalived_running(unsigned long mode) { if (process_running(main_pidfile)) return true; #ifdef _WITH_VRRP_ if (__test_bit(DAEMON_VRRP, &mode) && process_running(vrrp_pidfile)) return true; #endif #ifdef _WITH_LVS_ if (__test_bit(DAEMON_CHECKERS, &mode) && process_running(checkers_pidfile)) return true; #endif #ifdef _WITH_BFD_ if (__test_bit(DAEMON_BFD, &mode) && process_running(bfd_pidfile)) return true; #endif return false; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_1
crossvul-cpp_data_bad_436_2
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: SMTP WRAPPER connect to a specified smtp server and send mail * using the smtp protocol according to the RFC 821. A non blocking * timeouted connection is used to handle smtp protocol. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <errno.h> #include <unistd.h> #include <time.h> #include "smtp.h" #include "memory.h" #include "layer4.h" #include "logger.h" #include "utils.h" #if !HAVE_DECL_SOCK_CLOEXEC #include "old_socket.h" #endif #ifdef _WITH_LVS_ #include "check_api.h" #endif #ifdef THREAD_DUMP #include "scheduler.h" #endif #ifdef _SMTP_ALERT_DEBUG_ bool do_smtp_alert_debug; #endif /* SMTP FSM definition */ static int connection_error(thread_t *); static int connection_in_progress(thread_t *); static int connection_timeout(thread_t *); static int connection_success(thread_t *); static int helo_cmd(thread_t *); static int mail_cmd(thread_t *); static int rcpt_cmd(thread_t *); static int data_cmd(thread_t *); static int body_cmd(thread_t *); static int quit_cmd(thread_t *); static int connection_code(thread_t *, int); static int helo_code(thread_t *, int); static int mail_code(thread_t *, int); static int rcpt_code(thread_t *, int); static int data_code(thread_t *, int); static int body_code(thread_t *, int); static int quit_code(thread_t *, int); static int smtp_read_thread(thread_t *); static int smtp_send_thread(thread_t *); struct { int (*send) (thread_t *); int (*read) (thread_t *, int); } SMTP_FSM[SMTP_MAX_FSM_STATE] = { /* Stream Write Handlers | Stream Read handlers * *-------------------------------+--------------------------*/ {connection_error, NULL}, /* connect_error */ {connection_in_progress, NULL}, /* connect_in_progress */ {connection_timeout, NULL}, /* connect_timeout */ {connection_success, connection_code}, /* connect_success */ {helo_cmd, helo_code}, /* HELO */ {mail_cmd, mail_code}, /* MAIL */ {rcpt_cmd, rcpt_code}, /* RCPT */ {data_cmd, data_code}, /* DATA */ {body_cmd, body_code}, /* BODY */ {quit_cmd, quit_code} /* QUIT */ }; static void free_smtp_all(smtp_t * smtp) { FREE(smtp->buffer); FREE(smtp->subject); FREE(smtp->body); FREE(smtp->email_to); FREE(smtp); } static char * fetch_next_email(smtp_t * smtp) { return list_element(global_data->email, smtp->email_it); } /* layer4 connection handlers */ static int connection_error(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); log_message(LOG_INFO, "SMTP connection ERROR to %s." , FMT_SMTP_HOST()); free_smtp_all(smtp); return 0; } static int connection_timeout(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); log_message(LOG_INFO, "Timeout connecting SMTP server %s." , FMT_SMTP_HOST()); free_smtp_all(smtp); return 0; } static int connection_in_progress(thread_t * thread) { int status; DBG("SMTP connection to %s now IN_PROGRESS.", FMT_SMTP_HOST()); /* * Here we use the propriety of a union structure, * each element of the structure have the same value. */ status = tcp_socket_state(thread, connection_in_progress); if (status != connect_in_progress) SMTP_FSM_SEND(status, thread); return 0; } static int connection_success(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); log_message(LOG_INFO, "Remote SMTP server %s connected." , FMT_SMTP_HOST()); smtp->stage = connect_success; thread_add_read(thread->master, smtp_read_thread, smtp, smtp->fd, global_data->smtp_connection_to); return 0; } /* SMTP protocol handlers */ static int smtp_read_thread(thread_t * thread) { smtp_t *smtp; char *buffer; char *reply; ssize_t rcv_buffer_size; int status = -1; smtp = THREAD_ARG(thread); if (thread->type == THREAD_READ_TIMEOUT) { log_message(LOG_INFO, "Timeout reading data to remote SMTP server %s." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); return -1; } buffer = smtp->buffer; rcv_buffer_size = read(thread->u.fd, buffer + smtp->buflen, SMTP_BUFFER_LENGTH - smtp->buflen); if (rcv_buffer_size == -1) { if (errno == EAGAIN) goto end; log_message(LOG_INFO, "Error reading data from remote SMTP server %s." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); return 0; } else if (rcv_buffer_size == 0) { log_message(LOG_INFO, "Remote SMTP server %s has closed the connection." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); return 0; } /* received data overflow buffer size ? */ if (smtp->buflen >= SMTP_BUFFER_MAX) { log_message(LOG_INFO, "Received buffer from remote SMTP server %s" " overflow our get read buffer length." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); return 0; } else { smtp->buflen += (size_t)rcv_buffer_size; buffer[smtp->buflen] = 0; /* NULL terminate */ } end: /* parse the buffer, finding the last line of the response for the code */ reply = buffer; while (reply < buffer + smtp->buflen) { char *p; p = strstr(reply, "\r\n"); if (!p) { memmove(buffer, reply, smtp->buflen - (size_t)(reply - buffer)); smtp->buflen -= (size_t)(reply - buffer); buffer[smtp->buflen] = 0; thread_add_read(thread->master, smtp_read_thread, smtp, thread->u.fd, global_data->smtp_connection_to); return 0; } if (reply[3] == '-') { /* Skip over the \r\n */ reply = p + 2; continue; } status = ((reply[0] - '0') * 100) + ((reply[1] - '0') * 10) + (reply[2] - '0'); reply = p + 2; break; } memmove(buffer, reply, smtp->buflen - (size_t)(reply - buffer)); smtp->buflen -= (size_t)(reply - buffer); buffer[smtp->buflen] = 0; if (status == -1) { thread_add_read(thread->master, smtp_read_thread, smtp, thread->u.fd, global_data->smtp_connection_to); return 0; } SMTP_FSM_READ(smtp->stage, thread, status); /* Registering next smtp command processing thread */ if (smtp->stage != ERROR) { thread_add_write(thread->master, smtp_send_thread, smtp, smtp->fd, global_data->smtp_connection_to); } else { log_message(LOG_INFO, "Can not read data from remote SMTP server %s." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); } return 0; } static int smtp_send_thread(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); if (thread->type == THREAD_WRITE_TIMEOUT) { log_message(LOG_INFO, "Timeout sending data to remote SMTP server %s." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); return 0; } SMTP_FSM_SEND(smtp->stage, thread); /* Handle END command */ if (smtp->stage == END) { SMTP_FSM_READ(QUIT, thread, 0); return 0; } /* Registering next smtp command processing thread */ if (smtp->stage != ERROR) { thread_add_read(thread->master, smtp_read_thread, smtp, thread->u.fd, global_data->smtp_connection_to); thread_del_write(thread); } else { log_message(LOG_INFO, "Can not send data to remote SMTP server %s." , FMT_SMTP_HOST()); SMTP_FSM_READ(QUIT, thread, 0); } return 0; } static int connection_code(thread_t * thread, int status) { smtp_t *smtp = THREAD_ARG(thread); if (status == 220) { smtp->stage++; } else { log_message(LOG_INFO, "Error connecting SMTP server %s." " SMTP status code = %d" , FMT_SMTP_HOST() , status); smtp->stage = ERROR; } return 0; } /* HELO command processing */ static int helo_cmd(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); char *buffer; buffer = (char *) MALLOC(SMTP_BUFFER_MAX); snprintf(buffer, SMTP_BUFFER_MAX, SMTP_HELO_CMD, (global_data->smtp_helo_name) ? global_data->smtp_helo_name : "localhost"); if (send(thread->u.fd, buffer, strlen(buffer), 0) == -1) smtp->stage = ERROR; FREE(buffer); return 0; } static int helo_code(thread_t * thread, int status) { smtp_t *smtp = THREAD_ARG(thread); if (status == 250) { smtp->stage++; } else { log_message(LOG_INFO, "Error processing HELO cmd on SMTP server %s." " SMTP status code = %d" , FMT_SMTP_HOST() , status); smtp->stage = ERROR; } return 0; } /* MAIL command processing */ static int mail_cmd(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); char *buffer; buffer = (char *) MALLOC(SMTP_BUFFER_MAX); snprintf(buffer, SMTP_BUFFER_MAX, SMTP_MAIL_CMD, global_data->email_from); if (send(thread->u.fd, buffer, strlen(buffer), 0) == -1) smtp->stage = ERROR; FREE(buffer); return 0; } static int mail_code(thread_t * thread, int status) { smtp_t *smtp = THREAD_ARG(thread); if (status == 250) { smtp->stage++; } else { log_message(LOG_INFO, "Error processing MAIL cmd on SMTP server %s." " SMTP status code = %d" , FMT_SMTP_HOST() , status); smtp->stage = ERROR; } return 0; } /* RCPT command processing */ static int rcpt_cmd(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); char *buffer; char *fetched_email; buffer = (char *) MALLOC(SMTP_BUFFER_MAX); /* We send RCPT TO command multiple time to add all our email receivers. * --rfc821.3.1 */ fetched_email = fetch_next_email(smtp); snprintf(buffer, SMTP_BUFFER_MAX, SMTP_RCPT_CMD, fetched_email); if (send(thread->u.fd, buffer, strlen(buffer), 0) == -1) smtp->stage = ERROR; FREE(buffer); return 0; } static int rcpt_code(thread_t * thread, int status) { smtp_t *smtp = THREAD_ARG(thread); char *fetched_email; if (status == 250) { smtp->email_it++; fetched_email = fetch_next_email(smtp); if (!fetched_email) smtp->stage++; } else { log_message(LOG_INFO, "Error processing RCPT cmd on SMTP server %s." " SMTP status code = %d" , FMT_SMTP_HOST() , status); smtp->stage = ERROR; } return 0; } /* DATA command processing */ static int data_cmd(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); if (send(thread->u.fd, SMTP_DATA_CMD, strlen(SMTP_DATA_CMD), 0) == -1) smtp->stage = ERROR; return 0; } static int data_code(thread_t * thread, int status) { smtp_t *smtp = THREAD_ARG(thread); if (status == 354) { smtp->stage++; } else { log_message(LOG_INFO, "Error processing DATA cmd on SMTP server %s." " SMTP status code = %d" , FMT_SMTP_HOST() , status); smtp->stage = ERROR; } return 0; } /* BODY command processing. * Do we need to use mutli-thread for multi-part body * handling ? Don t really think :) */ static int body_cmd(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); char *buffer; char rfc822[80]; time_t now; struct tm *t; buffer = (char *) MALLOC(SMTP_BUFFER_MAX); time(&now); t = localtime(&now); strftime(rfc822, sizeof(rfc822), "%a, %d %b %Y %H:%M:%S %z", t); snprintf(buffer, SMTP_BUFFER_MAX, SMTP_HEADERS_CMD, rfc822, global_data->email_from, smtp->subject, smtp->email_to); /* send the subject field */ if (send(thread->u.fd, buffer, strlen(buffer), 0) == -1) smtp->stage = ERROR; memset(buffer, 0, SMTP_BUFFER_MAX); snprintf(buffer, SMTP_BUFFER_MAX, SMTP_BODY_CMD, smtp->body); /* send the the body field */ if (send(thread->u.fd, buffer, strlen(buffer), 0) == -1) smtp->stage = ERROR; /* send the sending dot */ if (send(thread->u.fd, SMTP_SEND_CMD, strlen(SMTP_SEND_CMD), 0) == -1) smtp->stage = ERROR; FREE(buffer); return 0; } static int body_code(thread_t * thread, int status) { smtp_t *smtp = THREAD_ARG(thread); if (status == 250) { log_message(LOG_INFO, "SMTP alert successfully sent."); smtp->stage++; } else { log_message(LOG_INFO, "Error processing DOT cmd on SMTP server %s." " SMTP status code = %d" , FMT_SMTP_HOST() , status); smtp->stage = ERROR; } return 0; } /* QUIT command processing */ static int quit_cmd(thread_t * thread) { smtp_t *smtp = THREAD_ARG(thread); if (send(thread->u.fd, SMTP_QUIT_CMD, strlen(SMTP_QUIT_CMD), 0) == -1) smtp->stage = ERROR; else smtp->stage++; return 0; } static int quit_code(thread_t * thread, __attribute__((unused)) int status) { smtp_t *smtp = THREAD_ARG(thread); /* final state, we are disconnected from the remote host */ free_smtp_all(smtp); thread_close_fd(thread); return 0; } /* connect remote SMTP server */ static void smtp_connect(smtp_t * smtp) { enum connect_result status; if ((smtp->fd = socket(global_data->smtp_server.ss_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, IPPROTO_TCP)) == -1) { DBG("SMTP connect fail to create socket."); free_smtp_all(smtp); return; } #if !HAVE_DECL_SOCK_NONBLOCK if (set_sock_flags(smtp->fd, F_SETFL, O_NONBLOCK)) log_message(LOG_INFO, "Unable to set NONBLOCK on smtp_connect socket - %s (%d)", strerror(errno), errno); #endif #if !HAVE_DECL_SOCK_CLOEXEC if (set_sock_flags(smtp->fd, F_SETFD, FD_CLOEXEC)) log_message(LOG_INFO, "Unable to set CLOEXEC on smtp_connect socket - %s (%d)", strerror(errno), errno); #endif status = tcp_connect(smtp->fd, &global_data->smtp_server); /* Handle connection status code */ thread_add_event(master, SMTP_FSM[status].send, smtp, smtp->fd); } #ifdef _SMTP_ALERT_DEBUG_ static void smtp_log_to_file(smtp_t *smtp) { FILE *fp = fopen("/tmp/smtp-alert.log", "a"); time_t now; struct tm tm; char time_buf[25]; int time_buf_len; time(&now); localtime_r(&now, &tm); time_buf_len = strftime(time_buf, sizeof time_buf, "%a %b %e %X %Y", &tm); fprintf(fp, "%s: %s -> %s\n" "%*sSubject: %s\n" "%*sBody: %s\n\n", time_buf, global_data->email_from, smtp->email_to, time_buf_len - 7, "", smtp->subject, time_buf_len - 7, "", smtp->body); fclose(fp); free_smtp_all(smtp); } #endif /* * Build a comma separated string of smtp recipient email addresses * for the email message To-header. */ static void build_to_header_rcpt_addrs(smtp_t *smtp) { char *fetched_email; char *email_to_addrs; size_t bytes_available = SMTP_BUFFER_MAX - 1; size_t bytes_to_write; if (smtp == NULL) return; email_to_addrs = smtp->email_to; smtp->email_it = 0; while (1) { fetched_email = fetch_next_email(smtp); if (fetched_email == NULL) break; bytes_to_write = strlen(fetched_email); if (!smtp->email_it) { if (bytes_available < bytes_to_write) break; } else { if (bytes_available < 2 + bytes_to_write) break; /* Prepend with a comma and space to all non-first email addresses */ *email_to_addrs++ = ','; *email_to_addrs++ = ' '; bytes_available -= 2; } if (snprintf(email_to_addrs, bytes_to_write + 1, "%s", fetched_email) != (int)bytes_to_write) { /* Inconsistent state, no choice but to break here and do nothing */ break; } email_to_addrs += bytes_to_write; bytes_available -= bytes_to_write; smtp->email_it++; } smtp->email_it = 0; } /* Main entry point */ void smtp_alert(smtp_msg_t msg_type, void* data, const char *subject, const char *body) { smtp_t *smtp; #ifdef _WITH_VRRP_ vrrp_t *vrrp; vrrp_sgroup_t *vgroup; #endif #ifdef _WITH_LVS_ checker_t *checker; virtual_server_t *vs; smtp_rs *rs_info; #endif /* Only send mail if email specified */ if (LIST_ISEMPTY(global_data->email) || !global_data->smtp_server.ss_family) return; /* allocate & initialize smtp argument data structure */ smtp = (smtp_t *) MALLOC(sizeof(smtp_t)); smtp->subject = (char *) MALLOC(MAX_HEADERS_LENGTH); smtp->body = (char *) MALLOC(MAX_BODY_LENGTH); smtp->buffer = (char *) MALLOC(SMTP_BUFFER_MAX); smtp->email_to = (char *) MALLOC(SMTP_BUFFER_MAX); /* format subject if rserver is specified */ #ifdef _WITH_LVS_ if (msg_type == SMTP_MSG_RS) { checker = (checker_t *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] Realserver %s of virtual server %s - %s", global_data->router_id, FMT_RS(checker->rs, checker->vs), FMT_VS(checker->vs), checker->rs->alive ? "UP" : "DOWN"); } else if (msg_type == SMTP_MSG_VS) { vs = (virtual_server_t *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] Virtualserver %s - %s", global_data->router_id, FMT_VS(vs), subject); } else if (msg_type == SMTP_MSG_RS_SHUT) { rs_info = (smtp_rs *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] Realserver %s of virtual server %s - %s", global_data->router_id, FMT_RS(rs_info->rs, rs_info->vs), FMT_VS(rs_info->vs), subject); } else #endif #ifdef _WITH_VRRP_ if (msg_type == SMTP_MSG_VRRP) { vrrp = (vrrp_t *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] VRRP Instance %s - %s", global_data->router_id, vrrp->iname, subject); } else if (msg_type == SMTP_MSG_VGROUP) { vgroup = (vrrp_sgroup_t *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] VRRP Group %s - %s", global_data->router_id, vgroup->gname, subject); } else #endif if (global_data->router_id) snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] %s" , global_data->router_id , subject); else snprintf(smtp->subject, MAX_HEADERS_LENGTH, "%s", subject); strncpy(smtp->body, body, MAX_BODY_LENGTH - 1); smtp->body[MAX_BODY_LENGTH - 1]= '\0'; build_to_header_rcpt_addrs(smtp); #ifdef _SMTP_ALERT_DEBUG_ if (do_smtp_alert_debug) smtp_log_to_file(smtp); else #endif smtp_connect(smtp); } #ifdef THREAD_DUMP void register_smtp_addresses(void) { register_thread_address("body_cmd", body_cmd); register_thread_address("connection_error", connection_error); register_thread_address("connection_in_progress", connection_in_progress); register_thread_address("connection_success", connection_success); register_thread_address("connection_timeout", connection_timeout); register_thread_address("data_cmd", data_cmd); register_thread_address("helo_cmd", helo_cmd); register_thread_address("mail_cmd", mail_cmd); register_thread_address("quit_cmd", quit_cmd); register_thread_address("rcpt_cmd", rcpt_cmd); register_thread_address("smtp_read_thread", smtp_read_thread); register_thread_address("smtp_send_thread", smtp_send_thread); } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_2
crossvul-cpp_data_good_1505_0
/* Copyright (C) 2010 ABRT team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "problem_api.h" #include "libabrt.h" /* Maximal length of backtrace. */ #define MAX_BACKTRACE_SIZE (1024*1024) /* Amount of data received from one client for a message before reporting error. */ #define MAX_MESSAGE_SIZE (4*MAX_BACKTRACE_SIZE) /* Maximal number of characters read from socket at once. */ #define INPUT_BUFFER_SIZE (8*1024) /* We exit after this many seconds */ #define TIMEOUT 10 /* Unix socket in ABRT daemon for creating new dump directories. Why to use socket for creating dump dirs? Security. When a Python script throws unexpected exception, ABRT handler catches it, running as a part of that broken Python application. The application is running with certain SELinux privileges, for example it can not execute other programs, or to create files in /var/cache or anything else required to properly fill a problem directory. Adding these privileges to every application would weaken the security. The most suitable solution is for the Python application to open a socket where ABRT daemon is listening, write all relevant data to that socket, and close it. ABRT daemon handles the rest. ** Protocol Initializing new dump: open /var/run/abrt.socket Providing dump data (hook writes to the socket): MANDATORY ITEMS: -> "PID=" number 0 - PID_MAX (/proc/sys/kernel/pid_max) \0 -> "EXECUTABLE=" string \0 -> "BACKTRACE=" string \0 -> "ANALYZER=" string \0 -> "BASENAME=" string (no slashes) \0 -> "REASON=" string \0 You can send more messages using the same KEY=value format. */ static unsigned total_bytes_read = 0; static uid_t client_uid = (uid_t)-1L; /* Remove dump dir */ static int delete_path(const char *dump_dir_name) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dump_dir_name)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dump_dir_name, g_settings_dump_location); return 400; /* Bad Request */ } if (!dir_has_correct_permissions(dump_dir_name)) { error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dump_dir_name); return 400; /* */ } int dir_fd = dd_openfd(dump_dir_name); if (dir_fd < 0) { perror_msg("Can't open problem directory '%s'", dump_dir_name); return 400; } if (!fdump_dir_accessible_by_uid(dir_fd, client_uid)) { close(dir_fd); if (errno == ENOTDIR) { error_msg("Path '%s' isn't problem directory", dump_dir_name); return 404; /* Not Found */ } error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dump_dir_name, (long)client_uid); return 403; /* Forbidden */ } struct dump_dir *dd = dd_fdopendir(dir_fd, dump_dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg("Failed to delete problem directory '%s'", dump_dir_name); dd_close(dd); return 400; } } return 0; /* success */ } static pid_t spawn_event_handler_child(const char *dump_dir_name, const char *event_name, int *fdp) { char *args[7]; args[0] = (char *) LIBEXEC_DIR"/abrt-handle-event"; /* Do not forward ASK_* messages to parent*/ args[1] = (char *) "-i"; args[2] = (char *) "-e"; args[3] = (char *) event_name; args[4] = (char *) "--"; args[5] = (char *) dump_dir_name; args[6] = NULL; int pipeout[2]; int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_QUIET | EXECFLG_ERR2OUT; VERB1 flags &= ~EXECFLG_QUIET; char *env_vec[2]; /* Intercept ASK_* messages in Client API -> don't wait for user response */ env_vec[0] = xstrdup("REPORT_CLIENT_NONINTERACTIVE=1"); env_vec[1] = NULL; pid_t child = fork_execv_on_steroids(flags, args, pipeout, env_vec, /*dir:*/ NULL, /*uid(unused):*/ 0); if (fdp) *fdp = pipeout[0]; return child; } static int run_post_create(const char *dirname) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dirname)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location); return 400; /* Bad Request */ } if (!dir_has_correct_permissions(dirname)) { error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname); return 400; /* */ } if (g_settings_privatereports) { struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY); const bool complete = dd && problem_dump_dir_is_complete(dd); dd_close(dd); if (complete) { error_msg("Problem directory '%s' has already been processed", dirname); return 403; } } int child_stdout_fd; int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd); char *dup_of_dir = NULL; struct strbuf *cmd_output = strbuf_new(); bool child_is_post_create = 1; /* else it is a notify child */ read_child_output: //log("Reading from event fd %d", child_stdout_fd); /* Read streamed data and split lines */ for (;;) { char buf[250]; /* usually we get one line, no need to have big buf */ errno = 0; int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1); if (r <= 0) break; buf[r] = '\0'; /* split lines in the current buffer */ char *raw = buf; char *newline; while ((newline = strchr(raw, '\n')) != NULL) { *newline = '\0'; strbuf_append_str(cmd_output, raw); char *msg = cmd_output->buf; /* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */ log("%s", msg); if (child_is_post_create && prefixcmp(msg, "DUP_OF_DIR: ") == 0 ) { free(dup_of_dir); dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: ")); } strbuf_clear(cmd_output); /* jump to next line */ raw = newline + 1; } /* beginning of next line. the line continues by next read */ strbuf_append_str(cmd_output, raw); } /* EOF/error */ /* Wait for child to actually exit, collect status */ int status = 0; if (safe_waitpid(child_pid, &status, 0) <= 0) /* should not happen */ perror_msg("waitpid(%d)", child_pid); /* If it was a "notify[-dup]" event, then we're done */ if (!child_is_post_create) goto ret; /* exit 0 means "this is a good, non-dup dir" */ /* exit with 1 + "DUP_OF_DIR: dir" string => dup */ if (status != 0) { if (WIFSIGNALED(status)) { log("'post-create' on '%s' killed by signal %d", dirname, WTERMSIG(status)); goto delete_bad_dir; } /* else: it is WIFEXITED(status) */ if (!dup_of_dir) { log("'post-create' on '%s' exited with %d", dirname, WEXITSTATUS(status)); goto delete_bad_dir; } } const char *work_dir = (dup_of_dir ? dup_of_dir : dirname); /* Load problem_data (from the *first dir* if this one is a dup) */ struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0); if (!dd) /* dd_opendir already emitted error msg */ goto delete_bad_dir; /* Update count */ char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT); unsigned long count = strtoul(count_str, NULL, 10); /* Don't increase crash count if we are working with newly uploaded * directory (remote crash) which already has its crash count set. */ if ((status != 0 && dup_of_dir) || count == 0) { count++; char new_count_str[sizeof(long)*3 + 2]; sprintf(new_count_str, "%lu", count); dd_save_text(dd, FILENAME_COUNT, new_count_str); /* This condition can be simplified to either * (status * != 0 && * dup_of_dir) or (count == 1). But the * chosen form is much more reliable and safe. We must not call * dd_opendir() to locked dd otherwise we go into a deadlock. */ if (strcmp(dd->dd_dirname, dirname) != 0) { /* Update the last occurrence file by the time file of the new problem */ struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY); char *last_ocr = NULL; if (new_dd) { /* TIME must exists in a valid dump directory but we don't want to die * due to broken duplicated dump directory */ last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME, DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT); dd_close(new_dd); } else { /* dd_opendir() already produced a message with good information about failure */ error_msg("Can't read the last occurrence file from the new dump directory."); } if (!last_ocr) { /* the new dump directory may lie in the dump location for some time */ log("Using current time for the last occurrence file which may be incorrect."); time_t t = time(NULL); last_ocr = xasprintf("%lu", (long)t); } dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr); free(last_ocr); } } /* Reset mode/uig/gid to correct values for all files created by event run */ dd_sanitize_mode_and_owner(dd); dd_close(dd); if (!dup_of_dir) log_notice("New problem directory %s, processing", work_dir); else { log_warning("Deleting problem directory %s (dup of %s)", strrchr(dirname, '/') + 1, strrchr(dup_of_dir, '/') + 1); delete_dump_dir(dirname); } /* Run "notify[-dup]" event */ int fd; child_pid = spawn_event_handler_child( work_dir, (dup_of_dir ? "notify-dup" : "notify"), &fd ); //log("Started notify, fd %d -> %d", fd, child_stdout_fd); xmove_fd(fd, child_stdout_fd); child_is_post_create = 0; strbuf_clear(cmd_output); free(dup_of_dir); dup_of_dir = NULL; goto read_child_output; delete_bad_dir: log_warning("Deleting problem directory '%s'", dirname); delete_dump_dir(dirname); ret: strbuf_free(cmd_output); free(dup_of_dir); close(child_stdout_fd); return 0; } /* Create a new problem directory from client session. * Caller must ensure that all fields in struct client * are properly filled. */ static int create_problem_dir(GHashTable *problem_info, unsigned pid) { /* Exit if free space is less than 1/4 of MaxCrashReportsSize */ if (g_settings_nMaxCrashReportsSize > 0) { if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) exit(1); } /* Create temp directory with the problem data. * This directory is renamed to final directory name after * all files have been stored into it. */ gchar *dir_basename = g_hash_table_lookup(problem_info, "basename"); if (!dir_basename) dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE); char *path = xasprintf("%s/%s-%s-%u.new", g_settings_dump_location, dir_basename, iso_date_string(NULL), pid); /* This item is useless, don't save it */ g_hash_table_remove(problem_info, "basename"); /* No need to check the path length, as all variables used are limited, * and dd_create() fails if the path is too long. */ struct dump_dir *dd = dd_create(path, g_settings_privatereports ? 0 : client_uid, DEFAULT_DUMP_DIR_MODE); if (!dd) { error_msg_and_die("Error creating problem directory '%s'", path); } dd_create_basic_files(dd, client_uid, NULL); dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE); if (!gpkey) { /* Obtain and save the command line. */ char *cmdline = get_cmdline(pid); if (cmdline) { dd_save_text(dd, FILENAME_CMDLINE, cmdline); free(cmdline); } } /* Store id of the user whose application crashed. */ char uid_str[sizeof(long) * 3 + 2]; sprintf(uid_str, "%lu", (long)client_uid); dd_save_text(dd, FILENAME_UID, uid_str); GHashTableIter iter; gpointer gpvalue; g_hash_table_iter_init(&iter, problem_info); while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue)) { dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue); } dd_close(dd); /* Not needing it anymore */ g_hash_table_destroy(problem_info); /* Move the completely created problem directory * to final directory. */ char *newpath = xstrndup(path, strlen(path) - strlen(".new")); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log_notice("Saved problem directory of pid %u to '%s'", pid, path); /* We let the peer know that problem dir was created successfully * _before_ we run potentially long-running post-create. */ printf("HTTP/1.1 201 Created\r\n\r\n"); fflush(NULL); close(STDOUT_FILENO); xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */ /* Trim old problem directories if necessary */ if (g_settings_nMaxCrashReportsSize > 0) { trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path); } run_post_create(path); /* free(path); */ exit(0); } static gboolean key_value_ok(gchar *key, gchar *value) { char *i; /* check key, it has to be valid filename and will end up in the * bugzilla */ for (i = key; *i != 0; i++) { if (!isalpha(*i) && (*i != '-') && (*i != '_') && (*i != ' ')) return FALSE; } /* check value of 'basename', it has to be valid non-hidden directory * name */ if (strcmp(key, "basename") == 0 || strcmp(key, FILENAME_TYPE) == 0 ) { if (!str_is_correct_filename(value)) { error_msg("Value of '%s' ('%s') is not a valid directory name", key, value); return FALSE; } } return TRUE; } /* Handles a message received from client over socket. */ static void process_message(GHashTable *problem_info, char *message) { gchar *key, *value; value = strchr(message, '='); if (value) { key = g_ascii_strdown(message, value - message); /* result is malloced */ //TODO: is it ok? it uses g_malloc, not malloc! value++; if (key_value_ok(key, value)) { if (strcmp(key, FILENAME_UID) == 0) { error_msg("Ignoring value of %s, will be determined later", FILENAME_UID); } else { g_hash_table_insert(problem_info, key, xstrdup(value)); /* Compat, delete when FILENAME_ANALYZER is replaced by FILENAME_TYPE: */ if (strcmp(key, FILENAME_TYPE) == 0) g_hash_table_insert(problem_info, xstrdup(FILENAME_ANALYZER), xstrdup(value)); /* Prevent freeing key later: */ key = NULL; } } else { /* should use error_msg_and_die() here? */ error_msg("Invalid key or value format: %s", message); } free(key); } else { /* should use error_msg_and_die() here? */ error_msg("Invalid message format: '%s'", message); } } static void die_if_data_is_missing(GHashTable *problem_info) { gboolean missing_data = FALSE; gchar **pstring; static const gchar *const needed[] = { FILENAME_TYPE, FILENAME_REASON, /* FILENAME_BACKTRACE, - ECC errors have no such elements */ /* FILENAME_EXECUTABLE, */ NULL }; for (pstring = (gchar**) needed; *pstring; pstring++) { if (!g_hash_table_lookup(problem_info, *pstring)) { error_msg("Element '%s' is missing", *pstring); missing_data = TRUE; } } if (missing_data) error_msg_and_die("Some data is missing, aborting"); } /* * Takes hash table, looks for key FILENAME_PID and tries to convert its value * to int. */ unsigned convert_pid(GHashTable *problem_info) { long ret; gchar *pid_str = (gchar *) g_hash_table_lookup(problem_info, FILENAME_PID); char *err_pos; if (!pid_str) error_msg_and_die("PID data is missing, aborting"); errno = 0; ret = strtol(pid_str, &err_pos, 10); if (errno || pid_str == err_pos || *err_pos != '\0' || ret > UINT_MAX || ret < 1) error_msg_and_die("Malformed or out-of-range PID number: '%s'", pid_str); return (unsigned) ret; } static int perform_http_xact(void) { /* use free instead of g_free so that we can use xstr* functions from * libreport/lib/xfuncs.c */ GHashTable *problem_info = g_hash_table_new_full(g_str_hash, g_str_equal, free, free); /* Read header */ char *body_start = NULL; char *messagebuf_data = NULL; unsigned messagebuf_len = 0; /* Loop until EOF/error/timeout/end_of_header */ while (1) { messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE); char *p = messagebuf_data + messagebuf_len; int rd = read(STDIN_FILENO, p, INPUT_BUFFER_SIZE); if (rd < 0) { if (errno == EINTR) /* SIGALRM? */ error_msg_and_die("Timed out"); perror_msg_and_die("read"); } if (rd == 0) break; log_debug("Received %u bytes of data", rd); messagebuf_len += rd; total_bytes_read += rd; if (total_bytes_read > MAX_MESSAGE_SIZE) error_msg_and_die("Message is too long, aborting"); /* Check whether we see end of header */ /* Note: we support both [\r]\n\r\n and \n\n */ char *past_end = messagebuf_data + messagebuf_len; if (p > messagebuf_data+1) p -= 2; /* start search from two last bytes in last read - they might be '\n\r' */ while (p < past_end) { p = memchr(p, '\n', past_end - p); if (!p) break; p++; if (p >= past_end) break; if (*p == '\n' || (*p == '\r' && p+1 < past_end && p[1] == '\n') ) { body_start = p + 1 + (*p == '\r'); *p = '\0'; goto found_end_of_header; } } } /* while (read) */ found_end_of_header: ; log_debug("Request: %s", messagebuf_data); /* Sanitize and analyze header. * Header now is in messagebuf_data, NUL terminated string, * with last empty line deleted (by placement of NUL). * \r\n are not (yet) converted to \n, multi-line headers also * not converted. */ /* First line must be "op<space>[http://host]/path<space>HTTP/n.n". * <space> is exactly one space char. */ if (prefixcmp(messagebuf_data, "DELETE ") == 0) { messagebuf_data += strlen("DELETE "); char *space = strchr(messagebuf_data, ' '); if (!space || prefixcmp(space+1, "HTTP/") != 0) return 400; /* Bad Request */ *space = '\0'; //decode_url(messagebuf_data); %20 => ' ' alarm(0); return delete_path(messagebuf_data); } /* We erroneously used "PUT /" to create new problems. * POST is the correct request in this case: * "PUT /" implies creation or replace of resource named "/"! * Delete PUT in 2014. */ if (prefixcmp(messagebuf_data, "PUT ") != 0 && prefixcmp(messagebuf_data, "POST ") != 0 ) { return 400; /* Bad Request */ } enum { CREATION_NOTIFICATION, CREATION_REQUEST, }; int url_type; char *url = skip_non_whitespace(messagebuf_data) + 1; /* skip "POST " */ if (prefixcmp(url, "/creation_notification ") == 0) url_type = CREATION_NOTIFICATION; else if (prefixcmp(url, "/ ") == 0) url_type = CREATION_REQUEST; else return 400; /* Bad Request */ /* Read body */ if (!body_start) { log_warning("Premature EOF detected, exiting"); return 400; /* Bad Request */ } messagebuf_len -= (body_start - messagebuf_data); memmove(messagebuf_data, body_start, messagebuf_len); log_debug("Body so far: %u bytes, '%s'", messagebuf_len, messagebuf_data); /* Loop until EOF/error/timeout */ while (1) { if (url_type == CREATION_REQUEST) { while (1) { unsigned len = strnlen(messagebuf_data, messagebuf_len); if (len >= messagebuf_len) break; /* messagebuf has at least one NUL - process the line */ process_message(problem_info, messagebuf_data); messagebuf_len -= (len + 1); memmove(messagebuf_data, messagebuf_data + len + 1, messagebuf_len); } } messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE + 1); int rd = read(STDIN_FILENO, messagebuf_data + messagebuf_len, INPUT_BUFFER_SIZE); if (rd < 0) { if (errno == EINTR) /* SIGALRM? */ error_msg_and_die("Timed out"); perror_msg_and_die("read"); } if (rd == 0) break; log_debug("Received %u bytes of data", rd); messagebuf_len += rd; total_bytes_read += rd; if (total_bytes_read > MAX_MESSAGE_SIZE) error_msg_and_die("Message is too long, aborting"); } /* Body received, EOF was seen. Don't let alarm to interrupt after this. */ alarm(0); int ret = 0; if (url_type == CREATION_NOTIFICATION) { if (client_uid != 0) { error_msg("UID=%ld is not authorized to trigger post-create processing", (long)client_uid); ret = 403; /* Forbidden */ goto out; } messagebuf_data[messagebuf_len] = '\0'; return run_post_create(messagebuf_data); } /* Save problem dir */ unsigned pid = convert_pid(problem_info); die_if_data_is_missing(problem_info); char *executable = g_hash_table_lookup(problem_info, FILENAME_EXECUTABLE); if (executable) { char *last_file = concat_path_file(g_settings_dump_location, "last-via-server"); int repeating_crash = check_recent_crash_file(last_file, executable); free(last_file); if (repeating_crash) /* Only pretend that we saved it */ goto out; /* ret is 0: "success" */ } #if 0 //TODO: /* At least it should generate local problem identifier UUID */ problem_data_add_basics(problem_info); //...the problem being that problem_info here is not a problem_data_t! #endif create_problem_dir(problem_info, pid); /* does not return */ out: g_hash_table_destroy(problem_info); return ret; /* Used as HTTP response code */ } static void dummy_handler(int sig_unused) {} int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [options]" ); enum { OPT_v = 1 << 0, OPT_u = 1 << 1, OPT_s = 1 << 2, OPT_p = 1 << 3, }; /* Keep enum above and order of options below in sync! */ struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_INTEGER('u', NULL, &client_uid, _("Use NUM as client uid")), OPT_BOOL( 's', NULL, NULL , _("Log to syslog")), OPT_BOOL( 'p', NULL, NULL , _("Add program names to log")), OPT_END() }; unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); export_abrt_envvars(opts & OPT_p); msg_prefix = xasprintf("%s[%u]", g_progname, getpid()); if (opts & OPT_s) { logmode = LOGMODE_JOURNAL; } /* Set up timeout handling */ /* Part 1 - need this to make SIGALRM interrupt syscalls * (as opposed to restarting them): I want read syscall to be interrupted */ struct sigaction sa; /* sa.sa_flags.SA_RESTART bit is clear: make signal interrupt syscalls */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = dummy_handler; /* pity, SIG_DFL won't do */ sigaction(SIGALRM, &sa, NULL); /* Part 2 - set the timeout per se */ alarm(TIMEOUT); if (client_uid == (uid_t)-1L) { /* Get uid of the connected client */ struct ucred cr; socklen_t crlen = sizeof(cr); if (0 != getsockopt(STDIN_FILENO, SOL_SOCKET, SO_PEERCRED, &cr, &crlen)) perror_msg_and_die("getsockopt(SO_PEERCRED)"); if (crlen != sizeof(cr)) error_msg_and_die("%s: bad crlen %d", "getsockopt(SO_PEERCRED)", (int)crlen); client_uid = cr.uid; } load_abrt_conf(); int r = perform_http_xact(); if (r == 0) r = 200; free_abrt_conf_data(); printf("HTTP/1.1 %u \r\n\r\n", r); return (r >= 400); /* Error if 400+ */ } #if 0 // TODO: example of SSLed connection #include <openssl/ssl.h> #include <openssl/err.h> if (flags & OPT_SSL) { /* load key and cert files */ SSL_CTX *ctx; SSL *ssl; ctx = init_ssl_context(); if (SSL_CTX_use_certificate_file(ctx, cert_path, SSL_FILETYPE_PEM) <= 0 || SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0 ) { ERR_print_errors_fp(stderr); error_msg_and_die("SSL certificates err\n"); } if (!SSL_CTX_check_private_key(ctx)) { error_msg_and_die("Private key does not match public key\n"); } (void)SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); //TODO more errors? ssl = SSL_new(ctx); SSL_set_fd(ssl, sockfd_in); //SSL_set_accept_state(ssl); if (SSL_accept(ssl) == 1) { //while whatever serve while (serve(ssl, flags)) continue; //TODO errors SSL_shutdown(ssl); } SSL_free(ssl); SSL_CTX_free(ctx); } else { while (serve(&sockfd_in, flags)) continue; } err = (flags & OPT_SSL) ? SSL_read(sock, buffer, READ_BUF-1): read(*(int*)sock, buffer, READ_BUF-1); if ( err < 0 ) { //TODO handle errno || SSL_get_error(ssl,err); break; } if ( err == 0 ) break; if (!head) { buffer[err] = '\0'; clean[i%2] = delete_cr(buffer); cut = g_strstr_len(buffer, -1, "\n\n"); if ( cut == NULL ) { g_string_append(headers, buffer); } else { g_string_append_len(headers, buffer, cut-buffer); } } /* end of header section? */ if ( !head && ( cut != NULL || (clean[(i+1)%2] && buffer[0]=='\n') ) ) { parse_head(&request, headers); head = TRUE; c_len = has_body(&request); if ( c_len ) { //if we want to read body some day - this will be the right place to begin //malloc body append rest of the (fixed) buffer at the beginning of a body //if clean buffer[1]; } else { break; } break; //because we don't support body yet } else if ( head == TRUE ) { /* body-reading stuff * read body, check content-len * save body to request */ break; } else { // count header size len += err; if ( len > READ_BUF-1 ) { //TODO header is too long break; } } i++; } g_string_free(headers, true); //because we allocated it rt = generate_response(&request, &response); /* write headers */ if ( flags & OPT_SSL ) { //TODO err err = SSL_write(sock, response.response_line, strlen(response.response_line)); err = SSL_write(sock, response.head->str , strlen(response.head->str)); err = SSL_write(sock, "\r\n", 2); } else { //TODO err err = write(*(int*)sock, response.response_line, strlen(response.response_line)); err = write(*(int*)sock, response.head->str , strlen(response.head->str)); err = write(*(int*)sock, "\r\n", 2); } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/good_1505_0
crossvul-cpp_data_good_3271_0
/** \ingroup rpmcli * \file lib/verify.c * Verify installed payload files from package metadata. */ #include "system.h" #include <errno.h> #if WITH_CAP #include <sys/capability.h> #endif #if WITH_ACL #include <acl/libacl.h> #endif #include <rpm/rpmcli.h> #include <rpm/header.h> #include <rpm/rpmlog.h> #include <rpm/rpmfi.h> #include <rpm/rpmts.h> #include <rpm/rpmdb.h> #include <rpm/rpmfileutil.h> #include "lib/misc.h" #include "lib/rpmchroot.h" #include "lib/rpmte_internal.h" /* rpmteProcess() */ #include "lib/rpmug.h" #include "debug.h" #define S_ISDEV(m) (S_ISBLK((m)) || S_ISCHR((m))) /* If cap_compare() (Linux extension) not available, do it the hard way */ #if WITH_CAP && !defined(HAVE_CAP_COMPARE) static int cap_compare(cap_t acap, cap_t bcap) { int rc = 0; size_t asize = cap_size(acap); size_t bsize = cap_size(bcap); if (asize != bsize) { rc = 1; } else { char *abuf = xcalloc(asize, sizeof(*abuf)); char *bbuf = xcalloc(bsize, sizeof(*bbuf)); cap_copy_ext(abuf, acap, asize); cap_copy_ext(bbuf, bcap, bsize); rc = memcmp(abuf, bbuf, asize); free(abuf); free(bbuf); } return rc; } #endif rpmVerifyAttrs rpmfilesVerify(rpmfiles fi, int ix, rpmVerifyAttrs omitMask) { rpm_mode_t fmode = rpmfilesFMode(fi, ix); rpmfileAttrs fileAttrs = rpmfilesFFlags(fi, ix); rpmVerifyAttrs flags = rpmfilesVFlags(fi, ix); const char * fn = rpmfilesFN(fi, ix); struct stat sb; rpmVerifyAttrs vfy = RPMVERIFY_NONE; /* * Check to see if the file was installed - if not pretend all is OK. */ switch (rpmfilesFState(fi, ix)) { case RPMFILE_STATE_NETSHARED: case RPMFILE_STATE_NOTINSTALLED: goto exit; break; case RPMFILE_STATE_REPLACED: /* For replaced files we can only verify if it exists at all */ flags = RPMVERIFY_LSTATFAIL; break; case RPMFILE_STATE_WRONGCOLOR: /* * Files with wrong color are supposed to share some attributes * with the actually installed file - verify what we can. */ flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_RDEV); break; case RPMFILE_STATE_NORMAL: /* File from a non-installed package, try to verify nevertheless */ case RPMFILE_STATE_MISSING: break; } if (fn == NULL || lstat(fn, &sb) != 0) { vfy |= RPMVERIFY_LSTATFAIL; goto exit; } /* If we expected a directory but got a symlink to one, follow the link */ if (S_ISDIR(fmode) && S_ISLNK(sb.st_mode)) { struct stat dsb; /* ...if it actually points to a directory */ if (stat(fn, &dsb) == 0 && S_ISDIR(dsb.st_mode)) { uid_t fuid; /* ...and is by a legit user, to match fsmVerify() behavior */ if (sb.st_uid == 0 || (rpmugUid(rpmfilesFUser(fi, ix), &fuid) == 0 && sb.st_uid == fuid)) { sb = dsb; /* struct assignment */ } } } /* Links have no mode, other types have no linkto */ if (S_ISLNK(sb.st_mode)) flags &= ~(RPMVERIFY_MODE); else flags &= ~(RPMVERIFY_LINKTO); /* Not all attributes of non-regular files can be verified */ if (!S_ISREG(sb.st_mode)) flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_CAPS); /* Content checks of %ghost files are meaningless. */ if (fileAttrs & RPMFILE_GHOST) flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_LINKTO); /* Don't verify any features in omitMask. */ flags &= ~(omitMask | RPMVERIFY_FAILURES); if (flags & RPMVERIFY_FILEDIGEST) { const unsigned char *digest; int algo; size_t diglen; /* XXX If --nomd5, then prelinked library sizes are not corrected. */ if ((digest = rpmfilesFDigest(fi, ix, &algo, &diglen))) { unsigned char fdigest[diglen]; rpm_loff_t fsize; if (rpmDoDigest(algo, fn, 0, fdigest, &fsize)) { vfy |= (RPMVERIFY_READFAIL|RPMVERIFY_FILEDIGEST); } else { sb.st_size = fsize; if (memcmp(fdigest, digest, diglen)) vfy |= RPMVERIFY_FILEDIGEST; } } else { vfy |= RPMVERIFY_FILEDIGEST; } } if (flags & RPMVERIFY_LINKTO) { char linkto[1024+1]; int size = 0; if ((size = readlink(fn, linkto, sizeof(linkto)-1)) == -1) vfy |= (RPMVERIFY_READLINKFAIL|RPMVERIFY_LINKTO); else { const char * flink = rpmfilesFLink(fi, ix); linkto[size] = '\0'; if (flink == NULL || !rstreq(linkto, flink)) vfy |= RPMVERIFY_LINKTO; } } if (flags & RPMVERIFY_FILESIZE) { if (sb.st_size != rpmfilesFSize(fi, ix)) vfy |= RPMVERIFY_FILESIZE; } if (flags & RPMVERIFY_MODE) { rpm_mode_t metamode = fmode; rpm_mode_t filemode; /* * Platforms (like AIX) where sizeof(rpm_mode_t) != sizeof(mode_t) * need the (rpm_mode_t) cast here. */ filemode = (rpm_mode_t)sb.st_mode; /* * Comparing the type of %ghost files is meaningless, but perms are OK. */ if (fileAttrs & RPMFILE_GHOST) { metamode &= ~0xf000; filemode &= ~0xf000; } if (metamode != filemode) vfy |= RPMVERIFY_MODE; #if WITH_ACL /* * For now, any non-default acl's on a file is a difference as rpm * cannot have set them. */ acl_t facl = acl_get_file(fn, ACL_TYPE_ACCESS); if (facl) { if (acl_equiv_mode(facl, NULL) == 1) { vfy |= RPMVERIFY_MODE; } acl_free(facl); } #endif } if (flags & RPMVERIFY_RDEV) { if (S_ISCHR(fmode) != S_ISCHR(sb.st_mode) || S_ISBLK(fmode) != S_ISBLK(sb.st_mode)) { vfy |= RPMVERIFY_RDEV; } else if (S_ISDEV(fmode) && S_ISDEV(sb.st_mode)) { rpm_rdev_t st_rdev = (sb.st_rdev & 0xffff); rpm_rdev_t frdev = (rpmfilesFRdev(fi, ix) & 0xffff); if (st_rdev != frdev) vfy |= RPMVERIFY_RDEV; } } #if WITH_CAP if (flags & RPMVERIFY_CAPS) { /* * Empty capability set ("=") is not exactly the same as no * capabilities at all but suffices for now... */ cap_t cap, fcap; cap = cap_from_text(rpmfilesFCaps(fi, ix)); if (!cap) { cap = cap_from_text("="); } fcap = cap_get_file(fn); if (!fcap) { fcap = cap_from_text("="); } if (cap_compare(cap, fcap) != 0) vfy |= RPMVERIFY_CAPS; cap_free(fcap); cap_free(cap); } #endif if ((flags & RPMVERIFY_MTIME) && (sb.st_mtime != rpmfilesFMtime(fi, ix))) { vfy |= RPMVERIFY_MTIME; } if (flags & RPMVERIFY_USER) { const char * name = rpmugUname(sb.st_uid); const char * fuser = rpmfilesFUser(fi, ix); uid_t uid; int namematch = 0; int idmatch = 0; if (name && fuser) namematch = rstreq(name, fuser); if (fuser && rpmugUid(fuser, &uid) == 0) idmatch = (uid == sb.st_uid); if (namematch != idmatch) { rpmlog(RPMLOG_WARNING, _("Duplicate username or UID for user %s\n"), fuser); } if (!(namematch || idmatch)) vfy |= RPMVERIFY_USER; } if (flags & RPMVERIFY_GROUP) { const char * name = rpmugGname(sb.st_gid); const char * fgroup = rpmfilesFGroup(fi, ix); gid_t gid; int namematch = 0; int idmatch = 0; if (name && fgroup) namematch = rstreq(name, fgroup); if (fgroup && rpmugGid(fgroup, &gid) == 0) idmatch = (gid == sb.st_gid); if (namematch != idmatch) { rpmlog(RPMLOG_WARNING, _("Duplicate groupname or GID for group %s\n"), fgroup); } if (!(namematch || idmatch)) vfy |= RPMVERIFY_GROUP; } exit: return vfy; } int rpmVerifyFile(const rpmts ts, const rpmfi fi, rpmVerifyAttrs * res, rpmVerifyAttrs omitMask) { rpmVerifyAttrs vfy = rpmfiVerify(fi, omitMask); if (res) *res = vfy; return (vfy & RPMVERIFY_LSTATFAIL) ? 1 : 0; } /** * Return exit code from running verify script from header. * @param ts transaction set * @param h header * @return 0 on success */ static int rpmVerifyScript(rpmts ts, Header h) { int rc = 0; if (headerIsEntry(h, RPMTAG_VERIFYSCRIPT)) { /* fake up a erasure transaction element */ rpmte p = rpmteNew(ts, h, TR_REMOVED, NULL, NULL); if (p != NULL) { rpmteSetHeader(p, h); rc = (rpmpsmRun(ts, p, PKG_VERIFY) != RPMRC_OK); /* clean up our fake transaction bits */ rpmteFree(p); } else { rc = RPMRC_FAIL; } } return rc; } #define unknown "?" #define _verify(_RPMVERIFY_F, _C, _pad) \ ((verifyResult & _RPMVERIFY_F) ? _C : _pad) #define _verifylink(_RPMVERIFY_F, _C, _pad) \ ((verifyResult & RPMVERIFY_READLINKFAIL) ? unknown : \ (verifyResult & _RPMVERIFY_F) ? _C : _pad) #define _verifyfile(_RPMVERIFY_F, _C, _pad) \ ((verifyResult & RPMVERIFY_READFAIL) ? unknown : \ (verifyResult & _RPMVERIFY_F) ? _C : _pad) char * rpmVerifyString(uint32_t verifyResult, const char *pad) { char *fmt = NULL; rasprintf(&fmt, "%s%s%s%s%s%s%s%s%s", _verify(RPMVERIFY_FILESIZE, "S", pad), _verify(RPMVERIFY_MODE, "M", pad), _verifyfile(RPMVERIFY_FILEDIGEST, "5", pad), _verify(RPMVERIFY_RDEV, "D", pad), _verifylink(RPMVERIFY_LINKTO, "L", pad), _verify(RPMVERIFY_USER, "U", pad), _verify(RPMVERIFY_GROUP, "G", pad), _verify(RPMVERIFY_MTIME, "T", pad), _verify(RPMVERIFY_CAPS, "P", pad)); return fmt; } #undef _verifyfile #undef _verifylink #undef _verify #undef aok #undef unknown char * rpmFFlagsString(uint32_t fflags, const char *pad) { char *fmt = NULL; rasprintf(&fmt, "%s%s%s%s%s%s%s%s", (fflags & RPMFILE_DOC) ? "d" : pad, (fflags & RPMFILE_CONFIG) ? "c" : pad, (fflags & RPMFILE_SPECFILE) ? "s" : pad, (fflags & RPMFILE_MISSINGOK) ? "m" : pad, (fflags & RPMFILE_NOREPLACE) ? "n" : pad, (fflags & RPMFILE_GHOST) ? "g" : pad, (fflags & RPMFILE_LICENSE) ? "l" : pad, (fflags & RPMFILE_README) ? "r" : pad); return fmt; } static const char * stateStr(rpmfileState fstate) { switch (fstate) { case RPMFILE_STATE_NORMAL: return NULL; case RPMFILE_STATE_NOTINSTALLED: return rpmIsVerbose() ? _("not installed") : NULL; case RPMFILE_STATE_NETSHARED: return rpmIsVerbose() ? _("net shared") : NULL; case RPMFILE_STATE_WRONGCOLOR: return rpmIsVerbose() ? _("wrong color") : NULL; case RPMFILE_STATE_REPLACED: return _("replaced"); case RPMFILE_STATE_MISSING: return _("no state"); } return _("unknown state"); } /** * Check file info from header against what's actually installed. * @param ts transaction set * @param h header to verify * @param omitMask bits to disable verify checks * @param skipAttr skip files with these attrs (eg %ghost) * @return 0 no problems, 1 problems found */ static int verifyHeader(rpmts ts, Header h, rpmVerifyAttrs omitMask, rpmfileAttrs skipAttrs) { rpmVerifyAttrs verifyResult = 0; rpmVerifyAttrs verifyAll = 0; /* assume no problems */ rpmfi fi = rpmfiNew(ts, h, RPMTAG_BASENAMES, RPMFI_FLAGS_VERIFY); if (fi == NULL) return 1; rpmfiInit(fi, 0); while (rpmfiNext(fi) >= 0) { rpmfileAttrs fileAttrs = rpmfiFFlags(fi); char *buf = NULL, *attrFormat; const char *fstate = NULL; char ac; /* Skip on attributes (eg from --noghost) */ if (skipAttrs & fileAttrs) continue; verifyResult = rpmfiVerify(fi, omitMask); /* Filter out timestamp differences of shared files */ if (verifyResult & RPMVERIFY_MTIME) { rpmdbMatchIterator mi; mi = rpmtsInitIterator(ts, RPMDBI_BASENAMES, rpmfiFN(fi), 0); if (rpmdbGetIteratorCount(mi) > 1) verifyResult &= ~RPMVERIFY_MTIME; rpmdbFreeIterator(mi); } /* State is only meaningful for installed packages */ if (headerGetInstance(h)) fstate = stateStr(rpmfiFState(fi)); attrFormat = rpmFFlagsString(fileAttrs, ""); ac = rstreq(attrFormat, "") ? ' ' : attrFormat[0]; if (verifyResult & RPMVERIFY_LSTATFAIL) { if (!(fileAttrs & (RPMFILE_MISSINGOK|RPMFILE_GHOST)) || rpmIsVerbose()) { rasprintf(&buf, _("missing %c %s"), ac, rpmfiFN(fi)); if ((verifyResult & RPMVERIFY_LSTATFAIL) != 0 && errno != ENOENT) { char *app; rasprintf(&app, " (%s)", strerror(errno)); rstrcat(&buf, app); free(app); } } } else if (verifyResult || fstate || rpmIsVerbose()) { char *verifyFormat = rpmVerifyString(verifyResult, "."); rasprintf(&buf, "%s %c %s", verifyFormat, ac, rpmfiFN(fi)); free(verifyFormat); } free(attrFormat); if (buf) { if (fstate) buf = rstrscat(&buf, " (", fstate, ")", NULL); rpmlog(RPMLOG_NOTICE, "%s\n", buf); buf = _free(buf); } verifyAll |= verifyResult; } rpmfiFree(fi); return (verifyAll != 0) ? 1 : 0; } /** * Check installed package dependencies for problems. * @param ts transaction set * @param h header * @return number of problems found (0 for no problems) */ static int verifyDependencies(rpmts ts, Header h) { rpmps ps; rpmte te; int rc; rpmtsEmpty(ts); (void) rpmtsAddInstallElement(ts, h, NULL, 0, NULL); (void) rpmtsCheck(ts); te = rpmtsElement(ts, 0); ps = rpmteProblems(te); rc = rpmpsNumProblems(ps); if (rc > 0) { rpmlog(RPMLOG_NOTICE, _("Unsatisfied dependencies for %s:\n"), rpmteNEVRA(te)); rpmpsi psi = rpmpsInitIterator(ps); rpmProblem p; while ((p = rpmpsiNext(psi)) != NULL) { char * ps = rpmProblemString(p); rpmlog(RPMLOG_NOTICE, "\t%s\n", ps); free(ps); } rpmpsFreeIterator(psi); } rpmpsFree(ps); rpmtsEmpty(ts); return rc; } int showVerifyPackage(QVA_t qva, rpmts ts, Header h) { rpmVerifyAttrs omitMask = ((qva->qva_flags & VERIFY_ATTRS) ^ VERIFY_ATTRS); int ec = 0; int rc; if (qva->qva_flags & VERIFY_DEPS) { if ((rc = verifyDependencies(ts, h)) != 0) ec = rc; } if (qva->qva_flags & VERIFY_FILES) { if ((rc = verifyHeader(ts, h, omitMask, qva->qva_fflags)) != 0) ec = rc; } if (qva->qva_flags & VERIFY_SCRIPT) { if ((rc = rpmVerifyScript(ts, h)) != 0) ec = rc; } return ec; } int rpmcliVerify(rpmts ts, QVA_t qva, char * const * argv) { rpmVSFlags vsflags, ovsflags; int ec = 0; FD_t scriptFd = fdDup(STDOUT_FILENO); /* * Open the DB + indices explicitly before possible chroot, * otherwises BDB is going to be unhappy... */ rpmtsOpenDB(ts, O_RDONLY); rpmdbOpenAll(rpmtsGetRdb(ts)); if (rpmChrootSet(rpmtsRootDir(ts)) || rpmChrootIn()) { ec = 1; goto exit; } if (qva->qva_showPackage == NULL) qva->qva_showPackage = showVerifyPackage; vsflags = rpmExpandNumeric("%{?_vsflags_verify}"); if (rpmcliQueryFlags & VERIFY_DIGEST) vsflags |= _RPMVSF_NODIGESTS; if (rpmcliQueryFlags & VERIFY_SIGNATURE) vsflags |= _RPMVSF_NOSIGNATURES; if (rpmcliQueryFlags & VERIFY_HDRCHK) vsflags |= RPMVSF_NOHDRCHK; vsflags &= ~RPMVSF_NEEDPAYLOAD; rpmtsSetScriptFd(ts, scriptFd); ovsflags = rpmtsSetVSFlags(ts, vsflags); ec = rpmcliArgIter(ts, qva, argv); rpmtsSetVSFlags(ts, ovsflags); rpmtsSetScriptFd(ts, NULL); if (qva->qva_showPackage == showVerifyPackage) qva->qva_showPackage = NULL; rpmtsEmpty(ts); if (rpmChrootOut() || rpmChrootSet(NULL)) ec = 1; exit: Fclose(scriptFd); return ec; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_3271_0
crossvul-cpp_data_good_4262_0
/* vips7 compat stub for vips_dzsave() * * 11/6/13 * - from im_vips2tiff() */ /* This file is part of VIPS. VIPS is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk */ /* Turn on IM_REGION_ADDR() range checks, don't delete intermediates. #define DEBUG */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /*HAVE_CONFIG_H*/ #include <vips/intl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <vips/vips.h> #include <vips/vips7compat.h> int im_vips2dz( IMAGE *in, const char *filename ) { char *p, *q; char name[FILENAME_MAX]; char mode[FILENAME_MAX]; char buf[FILENAME_MAX]; int i; VipsForeignDzLayout layout = VIPS_FOREIGN_DZ_LAYOUT_DZ; char *suffix = ".jpeg"; int overlap = 0; int tile_size = 256; VipsForeignDzDepth depth = VIPS_FOREIGN_DZ_DEPTH_ONEPIXEL; gboolean centre = FALSE; VipsAngle angle = VIPS_ANGLE_D0; /* We can't use im_filename_split() --- it assumes that we have a * filename with an extension before the ':', and filename here is * actually a dirname. * * Just split on the first ':'. */ im_strncpy( name, filename, FILENAME_MAX ); if( (p = strchr( name, ':' )) ) { *p = '\0'; im_strncpy( mode, p + 1, FILENAME_MAX ); } else strcpy( mode, "" ); strcpy( buf, mode ); p = &buf[0]; if( (q = im_getnextoption( &p )) ) { if( (i = vips_enum_from_nick( "im_vips2dz", VIPS_TYPE_FOREIGN_DZ_LAYOUT, q )) < 0 ) return( -1 ); layout = i; } if( (q = im_getnextoption( &p )) ) suffix = g_strdup( q ); if( (q = im_getnextoption( &p )) ) overlap = atoi( q ); if( (q = im_getnextoption( &p )) ) tile_size = atoi( q ); if( (q = im_getnextoption( &p )) ) { if( (i = vips_enum_from_nick( "im_vips2dz", VIPS_TYPE_FOREIGN_DZ_DEPTH, q )) < 0 ) return( -1 ); depth = i; } if( (q = im_getnextoption( &p )) ) { if( im_isprefix( "cen", q ) ) centre = TRUE; } if( (q = im_getnextoption( &p )) ) { if( (i = vips_enum_from_nick( "im_vips2dz", VIPS_TYPE_ANGLE, q )) < 0 ) return( -1 ); angle = i; } if( vips_dzsave( in, name, "layout", layout, "suffix", suffix, "overlap", overlap, "tile_size", tile_size, "depth", depth, "centre", centre, "angle", angle, NULL ) ) return( -1 ); return( 0 ); }
./CrossVul/dataset_final_sorted/CWE-908/c/good_4262_0
crossvul-cpp_data_bad_4262_0
/* vips7 compat stub for vips_dzsave() * * 11/6/13 * - from im_vips2tiff() */ /* This file is part of VIPS. VIPS is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk */ /* Turn on IM_REGION_ADDR() range checks, don't delete intermediates. #define DEBUG */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /*HAVE_CONFIG_H*/ #include <vips/intl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <vips/vips.h> #include <vips/vips7compat.h> int im_vips2dz( IMAGE *in, const char *filename ) { char *p, *q; char name[FILENAME_MAX]; char mode[FILENAME_MAX]; char buf[FILENAME_MAX]; int i; VipsForeignDzLayout layout = VIPS_FOREIGN_DZ_LAYOUT_DZ; char *suffix = ".jpeg"; int overlap = 0; int tile_size = 256; VipsForeignDzDepth depth = VIPS_FOREIGN_DZ_DEPTH_ONEPIXEL; gboolean centre = FALSE; VipsAngle angle = VIPS_ANGLE_D0; /* We can't use im_filename_split() --- it assumes that we have a * filename with an extension before the ':', and filename here is * actually a dirname. * * Just split on the first ':'. */ im_strncpy( name, filename, FILENAME_MAX ); if( (p = strchr( name, ':' )) ) { *p = '\0'; im_strncpy( mode, p + 1, FILENAME_MAX ); } strcpy( buf, mode ); p = &buf[0]; if( (q = im_getnextoption( &p )) ) { if( (i = vips_enum_from_nick( "im_vips2dz", VIPS_TYPE_FOREIGN_DZ_LAYOUT, q )) < 0 ) return( -1 ); layout = i; } if( (q = im_getnextoption( &p )) ) suffix = g_strdup( q ); if( (q = im_getnextoption( &p )) ) overlap = atoi( q ); if( (q = im_getnextoption( &p )) ) tile_size = atoi( q ); if( (q = im_getnextoption( &p )) ) { if( (i = vips_enum_from_nick( "im_vips2dz", VIPS_TYPE_FOREIGN_DZ_DEPTH, q )) < 0 ) return( -1 ); depth = i; } if( (q = im_getnextoption( &p )) ) { if( im_isprefix( "cen", q ) ) centre = TRUE; } if( (q = im_getnextoption( &p )) ) { if( (i = vips_enum_from_nick( "im_vips2dz", VIPS_TYPE_ANGLE, q )) < 0 ) return( -1 ); angle = i; } if( vips_dzsave( in, name, "layout", layout, "suffix", suffix, "overlap", overlap, "tile_size", tile_size, "depth", depth, "centre", centre, "angle", angle, NULL ) ) return( -1 ); return( 0 ); }
./CrossVul/dataset_final_sorted/CWE-908/c/bad_4262_0
crossvul-cpp_data_good_3196_1
// This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002, 2003 // Copyright Dirk Lemstra 2014-2015 // // Implementation of Exception and derived classes // #define MAGICKCORE_IMPLEMENTATION 1 #define MAGICK_PLUSPLUS_IMPLEMENTATION 1 #include "Magick++/Include.h" #include <string> #include <errno.h> #include <string.h> using namespace std; #include "Magick++/Exception.h" Magick::Exception::Exception(const std::string& what_) : std::exception(), _what(what_), _nested((Exception *) NULL) { } Magick::Exception::Exception(const std::string& what_, Exception* nested_) : std::exception(), _what(what_), _nested(nested_) { } Magick::Exception::Exception(const Magick::Exception& original_) : exception(original_), _what(original_._what), _nested((Exception *) NULL) { } Magick::Exception::~Exception() throw() { if (_nested != (Exception *) NULL) delete _nested; } Magick::Exception& Magick::Exception::operator=( const Magick::Exception& original_) { if (this != &original_) this->_what=original_._what; return(*this); } const char* Magick::Exception::what() const throw() { return(_what.c_str()); } const Magick::Exception* Magick::Exception::nested() const throw() { return(_nested); } void Magick::Exception::nested(Exception* nested_) throw() { _nested=nested_; } Magick::Error::Error(const std::string& what_) : Exception(what_) { } Magick::Error::Error(const std::string& what_,Exception *nested_) : Exception(what_,nested_) { } Magick::Error::~Error() throw() { } Magick::ErrorBlob::ErrorBlob(const std::string& what_) : Error(what_) { } Magick::ErrorBlob::ErrorBlob(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorBlob::~ErrorBlob() throw() { } Magick::ErrorCache::ErrorCache(const std::string& what_) : Error(what_) { } Magick::ErrorCache::ErrorCache(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorCache::~ErrorCache() throw() { } Magick::ErrorCoder::ErrorCoder(const std::string& what_) : Error(what_) { } Magick::ErrorCoder::ErrorCoder(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorCoder::~ErrorCoder() throw() { } Magick::ErrorConfigure::ErrorConfigure(const std::string& what_) : Error(what_) { } Magick::ErrorConfigure::ErrorConfigure(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorConfigure::~ErrorConfigure() throw() { } Magick::ErrorCorruptImage::ErrorCorruptImage(const std::string& what_) : Error(what_) { } Magick::ErrorCorruptImage::ErrorCorruptImage(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorCorruptImage::~ErrorCorruptImage() throw() { } Magick::ErrorDelegate::ErrorDelegate(const std::string& what_) : Error(what_) { } Magick::ErrorDelegate::ErrorDelegate(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorDelegate::~ErrorDelegate()throw() { } Magick::ErrorDraw::ErrorDraw(const std::string& what_) : Error(what_) { } Magick::ErrorDraw::ErrorDraw(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorDraw::~ErrorDraw() throw() { } Magick::ErrorFileOpen::ErrorFileOpen(const std::string& what_) : Error(what_) { } Magick::ErrorFileOpen::~ErrorFileOpen() throw() { } Magick::ErrorFileOpen::ErrorFileOpen(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorImage::ErrorImage(const std::string& what_) : Error(what_) { } Magick::ErrorImage::ErrorImage(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorImage::~ErrorImage() throw() { } Magick::ErrorMissingDelegate::ErrorMissingDelegate(const std::string& what_) : Error(what_) { } Magick::ErrorMissingDelegate::ErrorMissingDelegate(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorMissingDelegate::~ErrorMissingDelegate() throw () { } Magick::ErrorModule::ErrorModule(const std::string& what_) : Error(what_) { } Magick::ErrorModule::ErrorModule(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorModule::~ErrorModule() throw() { } Magick::ErrorMonitor::ErrorMonitor(const std::string& what_) : Error(what_) { } Magick::ErrorMonitor::ErrorMonitor(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorMonitor::~ErrorMonitor() throw() { } Magick::ErrorOption::ErrorOption(const std::string& what_) : Error(what_) { } Magick::ErrorOption::ErrorOption(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorOption::~ErrorOption() throw() { } Magick::ErrorPolicy::ErrorPolicy(const std::string& what_) : Error(what_) { } Magick::ErrorPolicy::ErrorPolicy(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorPolicy::~ErrorPolicy() throw() { } Magick::ErrorRegistry::ErrorRegistry(const std::string& what_) : Error(what_) { } Magick::ErrorRegistry::ErrorRegistry(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorRegistry::~ErrorRegistry() throw() { } Magick::ErrorResourceLimit::ErrorResourceLimit(const std::string& what_) : Error(what_) { } Magick::ErrorResourceLimit::ErrorResourceLimit(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorResourceLimit::~ErrorResourceLimit() throw() { } Magick::ErrorStream::ErrorStream(const std::string& what_) : Error(what_) { } Magick::ErrorStream::ErrorStream(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorStream::~ErrorStream() throw() { } Magick::ErrorType::ErrorType(const std::string& what_) : Error(what_) { } Magick::ErrorType::ErrorType(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorType::~ErrorType() throw() { } Magick::ErrorUndefined::ErrorUndefined(const std::string& what_) : Error(what_) { } Magick::ErrorUndefined::ErrorUndefined(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorUndefined::~ErrorUndefined() throw() { } Magick::ErrorXServer::ErrorXServer(const std::string& what_) : Error(what_) { } Magick::ErrorXServer::ErrorXServer(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorXServer::~ErrorXServer() throw () { } Magick::Warning::Warning(const std::string& what_) : Exception(what_) { } Magick::Warning::Warning(const std::string& what_,Exception *nested_) : Exception(what_,nested_) { } Magick::Warning::~Warning() throw() { } Magick::WarningBlob::WarningBlob(const std::string& what_) : Warning(what_) { } Magick::WarningBlob::WarningBlob(const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningBlob::~WarningBlob() throw() { } Magick::WarningCache::WarningCache(const std::string& what_) : Warning(what_) { } Magick::WarningCache::WarningCache(const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningCache::~WarningCache() throw() { } Magick::WarningCoder::WarningCoder(const std::string& what_) : Warning(what_) { } Magick::WarningCoder::WarningCoder(const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningCoder::~WarningCoder() throw() { } Magick::WarningConfigure::WarningConfigure(const std::string& what_) : Warning(what_) { } Magick::WarningConfigure::WarningConfigure(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningConfigure::~WarningConfigure() throw() { } Magick::WarningCorruptImage::WarningCorruptImage(const std::string& what_) : Warning(what_) { } Magick::WarningCorruptImage::WarningCorruptImage(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningCorruptImage::~WarningCorruptImage() throw() { } Magick::WarningDelegate::WarningDelegate(const std::string& what_) : Warning(what_) { } Magick::WarningDelegate::WarningDelegate(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningDelegate::~WarningDelegate() throw() { } Magick::WarningDraw::WarningDraw(const std::string& what_) : Warning(what_) { } Magick::WarningDraw::WarningDraw(const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningDraw::~WarningDraw() throw() { } Magick::WarningFileOpen::WarningFileOpen(const std::string& what_) : Warning(what_) { } Magick::WarningFileOpen::WarningFileOpen(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningFileOpen::~WarningFileOpen() throw() { } Magick::WarningImage::WarningImage(const std::string& what_) : Warning(what_) { } Magick::WarningImage::WarningImage(const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningImage::~WarningImage() throw() { } Magick::WarningMissingDelegate::WarningMissingDelegate( const std::string& what_) : Warning(what_) { } Magick::WarningMissingDelegate::WarningMissingDelegate( const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningMissingDelegate::~WarningMissingDelegate() throw() { } Magick::WarningModule::WarningModule(const std::string& what_) : Warning(what_) { } Magick::WarningModule::WarningModule(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningModule::~WarningModule() throw() { } Magick::WarningMonitor::WarningMonitor(const std::string& what_) : Warning(what_) { } Magick::WarningMonitor::WarningMonitor(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningMonitor::~WarningMonitor() throw() { } Magick::WarningOption::WarningOption(const std::string& what_) : Warning(what_) { } Magick::WarningOption::WarningOption(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningOption::~WarningOption() throw() { } Magick::WarningRegistry::WarningRegistry(const std::string& what_) : Warning(what_) { } Magick::WarningRegistry::WarningRegistry(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningRegistry::~WarningRegistry() throw() { } Magick::WarningPolicy::WarningPolicy(const std::string& what_) : Warning(what_) { } Magick::WarningPolicy::WarningPolicy(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningPolicy::~WarningPolicy() throw() { } Magick::WarningResourceLimit::WarningResourceLimit(const std::string& what_) : Warning(what_) { } Magick::WarningResourceLimit::WarningResourceLimit(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningResourceLimit::~WarningResourceLimit() throw() { } Magick::WarningStream::WarningStream(const std::string& what_) : Warning(what_) { } Magick::WarningStream::WarningStream(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningStream::~WarningStream() throw() { } Magick::WarningType::WarningType(const std::string& what_) : Warning(what_) { } Magick::WarningType::WarningType(const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningType::~WarningType() throw() { } Magick::WarningUndefined::WarningUndefined(const std::string& what_) : Warning(what_) { } Magick::WarningUndefined::WarningUndefined(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningUndefined::~WarningUndefined() throw() { } Magick::WarningXServer::WarningXServer(const std::string& what_) : Warning(what_) { } Magick::WarningXServer::WarningXServer(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningXServer::~WarningXServer() throw() { } std::string Magick::formatExceptionMessage(const MagickCore::ExceptionInfo *exception_) { // Format error message ImageMagick-style std::string message=GetClientName(); if (exception_->reason != (char *) NULL) { message+=std::string(": "); message+=std::string(exception_->reason); } if (exception_->description != (char *) NULL) message += " (" + std::string(exception_->description) + ")"; return(message); } Magick::Exception* Magick::createException(const MagickCore::ExceptionInfo *exception_) { std::string message=formatExceptionMessage(exception_); switch (exception_->severity) { case BlobError: case BlobFatalError: return new ErrorBlob(message); case BlobWarning: return new WarningBlob(message); case CacheError: case CacheFatalError: return new ErrorCache(message); case CacheWarning: return new WarningCache(message); case CoderError: case CoderFatalError: return new ErrorCoder(message); case CoderWarning: return new WarningCoder(message); case ConfigureError: case ConfigureFatalError: return new ErrorConfigure(message); case ConfigureWarning: return new WarningConfigure(message); case CorruptImageError: case CorruptImageFatalError: return new ErrorCorruptImage(message); case CorruptImageWarning: return new WarningCorruptImage(message); case DelegateError: case DelegateFatalError: return new ErrorDelegate(message); case DelegateWarning: return new WarningDelegate(message); case DrawError: case DrawFatalError: return new ErrorDraw(message); case DrawWarning: return new WarningDraw(message); case FileOpenError: case FileOpenFatalError: return new ErrorFileOpen(message); case FileOpenWarning: return new WarningFileOpen(message); case ImageError: case ImageFatalError: return new ErrorImage(message); case ImageWarning: return new WarningImage(message); case MissingDelegateError: case MissingDelegateFatalError: return new ErrorMissingDelegate(message); case MissingDelegateWarning: return new WarningMissingDelegate(message); case ModuleError: case ModuleFatalError: return new ErrorModule(message); case ModuleWarning: return new WarningModule(message); case MonitorError: case MonitorFatalError: return new ErrorMonitor(message); case MonitorWarning: return new WarningMonitor(message); case OptionError: case OptionFatalError: return new ErrorOption(message); case OptionWarning: return new WarningOption(message); case PolicyWarning: return new WarningPolicy(message); case PolicyError: case PolicyFatalError: return new ErrorPolicy(message); case RegistryError: case RegistryFatalError: return new ErrorRegistry(message); case RegistryWarning: return new WarningRegistry(message); case ResourceLimitError: case ResourceLimitFatalError: return new ErrorResourceLimit(message); case ResourceLimitWarning: return new WarningResourceLimit(message); case StreamError: case StreamFatalError: return new ErrorStream(message); case StreamWarning: return new WarningStream(message); case TypeError: case TypeFatalError: return new ErrorType(message); case TypeWarning: return new WarningType(message); case UndefinedException: default: return new ErrorUndefined(message); case XServerError: case XServerFatalError: return new ErrorXServer(message); case XServerWarning: return new WarningXServer(message); } } MagickPPExport void Magick::throwExceptionExplicit( const ExceptionType severity_,const char* reason_,const char* description_) { // Just return if there is no reported error if (severity_ == UndefinedException) return; GetPPException; ThrowException(exceptionInfo,severity_,reason_, description_); ThrowPPException(false); } MagickPPExport void Magick::throwException(ExceptionInfo *exception_, const bool quiet_) { const ExceptionInfo *p; Exception *nestedException, *q; ExceptionType severity; size_t index; // Just return if there is no reported error if (exception_->severity == UndefinedException) return; std::string message=formatExceptionMessage(exception_); nestedException=(Exception *) NULL; LockSemaphoreInfo(exception_->semaphore); if (exception_->exceptions != (void *) NULL) { index=GetNumberOfElementsInLinkedList((LinkedListInfo *) exception_->exceptions); while(index > 0) { p=(const ExceptionInfo *) GetValueFromLinkedList((LinkedListInfo *) exception_->exceptions,--index); if ((p->severity != exception_->severity) || (LocaleCompare(p->reason, exception_->reason) != 0) || (LocaleCompare(p->description, exception_->description) != 0)) { if (nestedException == (Exception *) NULL) { nestedException=createException(p); q=nestedException; } else { Exception *r; r=createException(p); q->nested(r); q=r; } } } } severity=exception_->severity; UnlockSemaphoreInfo(exception_->semaphore); if ((quiet_) && (severity < MagickCore::ErrorException)) { delete nestedException; return; } DestroyExceptionInfo(exception_); switch (severity) { case BlobError: case BlobFatalError: throw ErrorBlob(message,nestedException); case BlobWarning: throw WarningBlob(message,nestedException); case CacheError: case CacheFatalError: throw ErrorCache(message,nestedException); case CacheWarning: throw WarningCache(message,nestedException); case CoderError: case CoderFatalError: throw ErrorCoder(message,nestedException); case CoderWarning: throw WarningCoder(message,nestedException); case ConfigureError: case ConfigureFatalError: throw ErrorConfigure(message,nestedException); case ConfigureWarning: throw WarningConfigure(message,nestedException); case CorruptImageError: case CorruptImageFatalError: throw ErrorCorruptImage(message,nestedException); case CorruptImageWarning: throw WarningCorruptImage(message,nestedException); case DelegateError: case DelegateFatalError: throw ErrorDelegate(message,nestedException); case DelegateWarning: throw WarningDelegate(message,nestedException); case DrawError: case DrawFatalError: throw ErrorDraw(message,nestedException); case DrawWarning: throw WarningDraw(message,nestedException); case FileOpenError: case FileOpenFatalError: throw ErrorFileOpen(message,nestedException); case FileOpenWarning: throw WarningFileOpen(message,nestedException); case ImageError: case ImageFatalError: throw ErrorImage(message,nestedException); case ImageWarning: throw WarningImage(message,nestedException); case MissingDelegateError: case MissingDelegateFatalError: throw ErrorMissingDelegate(message,nestedException); case MissingDelegateWarning: throw WarningMissingDelegate(message,nestedException); case ModuleError: case ModuleFatalError: throw ErrorModule(message,nestedException); case ModuleWarning: throw WarningModule(message,nestedException); case MonitorError: case MonitorFatalError: throw ErrorMonitor(message,nestedException); case MonitorWarning: throw WarningMonitor(message,nestedException); case OptionError: case OptionFatalError: throw ErrorOption(message,nestedException); case OptionWarning: throw WarningOption(message,nestedException); case PolicyWarning: throw WarningPolicy(message,nestedException); case PolicyError: case PolicyFatalError: throw ErrorPolicy(message,nestedException); case RegistryError: case RegistryFatalError: throw ErrorRegistry(message,nestedException); case RegistryWarning: throw WarningRegistry(message,nestedException); case ResourceLimitError: case ResourceLimitFatalError: throw ErrorResourceLimit(message,nestedException); case ResourceLimitWarning: throw WarningResourceLimit(message,nestedException); case StreamError: case StreamFatalError: throw ErrorStream(message,nestedException); case StreamWarning: throw WarningStream(message,nestedException); case TypeError: case TypeFatalError: throw ErrorType(message,nestedException); case TypeWarning: throw WarningType(message,nestedException); case UndefinedException: default: throw ErrorUndefined(message,nestedException); case XServerError: case XServerFatalError: throw ErrorXServer(message,nestedException); case XServerWarning: throw WarningXServer(message,nestedException); } }
./CrossVul/dataset_final_sorted/CWE-772/cpp/good_3196_1
crossvul-cpp_data_bad_3196_1
// This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002, 2003 // Copyright Dirk Lemstra 2014-2015 // // Implementation of Exception and derived classes // #define MAGICKCORE_IMPLEMENTATION 1 #define MAGICK_PLUSPLUS_IMPLEMENTATION 1 #include "Magick++/Include.h" #include <string> #include <errno.h> #include <string.h> using namespace std; #include "Magick++/Exception.h" Magick::Exception::Exception(const std::string& what_) : std::exception(), _what(what_), _nested((Exception *) NULL) { } Magick::Exception::Exception(const std::string& what_, Exception* nested_) : std::exception(), _what(what_), _nested(nested_) { } Magick::Exception::Exception(const Magick::Exception& original_) : exception(original_), _what(original_._what), _nested((Exception *) NULL) { } Magick::Exception::~Exception() throw() { if (_nested != (Exception *) NULL) delete _nested; } Magick::Exception& Magick::Exception::operator=( const Magick::Exception& original_) { if (this != &original_) this->_what=original_._what; return(*this); } const char* Magick::Exception::what() const throw() { return(_what.c_str()); } const Magick::Exception* Magick::Exception::nested() const throw() { return(_nested); } void Magick::Exception::nested(Exception* nested_) throw() { _nested=nested_; } Magick::Error::Error(const std::string& what_) : Exception(what_) { } Magick::Error::Error(const std::string& what_,Exception *nested_) : Exception(what_,nested_) { } Magick::Error::~Error() throw() { } Magick::ErrorBlob::ErrorBlob(const std::string& what_) : Error(what_) { } Magick::ErrorBlob::ErrorBlob(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorBlob::~ErrorBlob() throw() { } Magick::ErrorCache::ErrorCache(const std::string& what_) : Error(what_) { } Magick::ErrorCache::ErrorCache(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorCache::~ErrorCache() throw() { } Magick::ErrorCoder::ErrorCoder(const std::string& what_) : Error(what_) { } Magick::ErrorCoder::ErrorCoder(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorCoder::~ErrorCoder() throw() { } Magick::ErrorConfigure::ErrorConfigure(const std::string& what_) : Error(what_) { } Magick::ErrorConfigure::ErrorConfigure(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorConfigure::~ErrorConfigure() throw() { } Magick::ErrorCorruptImage::ErrorCorruptImage(const std::string& what_) : Error(what_) { } Magick::ErrorCorruptImage::ErrorCorruptImage(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorCorruptImage::~ErrorCorruptImage() throw() { } Magick::ErrorDelegate::ErrorDelegate(const std::string& what_) : Error(what_) { } Magick::ErrorDelegate::ErrorDelegate(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorDelegate::~ErrorDelegate()throw() { } Magick::ErrorDraw::ErrorDraw(const std::string& what_) : Error(what_) { } Magick::ErrorDraw::ErrorDraw(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorDraw::~ErrorDraw() throw() { } Magick::ErrorFileOpen::ErrorFileOpen(const std::string& what_) : Error(what_) { } Magick::ErrorFileOpen::~ErrorFileOpen() throw() { } Magick::ErrorFileOpen::ErrorFileOpen(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorImage::ErrorImage(const std::string& what_) : Error(what_) { } Magick::ErrorImage::ErrorImage(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorImage::~ErrorImage() throw() { } Magick::ErrorMissingDelegate::ErrorMissingDelegate(const std::string& what_) : Error(what_) { } Magick::ErrorMissingDelegate::ErrorMissingDelegate(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorMissingDelegate::~ErrorMissingDelegate() throw () { } Magick::ErrorModule::ErrorModule(const std::string& what_) : Error(what_) { } Magick::ErrorModule::ErrorModule(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorModule::~ErrorModule() throw() { } Magick::ErrorMonitor::ErrorMonitor(const std::string& what_) : Error(what_) { } Magick::ErrorMonitor::ErrorMonitor(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorMonitor::~ErrorMonitor() throw() { } Magick::ErrorOption::ErrorOption(const std::string& what_) : Error(what_) { } Magick::ErrorOption::ErrorOption(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorOption::~ErrorOption() throw() { } Magick::ErrorPolicy::ErrorPolicy(const std::string& what_) : Error(what_) { } Magick::ErrorPolicy::ErrorPolicy(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorPolicy::~ErrorPolicy() throw() { } Magick::ErrorRegistry::ErrorRegistry(const std::string& what_) : Error(what_) { } Magick::ErrorRegistry::ErrorRegistry(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorRegistry::~ErrorRegistry() throw() { } Magick::ErrorResourceLimit::ErrorResourceLimit(const std::string& what_) : Error(what_) { } Magick::ErrorResourceLimit::ErrorResourceLimit(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorResourceLimit::~ErrorResourceLimit() throw() { } Magick::ErrorStream::ErrorStream(const std::string& what_) : Error(what_) { } Magick::ErrorStream::ErrorStream(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorStream::~ErrorStream() throw() { } Magick::ErrorType::ErrorType(const std::string& what_) : Error(what_) { } Magick::ErrorType::ErrorType(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorType::~ErrorType() throw() { } Magick::ErrorUndefined::ErrorUndefined(const std::string& what_) : Error(what_) { } Magick::ErrorUndefined::ErrorUndefined(const std::string& what_, Exception *nested_) : Error(what_,nested_) { } Magick::ErrorUndefined::~ErrorUndefined() throw() { } Magick::ErrorXServer::ErrorXServer(const std::string& what_) : Error(what_) { } Magick::ErrorXServer::ErrorXServer(const std::string& what_,Exception *nested_) : Error(what_,nested_) { } Magick::ErrorXServer::~ErrorXServer() throw () { } Magick::Warning::Warning(const std::string& what_) : Exception(what_) { } Magick::Warning::Warning(const std::string& what_,Exception *nested_) : Exception(what_,nested_) { } Magick::Warning::~Warning() throw() { } Magick::WarningBlob::WarningBlob(const std::string& what_) : Warning(what_) { } Magick::WarningBlob::WarningBlob(const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningBlob::~WarningBlob() throw() { } Magick::WarningCache::WarningCache(const std::string& what_) : Warning(what_) { } Magick::WarningCache::WarningCache(const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningCache::~WarningCache() throw() { } Magick::WarningCoder::WarningCoder(const std::string& what_) : Warning(what_) { } Magick::WarningCoder::WarningCoder(const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningCoder::~WarningCoder() throw() { } Magick::WarningConfigure::WarningConfigure(const std::string& what_) : Warning(what_) { } Magick::WarningConfigure::WarningConfigure(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningConfigure::~WarningConfigure() throw() { } Magick::WarningCorruptImage::WarningCorruptImage(const std::string& what_) : Warning(what_) { } Magick::WarningCorruptImage::WarningCorruptImage(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningCorruptImage::~WarningCorruptImage() throw() { } Magick::WarningDelegate::WarningDelegate(const std::string& what_) : Warning(what_) { } Magick::WarningDelegate::WarningDelegate(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningDelegate::~WarningDelegate() throw() { } Magick::WarningDraw::WarningDraw(const std::string& what_) : Warning(what_) { } Magick::WarningDraw::WarningDraw(const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningDraw::~WarningDraw() throw() { } Magick::WarningFileOpen::WarningFileOpen(const std::string& what_) : Warning(what_) { } Magick::WarningFileOpen::WarningFileOpen(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningFileOpen::~WarningFileOpen() throw() { } Magick::WarningImage::WarningImage(const std::string& what_) : Warning(what_) { } Magick::WarningImage::WarningImage(const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningImage::~WarningImage() throw() { } Magick::WarningMissingDelegate::WarningMissingDelegate( const std::string& what_) : Warning(what_) { } Magick::WarningMissingDelegate::WarningMissingDelegate( const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningMissingDelegate::~WarningMissingDelegate() throw() { } Magick::WarningModule::WarningModule(const std::string& what_) : Warning(what_) { } Magick::WarningModule::WarningModule(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningModule::~WarningModule() throw() { } Magick::WarningMonitor::WarningMonitor(const std::string& what_) : Warning(what_) { } Magick::WarningMonitor::WarningMonitor(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningMonitor::~WarningMonitor() throw() { } Magick::WarningOption::WarningOption(const std::string& what_) : Warning(what_) { } Magick::WarningOption::WarningOption(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningOption::~WarningOption() throw() { } Magick::WarningRegistry::WarningRegistry(const std::string& what_) : Warning(what_) { } Magick::WarningRegistry::WarningRegistry(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningRegistry::~WarningRegistry() throw() { } Magick::WarningPolicy::WarningPolicy(const std::string& what_) : Warning(what_) { } Magick::WarningPolicy::WarningPolicy(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningPolicy::~WarningPolicy() throw() { } Magick::WarningResourceLimit::WarningResourceLimit(const std::string& what_) : Warning(what_) { } Magick::WarningResourceLimit::WarningResourceLimit(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningResourceLimit::~WarningResourceLimit() throw() { } Magick::WarningStream::WarningStream(const std::string& what_) : Warning(what_) { } Magick::WarningStream::WarningStream(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningStream::~WarningStream() throw() { } Magick::WarningType::WarningType(const std::string& what_) : Warning(what_) { } Magick::WarningType::WarningType(const std::string& what_,Exception *nested_) : Warning(what_,nested_) { } Magick::WarningType::~WarningType() throw() { } Magick::WarningUndefined::WarningUndefined(const std::string& what_) : Warning(what_) { } Magick::WarningUndefined::WarningUndefined(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningUndefined::~WarningUndefined() throw() { } Magick::WarningXServer::WarningXServer(const std::string& what_) : Warning(what_) { } Magick::WarningXServer::WarningXServer(const std::string& what_, Exception *nested_) : Warning(what_,nested_) { } Magick::WarningXServer::~WarningXServer() throw() { } std::string Magick::formatExceptionMessage(const MagickCore::ExceptionInfo *exception_) { // Format error message ImageMagick-style std::string message=GetClientName(); if (exception_->reason != (char *) NULL) { message+=std::string(": "); message+=std::string(exception_->reason); } if (exception_->description != (char *) NULL) message += " (" + std::string(exception_->description) + ")"; return(message); } Magick::Exception* Magick::createException(const MagickCore::ExceptionInfo *exception_) { std::string message=formatExceptionMessage(exception_); switch (exception_->severity) { case BlobError: case BlobFatalError: return new ErrorBlob(message); case BlobWarning: return new WarningBlob(message); case CacheError: case CacheFatalError: return new ErrorCache(message); case CacheWarning: return new WarningCache(message); case CoderError: case CoderFatalError: return new ErrorCoder(message); case CoderWarning: return new WarningCoder(message); case ConfigureError: case ConfigureFatalError: return new ErrorConfigure(message); case ConfigureWarning: return new WarningConfigure(message); case CorruptImageError: case CorruptImageFatalError: return new ErrorCorruptImage(message); case CorruptImageWarning: return new WarningCorruptImage(message); case DelegateError: case DelegateFatalError: return new ErrorDelegate(message); case DelegateWarning: return new WarningDelegate(message); case DrawError: case DrawFatalError: return new ErrorDraw(message); case DrawWarning: return new WarningDraw(message); case FileOpenError: case FileOpenFatalError: return new ErrorFileOpen(message); case FileOpenWarning: return new WarningFileOpen(message); case ImageError: case ImageFatalError: return new ErrorImage(message); case ImageWarning: return new WarningImage(message); case MissingDelegateError: case MissingDelegateFatalError: return new ErrorMissingDelegate(message); case MissingDelegateWarning: return new WarningMissingDelegate(message); case ModuleError: case ModuleFatalError: return new ErrorModule(message); case ModuleWarning: return new WarningModule(message); case MonitorError: case MonitorFatalError: return new ErrorMonitor(message); case MonitorWarning: return new WarningMonitor(message); case OptionError: case OptionFatalError: return new ErrorOption(message); case OptionWarning: return new WarningOption(message); case PolicyWarning: return new WarningPolicy(message); case PolicyError: case PolicyFatalError: return new ErrorPolicy(message); case RegistryError: case RegistryFatalError: return new ErrorRegistry(message); case RegistryWarning: return new WarningRegistry(message); case ResourceLimitError: case ResourceLimitFatalError: return new ErrorResourceLimit(message); case ResourceLimitWarning: return new WarningResourceLimit(message); case StreamError: case StreamFatalError: return new ErrorStream(message); case StreamWarning: return new WarningStream(message); case TypeError: case TypeFatalError: return new ErrorType(message); case TypeWarning: return new WarningType(message); case UndefinedException: default: return new ErrorUndefined(message); case XServerError: case XServerFatalError: return new ErrorXServer(message); case XServerWarning: return new WarningXServer(message); } } MagickPPExport void Magick::throwExceptionExplicit( const ExceptionType severity_,const char* reason_,const char* description_) { // Just return if there is no reported error if (severity_ == UndefinedException) return; GetPPException; ThrowException(exceptionInfo,severity_,reason_, description_); ThrowPPException(false); } MagickPPExport void Magick::throwException(ExceptionInfo *exception_, const bool quiet_) { const ExceptionInfo *p; Exception *nestedException, *q; ExceptionType severity; size_t index; // Just return if there is no reported error if (exception_->severity == UndefinedException) return; std::string message=formatExceptionMessage(exception_); nestedException=(Exception *) NULL; LockSemaphoreInfo(exception_->semaphore); if (exception_->exceptions != (void *) NULL) { index=GetNumberOfElementsInLinkedList((LinkedListInfo *) exception_->exceptions); while(index > 0) { p=(const ExceptionInfo *) GetValueFromLinkedList((LinkedListInfo *) exception_->exceptions,--index); if ((p->severity != exception_->severity) || (LocaleCompare(p->reason, exception_->reason) != 0) || (LocaleCompare(p->description, exception_->description) != 0)) { if (nestedException == (Exception *) NULL) nestedException=createException(p); else { q=createException(p); nestedException->nested(q); nestedException=q; } } } } severity=exception_->severity; UnlockSemaphoreInfo(exception_->semaphore); if ((quiet_) && (severity < MagickCore::ErrorException)) { delete nestedException; return; } DestroyExceptionInfo(exception_); switch (severity) { case BlobError: case BlobFatalError: throw ErrorBlob(message,nestedException); case BlobWarning: throw WarningBlob(message,nestedException); case CacheError: case CacheFatalError: throw ErrorCache(message,nestedException); case CacheWarning: throw WarningCache(message,nestedException); case CoderError: case CoderFatalError: throw ErrorCoder(message,nestedException); case CoderWarning: throw WarningCoder(message,nestedException); case ConfigureError: case ConfigureFatalError: throw ErrorConfigure(message,nestedException); case ConfigureWarning: throw WarningConfigure(message,nestedException); case CorruptImageError: case CorruptImageFatalError: throw ErrorCorruptImage(message,nestedException); case CorruptImageWarning: throw WarningCorruptImage(message,nestedException); case DelegateError: case DelegateFatalError: throw ErrorDelegate(message,nestedException); case DelegateWarning: throw WarningDelegate(message,nestedException); case DrawError: case DrawFatalError: throw ErrorDraw(message,nestedException); case DrawWarning: throw WarningDraw(message,nestedException); case FileOpenError: case FileOpenFatalError: throw ErrorFileOpen(message,nestedException); case FileOpenWarning: throw WarningFileOpen(message,nestedException); case ImageError: case ImageFatalError: throw ErrorImage(message,nestedException); case ImageWarning: throw WarningImage(message,nestedException); case MissingDelegateError: case MissingDelegateFatalError: throw ErrorMissingDelegate(message,nestedException); case MissingDelegateWarning: throw WarningMissingDelegate(message,nestedException); case ModuleError: case ModuleFatalError: throw ErrorModule(message,nestedException); case ModuleWarning: throw WarningModule(message,nestedException); case MonitorError: case MonitorFatalError: throw ErrorMonitor(message,nestedException); case MonitorWarning: throw WarningMonitor(message,nestedException); case OptionError: case OptionFatalError: throw ErrorOption(message,nestedException); case OptionWarning: throw WarningOption(message,nestedException); case PolicyWarning: throw WarningPolicy(message,nestedException); case PolicyError: case PolicyFatalError: throw ErrorPolicy(message,nestedException); case RegistryError: case RegistryFatalError: throw ErrorRegistry(message,nestedException); case RegistryWarning: throw WarningRegistry(message,nestedException); case ResourceLimitError: case ResourceLimitFatalError: throw ErrorResourceLimit(message,nestedException); case ResourceLimitWarning: throw WarningResourceLimit(message,nestedException); case StreamError: case StreamFatalError: throw ErrorStream(message,nestedException); case StreamWarning: throw WarningStream(message,nestedException); case TypeError: case TypeFatalError: throw ErrorType(message,nestedException); case TypeWarning: throw WarningType(message,nestedException); case UndefinedException: default: throw ErrorUndefined(message,nestedException); case XServerError: case XServerFatalError: throw ErrorXServer(message,nestedException); case XServerWarning: throw WarningXServer(message,nestedException); } }
./CrossVul/dataset_final_sorted/CWE-772/cpp/bad_3196_1
crossvul-cpp_data_bad_2619_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP IIIII CCCC TTTTT % % P P I C T % % PPPP I C T % % P I C T % % P IIIII CCCC T % % % % % % Read/Write Apple Macintosh QuickDraw/PICT Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/constitute.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/transform.h" #include "magick/utility.h" /* ImageMagick Macintosh PICT Methods. */ #define ReadPixmap(pixmap) \ { \ pixmap.version=(short) ReadBlobMSBShort(image); \ pixmap.pack_type=(short) ReadBlobMSBShort(image); \ pixmap.pack_size=ReadBlobMSBLong(image); \ pixmap.horizontal_resolution=1UL*ReadBlobMSBShort(image); \ (void) ReadBlobMSBShort(image); \ pixmap.vertical_resolution=1UL*ReadBlobMSBShort(image); \ (void) ReadBlobMSBShort(image); \ pixmap.pixel_type=(short) ReadBlobMSBShort(image); \ pixmap.bits_per_pixel=(short) ReadBlobMSBShort(image); \ pixmap.component_count=(short) ReadBlobMSBShort(image); \ pixmap.component_size=(short) ReadBlobMSBShort(image); \ pixmap.plane_bytes=ReadBlobMSBLong(image); \ pixmap.table=ReadBlobMSBLong(image); \ pixmap.reserved=ReadBlobMSBLong(image); \ if ((EOFBlob(image) != MagickFalse) || (pixmap.bits_per_pixel <= 0) || \ (pixmap.bits_per_pixel > 32) || (pixmap.component_count <= 0) || \ (pixmap.component_count > 4) || (pixmap.component_size <= 0)) \ ThrowReaderException(CorruptImageError,"ImproperImageHeader"); \ } typedef struct _PICTCode { const char *name; ssize_t length; const char *description; } PICTCode; typedef struct _PICTPixmap { short version, pack_type; size_t pack_size, horizontal_resolution, vertical_resolution; short pixel_type, bits_per_pixel, component_count, component_size; size_t plane_bytes, table, reserved; } PICTPixmap; typedef struct _PICTRectangle { short top, left, bottom, right; } PICTRectangle; static const PICTCode codes[] = { /* 0x00 */ { "NOP", 0, "nop" }, /* 0x01 */ { "Clip", 0, "clip" }, /* 0x02 */ { "BkPat", 8, "background pattern" }, /* 0x03 */ { "TxFont", 2, "text font (word)" }, /* 0x04 */ { "TxFace", 1, "text face (byte)" }, /* 0x05 */ { "TxMode", 2, "text mode (word)" }, /* 0x06 */ { "SpExtra", 4, "space extra (fixed point)" }, /* 0x07 */ { "PnSize", 4, "pen size (point)" }, /* 0x08 */ { "PnMode", 2, "pen mode (word)" }, /* 0x09 */ { "PnPat", 8, "pen pattern" }, /* 0x0a */ { "FillPat", 8, "fill pattern" }, /* 0x0b */ { "OvSize", 4, "oval size (point)" }, /* 0x0c */ { "Origin", 4, "dh, dv (word)" }, /* 0x0d */ { "TxSize", 2, "text size (word)" }, /* 0x0e */ { "FgColor", 4, "foreground color (ssize_tword)" }, /* 0x0f */ { "BkColor", 4, "background color (ssize_tword)" }, /* 0x10 */ { "TxRatio", 8, "numerator (point), denominator (point)" }, /* 0x11 */ { "Version", 1, "version (byte)" }, /* 0x12 */ { "BkPixPat", 0, "color background pattern" }, /* 0x13 */ { "PnPixPat", 0, "color pen pattern" }, /* 0x14 */ { "FillPixPat", 0, "color fill pattern" }, /* 0x15 */ { "PnLocHFrac", 2, "fractional pen position" }, /* 0x16 */ { "ChExtra", 2, "extra for each character" }, /* 0x17 */ { "reserved", 0, "reserved for Apple use" }, /* 0x18 */ { "reserved", 0, "reserved for Apple use" }, /* 0x19 */ { "reserved", 0, "reserved for Apple use" }, /* 0x1a */ { "RGBFgCol", 6, "RGB foreColor" }, /* 0x1b */ { "RGBBkCol", 6, "RGB backColor" }, /* 0x1c */ { "HiliteMode", 0, "hilite mode flag" }, /* 0x1d */ { "HiliteColor", 6, "RGB hilite color" }, /* 0x1e */ { "DefHilite", 0, "Use default hilite color" }, /* 0x1f */ { "OpColor", 6, "RGB OpColor for arithmetic modes" }, /* 0x20 */ { "Line", 8, "pnLoc (point), newPt (point)" }, /* 0x21 */ { "LineFrom", 4, "newPt (point)" }, /* 0x22 */ { "ShortLine", 6, "pnLoc (point, dh, dv (-128 .. 127))" }, /* 0x23 */ { "ShortLineFrom", 2, "dh, dv (-128 .. 127)" }, /* 0x24 */ { "reserved", -1, "reserved for Apple use" }, /* 0x25 */ { "reserved", -1, "reserved for Apple use" }, /* 0x26 */ { "reserved", -1, "reserved for Apple use" }, /* 0x27 */ { "reserved", -1, "reserved for Apple use" }, /* 0x28 */ { "LongText", 0, "txLoc (point), count (0..255), text" }, /* 0x29 */ { "DHText", 0, "dh (0..255), count (0..255), text" }, /* 0x2a */ { "DVText", 0, "dv (0..255), count (0..255), text" }, /* 0x2b */ { "DHDVText", 0, "dh, dv (0..255), count (0..255), text" }, /* 0x2c */ { "reserved", -1, "reserved for Apple use" }, /* 0x2d */ { "reserved", -1, "reserved for Apple use" }, /* 0x2e */ { "reserved", -1, "reserved for Apple use" }, /* 0x2f */ { "reserved", -1, "reserved for Apple use" }, /* 0x30 */ { "frameRect", 8, "rect" }, /* 0x31 */ { "paintRect", 8, "rect" }, /* 0x32 */ { "eraseRect", 8, "rect" }, /* 0x33 */ { "invertRect", 8, "rect" }, /* 0x34 */ { "fillRect", 8, "rect" }, /* 0x35 */ { "reserved", 8, "reserved for Apple use" }, /* 0x36 */ { "reserved", 8, "reserved for Apple use" }, /* 0x37 */ { "reserved", 8, "reserved for Apple use" }, /* 0x38 */ { "frameSameRect", 0, "rect" }, /* 0x39 */ { "paintSameRect", 0, "rect" }, /* 0x3a */ { "eraseSameRect", 0, "rect" }, /* 0x3b */ { "invertSameRect", 0, "rect" }, /* 0x3c */ { "fillSameRect", 0, "rect" }, /* 0x3d */ { "reserved", 0, "reserved for Apple use" }, /* 0x3e */ { "reserved", 0, "reserved for Apple use" }, /* 0x3f */ { "reserved", 0, "reserved for Apple use" }, /* 0x40 */ { "frameRRect", 8, "rect" }, /* 0x41 */ { "paintRRect", 8, "rect" }, /* 0x42 */ { "eraseRRect", 8, "rect" }, /* 0x43 */ { "invertRRect", 8, "rect" }, /* 0x44 */ { "fillRRrect", 8, "rect" }, /* 0x45 */ { "reserved", 8, "reserved for Apple use" }, /* 0x46 */ { "reserved", 8, "reserved for Apple use" }, /* 0x47 */ { "reserved", 8, "reserved for Apple use" }, /* 0x48 */ { "frameSameRRect", 0, "rect" }, /* 0x49 */ { "paintSameRRect", 0, "rect" }, /* 0x4a */ { "eraseSameRRect", 0, "rect" }, /* 0x4b */ { "invertSameRRect", 0, "rect" }, /* 0x4c */ { "fillSameRRect", 0, "rect" }, /* 0x4d */ { "reserved", 0, "reserved for Apple use" }, /* 0x4e */ { "reserved", 0, "reserved for Apple use" }, /* 0x4f */ { "reserved", 0, "reserved for Apple use" }, /* 0x50 */ { "frameOval", 8, "rect" }, /* 0x51 */ { "paintOval", 8, "rect" }, /* 0x52 */ { "eraseOval", 8, "rect" }, /* 0x53 */ { "invertOval", 8, "rect" }, /* 0x54 */ { "fillOval", 8, "rect" }, /* 0x55 */ { "reserved", 8, "reserved for Apple use" }, /* 0x56 */ { "reserved", 8, "reserved for Apple use" }, /* 0x57 */ { "reserved", 8, "reserved for Apple use" }, /* 0x58 */ { "frameSameOval", 0, "rect" }, /* 0x59 */ { "paintSameOval", 0, "rect" }, /* 0x5a */ { "eraseSameOval", 0, "rect" }, /* 0x5b */ { "invertSameOval", 0, "rect" }, /* 0x5c */ { "fillSameOval", 0, "rect" }, /* 0x5d */ { "reserved", 0, "reserved for Apple use" }, /* 0x5e */ { "reserved", 0, "reserved for Apple use" }, /* 0x5f */ { "reserved", 0, "reserved for Apple use" }, /* 0x60 */ { "frameArc", 12, "rect, startAngle, arcAngle" }, /* 0x61 */ { "paintArc", 12, "rect, startAngle, arcAngle" }, /* 0x62 */ { "eraseArc", 12, "rect, startAngle, arcAngle" }, /* 0x63 */ { "invertArc", 12, "rect, startAngle, arcAngle" }, /* 0x64 */ { "fillArc", 12, "rect, startAngle, arcAngle" }, /* 0x65 */ { "reserved", 12, "reserved for Apple use" }, /* 0x66 */ { "reserved", 12, "reserved for Apple use" }, /* 0x67 */ { "reserved", 12, "reserved for Apple use" }, /* 0x68 */ { "frameSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x69 */ { "paintSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6a */ { "eraseSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6b */ { "invertSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6c */ { "fillSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6d */ { "reserved", 4, "reserved for Apple use" }, /* 0x6e */ { "reserved", 4, "reserved for Apple use" }, /* 0x6f */ { "reserved", 4, "reserved for Apple use" }, /* 0x70 */ { "framePoly", 0, "poly" }, /* 0x71 */ { "paintPoly", 0, "poly" }, /* 0x72 */ { "erasePoly", 0, "poly" }, /* 0x73 */ { "invertPoly", 0, "poly" }, /* 0x74 */ { "fillPoly", 0, "poly" }, /* 0x75 */ { "reserved", 0, "reserved for Apple use" }, /* 0x76 */ { "reserved", 0, "reserved for Apple use" }, /* 0x77 */ { "reserved", 0, "reserved for Apple use" }, /* 0x78 */ { "frameSamePoly", 0, "poly (NYI)" }, /* 0x79 */ { "paintSamePoly", 0, "poly (NYI)" }, /* 0x7a */ { "eraseSamePoly", 0, "poly (NYI)" }, /* 0x7b */ { "invertSamePoly", 0, "poly (NYI)" }, /* 0x7c */ { "fillSamePoly", 0, "poly (NYI)" }, /* 0x7d */ { "reserved", 0, "reserved for Apple use" }, /* 0x7e */ { "reserved", 0, "reserved for Apple use" }, /* 0x7f */ { "reserved", 0, "reserved for Apple use" }, /* 0x80 */ { "frameRgn", 0, "region" }, /* 0x81 */ { "paintRgn", 0, "region" }, /* 0x82 */ { "eraseRgn", 0, "region" }, /* 0x83 */ { "invertRgn", 0, "region" }, /* 0x84 */ { "fillRgn", 0, "region" }, /* 0x85 */ { "reserved", 0, "reserved for Apple use" }, /* 0x86 */ { "reserved", 0, "reserved for Apple use" }, /* 0x87 */ { "reserved", 0, "reserved for Apple use" }, /* 0x88 */ { "frameSameRgn", 0, "region (NYI)" }, /* 0x89 */ { "paintSameRgn", 0, "region (NYI)" }, /* 0x8a */ { "eraseSameRgn", 0, "region (NYI)" }, /* 0x8b */ { "invertSameRgn", 0, "region (NYI)" }, /* 0x8c */ { "fillSameRgn", 0, "region (NYI)" }, /* 0x8d */ { "reserved", 0, "reserved for Apple use" }, /* 0x8e */ { "reserved", 0, "reserved for Apple use" }, /* 0x8f */ { "reserved", 0, "reserved for Apple use" }, /* 0x90 */ { "BitsRect", 0, "copybits, rect clipped" }, /* 0x91 */ { "BitsRgn", 0, "copybits, rgn clipped" }, /* 0x92 */ { "reserved", -1, "reserved for Apple use" }, /* 0x93 */ { "reserved", -1, "reserved for Apple use" }, /* 0x94 */ { "reserved", -1, "reserved for Apple use" }, /* 0x95 */ { "reserved", -1, "reserved for Apple use" }, /* 0x96 */ { "reserved", -1, "reserved for Apple use" }, /* 0x97 */ { "reserved", -1, "reserved for Apple use" }, /* 0x98 */ { "PackBitsRect", 0, "packed copybits, rect clipped" }, /* 0x99 */ { "PackBitsRgn", 0, "packed copybits, rgn clipped" }, /* 0x9a */ { "DirectBitsRect", 0, "PixMap, srcRect, dstRect, mode, PixData" }, /* 0x9b */ { "DirectBitsRgn", 0, "PixMap, srcRect, dstRect, mode, maskRgn, PixData" }, /* 0x9c */ { "reserved", -1, "reserved for Apple use" }, /* 0x9d */ { "reserved", -1, "reserved for Apple use" }, /* 0x9e */ { "reserved", -1, "reserved for Apple use" }, /* 0x9f */ { "reserved", -1, "reserved for Apple use" }, /* 0xa0 */ { "ShortComment", 2, "kind (word)" }, /* 0xa1 */ { "LongComment", 0, "kind (word), size (word), data" } }; /* Forward declarations. */ static MagickBooleanType WritePICTImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage decompresses an image via Macintosh pack bits decoding for % Macintosh PICT images. % % The format of the DecodeImage method is: % % unsigned char *DecodeImage(Image *blob,Image *image, % size_t bytes_per_line,const int bits_per_pixel, % unsigned size_t extent) % % A description of each parameter follows: % % o image_info: the image info. % % o blob,image: the address of a structure of type Image. % % o bytes_per_line: This integer identifies the number of bytes in a % scanline. % % o bits_per_pixel: the number of bits in a pixel. % % o extent: the number of pixels allocated. % */ static unsigned char *ExpandBuffer(unsigned char *pixels, MagickSizeType *bytes_per_line,const unsigned int bits_per_pixel) { register ssize_t i; register unsigned char *p, *q; static unsigned char scanline[8*256]; p=pixels; q=scanline; switch (bits_per_pixel) { case 8: case 16: case 32: return(pixels); case 4: { for (i=0; i < (ssize_t) *bytes_per_line; i++) { *q++=(*p >> 4) & 0xff; *q++=(*p & 15); p++; } *bytes_per_line*=2; break; } case 2: { for (i=0; i < (ssize_t) *bytes_per_line; i++) { *q++=(*p >> 6) & 0x03; *q++=(*p >> 4) & 0x03; *q++=(*p >> 2) & 0x03; *q++=(*p & 3); p++; } *bytes_per_line*=4; break; } case 1: { for (i=0; i < (ssize_t) *bytes_per_line; i++) { *q++=(*p >> 7) & 0x01; *q++=(*p >> 6) & 0x01; *q++=(*p >> 5) & 0x01; *q++=(*p >> 4) & 0x01; *q++=(*p >> 3) & 0x01; *q++=(*p >> 2) & 0x01; *q++=(*p >> 1) & 0x01; *q++=(*p & 0x01); p++; } *bytes_per_line*=8; break; } default: break; } return(scanline); } static unsigned char *DecodeImage(Image *blob,Image *image, size_t bytes_per_line,const unsigned int bits_per_pixel,size_t *extent) { MagickSizeType number_pixels; register ssize_t i; register unsigned char *p, *q; size_t bytes_per_pixel, length, row_bytes, scanline_length, width; ssize_t count, j, y; unsigned char *pixels, *scanline; /* Determine pixel buffer size. */ if (bits_per_pixel <= 8) bytes_per_line&=0x7fff; width=image->columns; bytes_per_pixel=1; if (bits_per_pixel == 16) { bytes_per_pixel=2; width*=2; } else if (bits_per_pixel == 32) width*=image->matte != MagickFalse ? 4 : 3; if (bytes_per_line == 0) bytes_per_line=width; row_bytes=(size_t) (image->columns | 0x8000); if (image->storage_class == DirectClass) row_bytes=(size_t) ((4*image->columns) | 0x8000); /* Allocate pixel and scanline buffer. */ pixels=(unsigned char *) AcquireQuantumMemory(image->rows,row_bytes* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) return((unsigned char *) NULL); *extent=row_bytes*image->rows*sizeof(*pixels); (void) ResetMagickMemory(pixels,0,*extent); scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,2* sizeof(*scanline)); if (scanline == (unsigned char *) NULL) return((unsigned char *) NULL); if (bytes_per_line < 8) { /* Pixels are already uncompressed. */ for (y=0; y < (ssize_t) image->rows; y++) { q=pixels+y*width; number_pixels=bytes_per_line; count=ReadBlob(blob,(size_t) number_pixels,scanline); if (count != (ssize_t) number_pixels) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CorruptImageError,"UnableToUncompressImage","`%s'", image->filename); break; } p=ExpandBuffer(scanline,&number_pixels,bits_per_pixel); if ((q+number_pixels) > (pixels+(*extent))) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CorruptImageError,"UnableToUncompressImage","`%s'", image->filename); break; } (void) CopyMagickMemory(q,p,(size_t) number_pixels); } scanline=(unsigned char *) RelinquishMagickMemory(scanline); return(pixels); } /* Uncompress RLE pixels into uncompressed pixel buffer. */ for (y=0; y < (ssize_t) image->rows; y++) { q=pixels+y*width; if (bytes_per_line > 200) scanline_length=ReadBlobMSBShort(blob); else scanline_length=1UL*ReadBlobByte(blob); if (scanline_length >= row_bytes) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CorruptImageError,"UnableToUncompressImage","`%s'",image->filename); break; } count=ReadBlob(blob,scanline_length,scanline); if (count != (ssize_t) scanline_length) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CorruptImageError,"UnableToUncompressImage","`%s'",image->filename); break; } for (j=0; j < (ssize_t) scanline_length; ) if ((scanline[j] & 0x80) == 0) { length=(size_t) ((scanline[j] & 0xff)+1); number_pixels=length*bytes_per_pixel; p=ExpandBuffer(scanline+j+1,&number_pixels,bits_per_pixel); if ((q-pixels+number_pixels) <= *extent) (void) CopyMagickMemory(q,p,(size_t) number_pixels); q+=number_pixels; j+=(ssize_t) (length*bytes_per_pixel+1); } else { length=(size_t) (((scanline[j] ^ 0xff) & 0xff)+2); number_pixels=bytes_per_pixel; p=ExpandBuffer(scanline+j+1,&number_pixels,bits_per_pixel); for (i=0; i < (ssize_t) length; i++) { if ((q-pixels+number_pixels) <= *extent) (void) CopyMagickMemory(q,p,(size_t) number_pixels); q+=number_pixels; } j+=(ssize_t) bytes_per_pixel+1; } } scanline=(unsigned char *) RelinquishMagickMemory(scanline); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EncodeImage compresses an image via Macintosh pack bits encoding % for Macintosh PICT images. % % The format of the EncodeImage method is: % % size_t EncodeImage(Image *image,const unsigned char *scanline, % const size_t bytes_per_line,unsigned char *pixels) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o scanline: A pointer to an array of characters to pack. % % o bytes_per_line: the number of bytes in a scanline. % % o pixels: A pointer to an array of characters where the packed % characters are stored. % */ static size_t EncodeImage(Image *image,const unsigned char *scanline, const size_t bytes_per_line,unsigned char *pixels) { #define MaxCount 128 #define MaxPackbitsRunlength 128 register const unsigned char *p; register ssize_t i; register unsigned char *q; size_t length; ssize_t count, repeat_count, runlength; unsigned char index; /* Pack scanline. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(scanline != (unsigned char *) NULL); assert(pixels != (unsigned char *) NULL); count=0; runlength=0; p=scanline+(bytes_per_line-1); q=pixels; index=(*p); for (i=(ssize_t) bytes_per_line-1; i >= 0; i--) { if (index == *p) runlength++; else { if (runlength < 3) while (runlength > 0) { *q++=(unsigned char) index; runlength--; count++; if (count == MaxCount) { *q++=(unsigned char) (MaxCount-1); count-=MaxCount; } } else { if (count > 0) *q++=(unsigned char) (count-1); count=0; while (runlength > 0) { repeat_count=runlength; if (repeat_count > MaxPackbitsRunlength) repeat_count=MaxPackbitsRunlength; *q++=(unsigned char) index; *q++=(unsigned char) (257-repeat_count); runlength-=repeat_count; } } runlength=1; } index=(*p); p--; } if (runlength < 3) while (runlength > 0) { *q++=(unsigned char) index; runlength--; count++; if (count == MaxCount) { *q++=(unsigned char) (MaxCount-1); count-=MaxCount; } } else { if (count > 0) *q++=(unsigned char) (count-1); count=0; while (runlength > 0) { repeat_count=runlength; if (repeat_count > MaxPackbitsRunlength) repeat_count=MaxPackbitsRunlength; *q++=(unsigned char) index; *q++=(unsigned char) (257-repeat_count); runlength-=repeat_count; } } if (count > 0) *q++=(unsigned char) (count-1); /* Write the number of and the packed length. */ length=(size_t) (q-pixels); if (bytes_per_line > 200) { (void) WriteBlobMSBShort(image,(unsigned short) length); length+=2; } else { (void) WriteBlobByte(image,(unsigned char) length); length++; } while (q != pixels) { q--; (void) WriteBlobByte(image,*q); } return(length); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P I C T % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPICT()() returns MagickTrue if the image format type, identified by the % magick string, is PICT. % % The format of the ReadPICTImage method is: % % MagickBooleanType IsPICT(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPICT(const unsigned char *magick,const size_t length) { /* Embedded OLE2 macintosh have "PICT" instead of 512 platform header. */ if (length < 12) return(MagickFalse); if (memcmp(magick,"PICT",4) == 0) return(MagickTrue); if (length < 528) return(MagickFalse); if (memcmp(magick+522,"\000\021\002\377\014\000",6) == 0) return(MagickTrue); return(MagickFalse); } #if !defined(macintosh) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPICTImage() reads an Apple Macintosh QuickDraw/PICT image file % and returns it. It allocates the memory necessary for the new Image % structure and returns a pointer to the new image. % % The format of the ReadPICTImage method is: % % Image *ReadPICTImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ReadRectangle(Image *image,PICTRectangle *rectangle) { rectangle->top=(short) ReadBlobMSBShort(image); rectangle->left=(short) ReadBlobMSBShort(image); rectangle->bottom=(short) ReadBlobMSBShort(image); rectangle->right=(short) ReadBlobMSBShort(image); if ((EOFBlob(image) != MagickFalse) || (rectangle->left > rectangle->right) || (rectangle->top > rectangle->bottom)) return(MagickFalse); return(MagickTrue); } static Image *ReadPICTImage(const ImageInfo *image_info, ExceptionInfo *exception) { char geometry[MaxTextExtent], header_ole[4]; Image *image; IndexPacket index; int c, code; MagickBooleanType jpeg, status; PICTRectangle frame; PICTPixmap pixmap; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; size_t extent, length; ssize_t count, flags, j, version, y; StringInfo *profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PICT header. */ pixmap.bits_per_pixel=0; pixmap.component_count=0; /* Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2 */ header_ole[0]=ReadBlobByte(image); header_ole[1]=ReadBlobByte(image); header_ole[2]=ReadBlobByte(image); header_ole[3]=ReadBlobByte(image); if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) && (header_ole[2] == 0x43) && (header_ole[3] == 0x54))) for (i=0; i < 508; i++) if (ReadBlobByte(image) == EOF) break; (void) ReadBlobMSBShort(image); /* skip picture size */ if (ReadRectangle(image,&frame) == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); while ((c=ReadBlobByte(image)) == 0) ; if (c != 0x11) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); version=ReadBlobByte(image); if (version == 2) { c=ReadBlobByte(image); if (c != 0xff) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } else if (version != 1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) || (frame.bottom < 0) || (frame.left >= frame.right) || (frame.top >= frame.bottom)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Create black canvas. */ flags=0; image->depth=8; image->columns=1UL*(frame.right-frame.left); image->rows=1UL*(frame.bottom-frame.top); image->x_resolution=DefaultResolution; image->y_resolution=DefaultResolution; image->units=UndefinedResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Interpret PICT opcodes. */ jpeg=MagickFalse; for (code=0; EOFBlob(image) == MagickFalse; ) { if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((version == 1) || ((TellBlob(image) % 2) != 0)) code=ReadBlobByte(image); if (version == 2) code=ReadBlobMSBSignedShort(image); if (code < 0) break; if (code > 0xa1) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code); } else { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %04X %s: %s",code,codes[code].name,codes[code].description); switch (code) { case 0x01: { /* Clipping rectangle. */ length=ReadBlobMSBShort(image); if (length != 0x000a) { for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; break; } if (ReadRectangle(image,&frame) == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0)) break; image->columns=1UL*(frame.right-frame.left); image->rows=1UL*(frame.bottom-frame.top); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } (void) SetImageBackgroundColor(image); break; } case 0x12: case 0x13: case 0x14: { ssize_t pattern; size_t height, width; /* Skip pattern definition. */ pattern=1L*ReadBlobMSBShort(image); for (i=0; i < 8; i++) if (ReadBlobByte(image) == EOF) break; if (pattern == 2) { for (i=0; i < 5; i++) if (ReadBlobByte(image) == EOF) break; break; } if (pattern != 1) ThrowReaderException(CorruptImageError,"UnknownPatternType"); length=ReadBlobMSBShort(image); if (ReadRectangle(image,&frame) == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); ReadPixmap(pixmap); image->depth=1UL*pixmap.component_size; image->x_resolution=1.0*pixmap.horizontal_resolution; image->y_resolution=1.0*pixmap.vertical_resolution; image->units=PixelsPerInchResolution; (void) ReadBlobMSBLong(image); flags=1L*ReadBlobMSBShort(image); length=ReadBlobMSBShort(image); for (i=0; i <= (ssize_t) length; i++) (void) ReadBlobMSBLong(image); width=1UL*(frame.bottom-frame.top); height=1UL*(frame.right-frame.left); if (pixmap.bits_per_pixel <= 8) length&=0x7fff; if (pixmap.bits_per_pixel == 16) width<<=1; if (length == 0) length=width; if (length < 8) { for (i=0; i < (ssize_t) (length*height); i++) if (ReadBlobByte(image) == EOF) break; } else for (j=0; j < (int) height; j++) if (length > 200) { for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++) if (ReadBlobByte(image) == EOF) break; } else for (j=0; j < (ssize_t) ReadBlobByte(image); j++) if (ReadBlobByte(image) == EOF) break; break; } case 0x1b: { /* Initialize image background color. */ image->background_color.red=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); image->background_color.green=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); image->background_color.blue=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); break; } case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { /* Skip polygon or region. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; break; } case 0x90: case 0x91: case 0x98: case 0x99: case 0x9a: case 0x9b: { ssize_t bytes_per_line; PICTRectangle source, destination; register unsigned char *p; size_t j; unsigned char *pixels; Image *tile_image; /* Pixmap clipped by a rectangle. */ bytes_per_line=0; if ((code != 0x9a) && (code != 0x9b)) bytes_per_line=1L*ReadBlobMSBShort(image); else { (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); } if (ReadRectangle(image,&frame) == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize tile image. */ tile_image=CloneImage(image,1UL*(frame.right-frame.left), 1UL*(frame.bottom-frame.top),MagickTrue,exception); if (tile_image == (Image *) NULL) return((Image *) NULL); if ((code == 0x9a) || (code == 0x9b) || ((bytes_per_line & 0x8000) != 0)) { ReadPixmap(pixmap); tile_image->depth=1UL*pixmap.component_size; tile_image->matte=pixmap.component_count == 4 ? MagickTrue : MagickFalse; tile_image->x_resolution=(double) pixmap.horizontal_resolution; tile_image->y_resolution=(double) pixmap.vertical_resolution; tile_image->units=PixelsPerInchResolution; if (tile_image->matte != MagickFalse) image->matte=tile_image->matte; } if ((code != 0x9a) && (code != 0x9b)) { /* Initialize colormap. */ tile_image->colors=2; if ((bytes_per_line & 0x8000) != 0) { (void) ReadBlobMSBLong(image); flags=1L*ReadBlobMSBShort(image); tile_image->colors=1UL*ReadBlobMSBShort(image)+1; } status=AcquireImageColormap(tile_image,tile_image->colors); if (status == MagickFalse) { tile_image=DestroyImage(tile_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if ((bytes_per_line & 0x8000) != 0) { for (i=0; i < (ssize_t) tile_image->colors; i++) { j=ReadBlobMSBShort(image) % tile_image->colors; if ((flags & 0x8000) != 0) j=(size_t) i; tile_image->colormap[j].red=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); tile_image->colormap[j].green=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); tile_image->colormap[j].blue=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); } } else { for (i=0; i < (ssize_t) tile_image->colors; i++) { tile_image->colormap[i].red=(Quantum) (QuantumRange- tile_image->colormap[i].red); tile_image->colormap[i].green=(Quantum) (QuantumRange- tile_image->colormap[i].green); tile_image->colormap[i].blue=(Quantum) (QuantumRange- tile_image->colormap[i].blue); } } } if (ReadRectangle(image,&source) == MagickFalse) { tile_image=DestroyImage(tile_image); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (ReadRectangle(image,&destination) == MagickFalse) { tile_image=DestroyImage(tile_image); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } (void) ReadBlobMSBShort(image); if ((code == 0x91) || (code == 0x99) || (code == 0x9b)) { /* Skip region. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; } if ((code != 0x9a) && (code != 0x9b) && (bytes_per_line & 0x8000) == 0) pixels=DecodeImage(image,tile_image,1UL*bytes_per_line,1,&extent); else pixels=DecodeImage(image,tile_image,1UL*bytes_per_line,1U* pixmap.bits_per_pixel,&extent); if (pixels == (unsigned char *) NULL) { tile_image=DestroyImage(tile_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* Convert PICT tile image to pixel packets. */ p=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { if (p > (pixels+extent+image->columns)) { tile_image=DestroyImage(tile_image); ThrowReaderException(CorruptImageError,"NotEnoughPixelData"); } q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) { if (tile_image->storage_class == PseudoClass) { index=ConstrainColormapIndex(tile_image,*p); SetPixelIndex(indexes+x,index); SetPixelRed(q, tile_image->colormap[(ssize_t) index].red); SetPixelGreen(q, tile_image->colormap[(ssize_t) index].green); SetPixelBlue(q, tile_image->colormap[(ssize_t) index].blue); } else { if (pixmap.bits_per_pixel == 16) { i=(*p++); j=(*p); SetPixelRed(q,ScaleCharToQuantum( (unsigned char) ((i & 0x7c) << 1))); SetPixelGreen(q,ScaleCharToQuantum( (unsigned char) (((i & 0x03) << 6) | ((j & 0xe0) >> 2)))); SetPixelBlue(q,ScaleCharToQuantum( (unsigned char) ((j & 0x1f) << 3))); } else if (tile_image->matte == MagickFalse) { if (p > (pixels+extent+2*image->columns)) { tile_image=DestroyImage(tile_image); ThrowReaderException(CorruptImageError, "NotEnoughPixelData"); } SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum( *(p+tile_image->columns))); SetPixelBlue(q,ScaleCharToQuantum( *(p+2*tile_image->columns))); } else { if (p > (pixels+extent+3*image->columns)) { tile_image=DestroyImage(tile_image); ThrowReaderException(CorruptImageError, "NotEnoughPixelData"); } SetPixelAlpha(q,ScaleCharToQuantum(*p)); SetPixelRed(q,ScaleCharToQuantum( *(p+tile_image->columns))); SetPixelGreen(q,ScaleCharToQuantum( *(p+2*tile_image->columns))); SetPixelBlue(q,ScaleCharToQuantum( *(p+3*tile_image->columns))); } } p++; q++; } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; if ((tile_image->storage_class == DirectClass) && (pixmap.bits_per_pixel != 16)) { p+=(pixmap.component_count-1)*tile_image->columns; if (p < pixels) break; } status=SetImageProgress(image,LoadImageTag,y,tile_image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (jpeg == MagickFalse) if ((code == 0x9a) || (code == 0x9b) || ((bytes_per_line & 0x8000) != 0)) (void) CompositeImage(image,CopyCompositeOp,tile_image, destination.left,destination.top); tile_image=DestroyImage(tile_image); break; } case 0xa1: { unsigned char *info; size_t type; /* Comment. */ type=ReadBlobMSBShort(image); length=ReadBlobMSBShort(image); if (length == 0) break; (void) ReadBlobMSBLong(image); length-=4; if (length == 0) break; info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info)); if (info == (unsigned char *) NULL) break; count=ReadBlob(image,length,info); if (count != (ssize_t) length) ThrowReaderException(ResourceLimitError,"UnableToReadImageData"); switch (type) { case 0xe0: { profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,info); status=SetImageProfile(image,"icc",profile); profile=DestroyStringInfo(profile); if (status == MagickFalse) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } break; } case 0x1f2: { profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,info); status=SetImageProfile(image,"iptc",profile); if (status == MagickFalse) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } profile=DestroyStringInfo(profile); break; } default: break; } info=(unsigned char *) RelinquishMagickMemory(info); break; } default: { /* Skip to next op code. */ if (codes[code].length == -1) (void) ReadBlobMSBShort(image); else for (i=0; i < (ssize_t) codes[code].length; i++) if (ReadBlobByte(image) == EOF) break; } } } if (code == 0xc00) { /* Skip header. */ for (i=0; i < 24; i++) if (ReadBlobByte(image) == EOF) break; continue; } if (((code >= 0xb0) && (code <= 0xcf)) || ((code >= 0x8000) && (code <= 0x80ff))) continue; if (code == 0x8200) { FILE *file; Image *tile_image; ImageInfo *read_info; int unique_file; /* Embedded JPEG. */ jpeg=MagickTrue; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(read_info->filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(read_info->filename); (void) CopyMagickString(image->filename,read_info->filename, MaxTextExtent); ThrowFileException(exception,FileOpenError, "UnableToCreateTemporaryFile",image->filename); image=DestroyImageList(image); return((Image *) NULL); } length=ReadBlobMSBLong(image); if (length > 154) { for (i=0; i < 6; i++) (void) ReadBlobMSBLong(image); if (ReadRectangle(image,&frame) == MagickFalse) { (void) fclose(file); (void) RelinquishUniqueFileResource(read_info->filename); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } for (i=0; i < 122; i++) if (ReadBlobByte(image) == EOF) break; for (i=0; i < (ssize_t) (length-154); i++) { c=ReadBlobByte(image); if (c == EOF) break; (void) fputc(c,file); } } (void) fclose(file); (void) close(unique_file); tile_image=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (tile_image == (Image *) NULL) continue; (void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g", (double) MagickMax(image->columns,tile_image->columns), (double) MagickMax(image->rows,tile_image->rows)); (void) SetImageExtent(image, MagickMax(image->columns,tile_image->columns), MagickMax(image->rows,tile_image->rows)); (void) TransformImageColorspace(image,tile_image->colorspace); (void) CompositeImage(image,CopyCompositeOp,tile_image,frame.left, frame.right); image->compression=tile_image->compression; tile_image=DestroyImage(tile_image); continue; } if ((code == 0xff) || (code == 0xffff)) break; if (((code >= 0xd0) && (code <= 0xfe)) || ((code >= 0x8100) && (code <= 0xffff))) { /* Skip reserved. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) length; i++) if (ReadBlobByte(image) == EOF) break; continue; } if ((code >= 0x100) && (code <= 0x7fff)) { /* Skip reserved. */ length=(size_t) ((code >> 7) & 0xff); for (i=0; i < (ssize_t) length; i++) if (ReadBlobByte(image) == EOF) break; continue; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPICTImage() adds attributes for the PICT image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPICTImage method is: % % size_t RegisterPICTImage(void) % */ ModuleExport size_t RegisterPICTImage(void) { MagickInfo *entry; entry=SetMagickInfo("PCT"); entry->decoder=(DecodeImageHandler *) ReadPICTImage; entry->encoder=(EncodeImageHandler *) WritePICTImage; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Apple Macintosh QuickDraw/PICT"); entry->magick=(IsImageFormatHandler *) IsPICT; entry->module=ConstantString("PICT"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PICT"); entry->decoder=(DecodeImageHandler *) ReadPICTImage; entry->encoder=(EncodeImageHandler *) WritePICTImage; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Apple Macintosh QuickDraw/PICT"); entry->magick=(IsImageFormatHandler *) IsPICT; entry->module=ConstantString("PICT"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPICTImage() removes format registrations made by the % PICT module from the list of supported formats. % % The format of the UnregisterPICTImage method is: % % UnregisterPICTImage(void) % */ ModuleExport void UnregisterPICTImage(void) { (void) UnregisterMagickInfo("PCT"); (void) UnregisterMagickInfo("PICT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePICTImage() writes an image to a file in the Apple Macintosh % QuickDraw/PICT image format. % % The format of the WritePICTImage method is: % % MagickBooleanType WritePICTImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WritePICTImage(const ImageInfo *image_info, Image *image) { #define MaxCount 128 #define PictCropRegionOp 0x01 #define PictEndOfPictureOp 0xff #define PictJPEGOp 0x8200 #define PictInfoOp 0x0C00 #define PictInfoSize 512 #define PictPixmapOp 0x9A #define PictPICTOp 0x98 #define PictVersion 0x11 const StringInfo *profile; double x_resolution, y_resolution; MagickBooleanType status; MagickOffsetType offset; PICTPixmap pixmap; PICTRectangle bounds, crop_rectangle, destination_rectangle, frame_rectangle, size_rectangle, source_rectangle; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; size_t bytes_per_line, count, row_bytes, storage_class; ssize_t y; unsigned char *buffer, *packed_scanline, *scanline; unsigned short base_address, transfer_mode; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns > 65535L) || (image->rows > 65535L)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); /* Initialize image info. */ size_rectangle.top=0; size_rectangle.left=0; size_rectangle.bottom=(short) image->rows; size_rectangle.right=(short) image->columns; frame_rectangle=size_rectangle; crop_rectangle=size_rectangle; source_rectangle=size_rectangle; destination_rectangle=size_rectangle; base_address=0xff; row_bytes=image->columns; bounds.top=0; bounds.left=0; bounds.bottom=(short) image->rows; bounds.right=(short) image->columns; pixmap.version=0; pixmap.pack_type=0; pixmap.pack_size=0; pixmap.pixel_type=0; pixmap.bits_per_pixel=8; pixmap.component_count=1; pixmap.component_size=8; pixmap.plane_bytes=0; pixmap.table=0; pixmap.reserved=0; transfer_mode=0; x_resolution=image->x_resolution != 0.0 ? image->x_resolution : DefaultResolution; y_resolution=image->y_resolution != 0.0 ? image->y_resolution : DefaultResolution; storage_class=image->storage_class; if (image_info->compression == JPEGCompression) storage_class=DirectClass; if (storage_class == DirectClass) { pixmap.component_count=image->matte != MagickFalse ? 4 : 3; pixmap.pixel_type=16; pixmap.bits_per_pixel=32; pixmap.pack_type=0x04; transfer_mode=0x40; row_bytes=4*image->columns; } /* Allocate memory. */ bytes_per_line=image->columns; if (storage_class == DirectClass) bytes_per_line*=image->matte != MagickFalse ? 4 : 3; buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer)); packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t) (row_bytes+MaxCount),sizeof(*packed_scanline)); scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline)); if ((buffer == (unsigned char *) NULL) || (packed_scanline == (unsigned char *) NULL) || (scanline == (unsigned char *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(scanline,0,row_bytes); (void) ResetMagickMemory(packed_scanline,0,(size_t) (row_bytes+MaxCount)); /* Write header, header size, size bounding box, version, and reserved. */ (void) ResetMagickMemory(buffer,0,PictInfoSize); (void) WriteBlob(image,PictInfoSize,buffer); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right); (void) WriteBlobMSBShort(image,PictVersion); (void) WriteBlobMSBShort(image,0x02ff); /* version #2 */ (void) WriteBlobMSBShort(image,PictInfoOp); (void) WriteBlobMSBLong(image,0xFFFE0000UL); /* Write full size of the file, resolution, frame bounding box, and reserved. */ (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right); (void) WriteBlobMSBLong(image,0x00000000L); profile=GetImageProfile(image,"iptc"); if (profile != (StringInfo *) NULL) { (void) WriteBlobMSBShort(image,0xa1); (void) WriteBlobMSBShort(image,0x1f2); (void) WriteBlobMSBShort(image,(unsigned short) (GetStringInfoLength(profile)+4)); (void) WriteBlobString(image,"8BIM"); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); } profile=GetImageProfile(image,"icc"); if (profile != (StringInfo *) NULL) { (void) WriteBlobMSBShort(image,0xa1); (void) WriteBlobMSBShort(image,0xe0); (void) WriteBlobMSBShort(image,(unsigned short) (GetStringInfoLength(profile)+4)); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) WriteBlobMSBShort(image,0xa1); (void) WriteBlobMSBShort(image,0xe0); (void) WriteBlobMSBShort(image,4); (void) WriteBlobMSBLong(image,0x00000002UL); } /* Write crop region opcode and crop bounding box. */ (void) WriteBlobMSBShort(image,PictCropRegionOp); (void) WriteBlobMSBShort(image,0xa); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right); if (image_info->compression == JPEGCompression) { Image *jpeg_image; ImageInfo *jpeg_info; size_t length; unsigned char *blob; jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (jpeg_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } jpeg_info=CloneImageInfo(image_info); (void) CopyMagickString(jpeg_info->magick,"JPEG",MaxTextExtent); length=0; blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length, &image->exception); jpeg_info=DestroyImageInfo(jpeg_info); if (blob == (unsigned char *) NULL) return(MagickFalse); jpeg_image=DestroyImage(jpeg_image); (void) WriteBlobMSBShort(image,PictJPEGOp); (void) WriteBlobMSBLong(image,(unsigned int) length+154); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBLong(image,0x00010000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00010000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x40000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00400000UL); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) image->rows); (void) WriteBlobMSBShort(image,(unsigned short) image->columns); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,768); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00566A70UL); (void) WriteBlobMSBLong(image,0x65670000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000001UL); (void) WriteBlobMSBLong(image,0x00016170UL); (void) WriteBlobMSBLong(image,0x706C0000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBShort(image,768); (void) WriteBlobMSBShort(image,(unsigned short) image->columns); (void) WriteBlobMSBShort(image,(unsigned short) image->rows); (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x87AC0001UL); (void) WriteBlobMSBLong(image,0x0B466F74UL); (void) WriteBlobMSBLong(image,0x6F202D20UL); (void) WriteBlobMSBLong(image,0x4A504547UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x0018FFFFUL); (void) WriteBlob(image,length,blob); if ((length & 0x01) != 0) (void) WriteBlobByte(image,'\0'); blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Write picture opcode, row bytes, and picture bounding box, and version. */ if (storage_class == PseudoClass) (void) WriteBlobMSBShort(image,PictPICTOp); else { (void) WriteBlobMSBShort(image,PictPixmapOp); (void) WriteBlobMSBLong(image,(size_t) base_address); } (void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000)); (void) WriteBlobMSBShort(image,(unsigned short) bounds.top); (void) WriteBlobMSBShort(image,(unsigned short) bounds.left); (void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom); (void) WriteBlobMSBShort(image,(unsigned short) bounds.right); /* Write pack type, pack size, resolution, pixel type, and pixel size. */ (void) WriteBlobMSBShort(image,(unsigned short) pixmap.version); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size); (void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel); /* Write component count, size, plane bytes, table size, and reserved. */ (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.table); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved); if (storage_class == PseudoClass) { /* Write image colormap. */ (void) WriteBlobMSBLong(image,0x00000000L); /* color seed */ (void) WriteBlobMSBShort(image,0L); /* color flags */ (void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1)); for (i=0; i < (ssize_t) image->colors; i++) { (void) WriteBlobMSBShort(image,(unsigned short) i); (void) WriteBlobMSBShort(image,ScaleQuantumToShort( image->colormap[i].red)); (void) WriteBlobMSBShort(image,ScaleQuantumToShort( image->colormap[i].green)); (void) WriteBlobMSBShort(image,ScaleQuantumToShort( image->colormap[i].blue)); } } /* Write source and destination rectangle. */ (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right); (void) WriteBlobMSBShort(image,(unsigned short) transfer_mode); /* Write picture data. */ count=0; if (storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) scanline[x]=(unsigned char) GetPixelIndex(indexes+x); count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), packed_scanline); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image_info->compression == JPEGCompression) { (void) ResetMagickMemory(scanline,0,row_bytes); for (y=0; y < (ssize_t) image->rows; y++) count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), packed_scanline); } else { register unsigned char *blue, *green, *opacity, *red; red=scanline; green=scanline+image->columns; blue=scanline+2*image->columns; opacity=scanline+3*image->columns; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; red=scanline; green=scanline+image->columns; blue=scanline+2*image->columns; if (image->matte != MagickFalse) { opacity=scanline; red=scanline+image->columns; green=scanline+2*image->columns; blue=scanline+3*image->columns; } for (x=0; x < (ssize_t) image->columns; x++) { *red++=ScaleQuantumToChar(GetPixelRed(p)); *green++=ScaleQuantumToChar(GetPixelGreen(p)); *blue++=ScaleQuantumToChar(GetPixelBlue(p)); if (image->matte != MagickFalse) *opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p))); p++; } count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if ((count & 0x01) != 0) (void) WriteBlobByte(image,'\0'); (void) WriteBlobMSBShort(image,PictEndOfPictureOp); offset=TellBlob(image); offset=SeekBlob(image,512,SEEK_SET); (void) WriteBlobMSBShort(image,(unsigned short) offset); scanline=(unsigned char *) RelinquishMagickMemory(scanline); packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline); buffer=(unsigned char *) RelinquishMagickMemory(buffer); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2619_0
crossvul-cpp_data_bad_661_0
/* * mac80211_hwsim - software simulator of 802.11 radio(s) for mac80211 * Copyright (c) 2008, Jouni Malinen <j@w1.fi> * Copyright (c) 2011, Javier Lopez <jlopex@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ /* * TODO: * - Add TSF sync and fix IBSS beacon transmission by adding * competition for "air time" at TBTT * - RX filtering based on filter configuration (data->rx_filter) */ #include <linux/list.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <net/dst.h> #include <net/xfrm.h> #include <net/mac80211.h> #include <net/ieee80211_radiotap.h> #include <linux/if_arp.h> #include <linux/rtnetlink.h> #include <linux/etherdevice.h> #include <linux/platform_device.h> #include <linux/debugfs.h> #include <linux/module.h> #include <linux/ktime.h> #include <net/genetlink.h> #include <net/net_namespace.h> #include <net/netns/generic.h> #include <linux/rhashtable.h> #include "mac80211_hwsim.h" #define WARN_QUEUE 100 #define MAX_QUEUE 200 MODULE_AUTHOR("Jouni Malinen"); MODULE_DESCRIPTION("Software simulator of 802.11 radio(s) for mac80211"); MODULE_LICENSE("GPL"); static int radios = 2; module_param(radios, int, 0444); MODULE_PARM_DESC(radios, "Number of simulated radios"); static int channels = 1; module_param(channels, int, 0444); MODULE_PARM_DESC(channels, "Number of concurrent channels"); static bool paged_rx = false; module_param(paged_rx, bool, 0644); MODULE_PARM_DESC(paged_rx, "Use paged SKBs for RX instead of linear ones"); static bool rctbl = false; module_param(rctbl, bool, 0444); MODULE_PARM_DESC(rctbl, "Handle rate control table"); static bool support_p2p_device = true; module_param(support_p2p_device, bool, 0444); MODULE_PARM_DESC(support_p2p_device, "Support P2P-Device interface type"); /** * enum hwsim_regtest - the type of regulatory tests we offer * * These are the different values you can use for the regtest * module parameter. This is useful to help test world roaming * and the driver regulatory_hint() call and combinations of these. * If you want to do specific alpha2 regulatory domain tests simply * use the userspace regulatory request as that will be respected as * well without the need of this module parameter. This is designed * only for testing the driver regulatory request, world roaming * and all possible combinations. * * @HWSIM_REGTEST_DISABLED: No regulatory tests are performed, * this is the default value. * @HWSIM_REGTEST_DRIVER_REG_FOLLOW: Used for testing the driver regulatory * hint, only one driver regulatory hint will be sent as such the * secondary radios are expected to follow. * @HWSIM_REGTEST_DRIVER_REG_ALL: Used for testing the driver regulatory * request with all radios reporting the same regulatory domain. * @HWSIM_REGTEST_DIFF_COUNTRY: Used for testing the drivers calling * different regulatory domains requests. Expected behaviour is for * an intersection to occur but each device will still use their * respective regulatory requested domains. Subsequent radios will * use the resulting intersection. * @HWSIM_REGTEST_WORLD_ROAM: Used for testing the world roaming. We accomplish * this by using a custom beacon-capable regulatory domain for the first * radio. All other device world roam. * @HWSIM_REGTEST_CUSTOM_WORLD: Used for testing the custom world regulatory * domain requests. All radios will adhere to this custom world regulatory * domain. * @HWSIM_REGTEST_CUSTOM_WORLD_2: Used for testing 2 custom world regulatory * domain requests. The first radio will adhere to the first custom world * regulatory domain, the second one to the second custom world regulatory * domain. All other devices will world roam. * @HWSIM_REGTEST_STRICT_FOLLOW_: Used for testing strict regulatory domain * settings, only the first radio will send a regulatory domain request * and use strict settings. The rest of the radios are expected to follow. * @HWSIM_REGTEST_STRICT_ALL: Used for testing strict regulatory domain * settings. All radios will adhere to this. * @HWSIM_REGTEST_STRICT_AND_DRIVER_REG: Used for testing strict regulatory * domain settings, combined with secondary driver regulatory domain * settings. The first radio will get a strict regulatory domain setting * using the first driver regulatory request and the second radio will use * non-strict settings using the second driver regulatory request. All * other devices should follow the intersection created between the * first two. * @HWSIM_REGTEST_ALL: Used for testing every possible mix. You will need * at least 6 radios for a complete test. We will test in this order: * 1 - driver custom world regulatory domain * 2 - second custom world regulatory domain * 3 - first driver regulatory domain request * 4 - second driver regulatory domain request * 5 - strict regulatory domain settings using the third driver regulatory * domain request * 6 and on - should follow the intersection of the 3rd, 4rth and 5th radio * regulatory requests. */ enum hwsim_regtest { HWSIM_REGTEST_DISABLED = 0, HWSIM_REGTEST_DRIVER_REG_FOLLOW = 1, HWSIM_REGTEST_DRIVER_REG_ALL = 2, HWSIM_REGTEST_DIFF_COUNTRY = 3, HWSIM_REGTEST_WORLD_ROAM = 4, HWSIM_REGTEST_CUSTOM_WORLD = 5, HWSIM_REGTEST_CUSTOM_WORLD_2 = 6, HWSIM_REGTEST_STRICT_FOLLOW = 7, HWSIM_REGTEST_STRICT_ALL = 8, HWSIM_REGTEST_STRICT_AND_DRIVER_REG = 9, HWSIM_REGTEST_ALL = 10, }; /* Set to one of the HWSIM_REGTEST_* values above */ static int regtest = HWSIM_REGTEST_DISABLED; module_param(regtest, int, 0444); MODULE_PARM_DESC(regtest, "The type of regulatory test we want to run"); static const char *hwsim_alpha2s[] = { "FI", "AL", "US", "DE", "JP", "AL", }; static const struct ieee80211_regdomain hwsim_world_regdom_custom_01 = { .n_reg_rules = 4, .alpha2 = "99", .reg_rules = { REG_RULE(2412-10, 2462+10, 40, 0, 20, 0), REG_RULE(2484-10, 2484+10, 40, 0, 20, 0), REG_RULE(5150-10, 5240+10, 40, 0, 30, 0), REG_RULE(5745-10, 5825+10, 40, 0, 30, 0), } }; static const struct ieee80211_regdomain hwsim_world_regdom_custom_02 = { .n_reg_rules = 2, .alpha2 = "99", .reg_rules = { REG_RULE(2412-10, 2462+10, 40, 0, 20, 0), REG_RULE(5725-10, 5850+10, 40, 0, 30, NL80211_RRF_NO_IR), } }; static const struct ieee80211_regdomain *hwsim_world_regdom_custom[] = { &hwsim_world_regdom_custom_01, &hwsim_world_regdom_custom_02, }; struct hwsim_vif_priv { u32 magic; u8 bssid[ETH_ALEN]; bool assoc; bool bcn_en; u16 aid; }; #define HWSIM_VIF_MAGIC 0x69537748 static inline void hwsim_check_magic(struct ieee80211_vif *vif) { struct hwsim_vif_priv *vp = (void *)vif->drv_priv; WARN(vp->magic != HWSIM_VIF_MAGIC, "Invalid VIF (%p) magic %#x, %pM, %d/%d\n", vif, vp->magic, vif->addr, vif->type, vif->p2p); } static inline void hwsim_set_magic(struct ieee80211_vif *vif) { struct hwsim_vif_priv *vp = (void *)vif->drv_priv; vp->magic = HWSIM_VIF_MAGIC; } static inline void hwsim_clear_magic(struct ieee80211_vif *vif) { struct hwsim_vif_priv *vp = (void *)vif->drv_priv; vp->magic = 0; } struct hwsim_sta_priv { u32 magic; }; #define HWSIM_STA_MAGIC 0x6d537749 static inline void hwsim_check_sta_magic(struct ieee80211_sta *sta) { struct hwsim_sta_priv *sp = (void *)sta->drv_priv; WARN_ON(sp->magic != HWSIM_STA_MAGIC); } static inline void hwsim_set_sta_magic(struct ieee80211_sta *sta) { struct hwsim_sta_priv *sp = (void *)sta->drv_priv; sp->magic = HWSIM_STA_MAGIC; } static inline void hwsim_clear_sta_magic(struct ieee80211_sta *sta) { struct hwsim_sta_priv *sp = (void *)sta->drv_priv; sp->magic = 0; } struct hwsim_chanctx_priv { u32 magic; }; #define HWSIM_CHANCTX_MAGIC 0x6d53774a static inline void hwsim_check_chanctx_magic(struct ieee80211_chanctx_conf *c) { struct hwsim_chanctx_priv *cp = (void *)c->drv_priv; WARN_ON(cp->magic != HWSIM_CHANCTX_MAGIC); } static inline void hwsim_set_chanctx_magic(struct ieee80211_chanctx_conf *c) { struct hwsim_chanctx_priv *cp = (void *)c->drv_priv; cp->magic = HWSIM_CHANCTX_MAGIC; } static inline void hwsim_clear_chanctx_magic(struct ieee80211_chanctx_conf *c) { struct hwsim_chanctx_priv *cp = (void *)c->drv_priv; cp->magic = 0; } static unsigned int hwsim_net_id; static int hwsim_netgroup; struct hwsim_net { int netgroup; u32 wmediumd; }; static inline int hwsim_net_get_netgroup(struct net *net) { struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id); return hwsim_net->netgroup; } static inline void hwsim_net_set_netgroup(struct net *net) { struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id); hwsim_net->netgroup = hwsim_netgroup++; } static inline u32 hwsim_net_get_wmediumd(struct net *net) { struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id); return hwsim_net->wmediumd; } static inline void hwsim_net_set_wmediumd(struct net *net, u32 portid) { struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id); hwsim_net->wmediumd = portid; } static struct class *hwsim_class; static struct net_device *hwsim_mon; /* global monitor netdev */ #define CHAN2G(_freq) { \ .band = NL80211_BAND_2GHZ, \ .center_freq = (_freq), \ .hw_value = (_freq), \ .max_power = 20, \ } #define CHAN5G(_freq) { \ .band = NL80211_BAND_5GHZ, \ .center_freq = (_freq), \ .hw_value = (_freq), \ .max_power = 20, \ } static const struct ieee80211_channel hwsim_channels_2ghz[] = { CHAN2G(2412), /* Channel 1 */ CHAN2G(2417), /* Channel 2 */ CHAN2G(2422), /* Channel 3 */ CHAN2G(2427), /* Channel 4 */ CHAN2G(2432), /* Channel 5 */ CHAN2G(2437), /* Channel 6 */ CHAN2G(2442), /* Channel 7 */ CHAN2G(2447), /* Channel 8 */ CHAN2G(2452), /* Channel 9 */ CHAN2G(2457), /* Channel 10 */ CHAN2G(2462), /* Channel 11 */ CHAN2G(2467), /* Channel 12 */ CHAN2G(2472), /* Channel 13 */ CHAN2G(2484), /* Channel 14 */ }; static const struct ieee80211_channel hwsim_channels_5ghz[] = { CHAN5G(5180), /* Channel 36 */ CHAN5G(5200), /* Channel 40 */ CHAN5G(5220), /* Channel 44 */ CHAN5G(5240), /* Channel 48 */ CHAN5G(5260), /* Channel 52 */ CHAN5G(5280), /* Channel 56 */ CHAN5G(5300), /* Channel 60 */ CHAN5G(5320), /* Channel 64 */ CHAN5G(5500), /* Channel 100 */ CHAN5G(5520), /* Channel 104 */ CHAN5G(5540), /* Channel 108 */ CHAN5G(5560), /* Channel 112 */ CHAN5G(5580), /* Channel 116 */ CHAN5G(5600), /* Channel 120 */ CHAN5G(5620), /* Channel 124 */ CHAN5G(5640), /* Channel 128 */ CHAN5G(5660), /* Channel 132 */ CHAN5G(5680), /* Channel 136 */ CHAN5G(5700), /* Channel 140 */ CHAN5G(5745), /* Channel 149 */ CHAN5G(5765), /* Channel 153 */ CHAN5G(5785), /* Channel 157 */ CHAN5G(5805), /* Channel 161 */ CHAN5G(5825), /* Channel 165 */ CHAN5G(5845), /* Channel 169 */ }; static const struct ieee80211_rate hwsim_rates[] = { { .bitrate = 10 }, { .bitrate = 20, .flags = IEEE80211_RATE_SHORT_PREAMBLE }, { .bitrate = 55, .flags = IEEE80211_RATE_SHORT_PREAMBLE }, { .bitrate = 110, .flags = IEEE80211_RATE_SHORT_PREAMBLE }, { .bitrate = 60 }, { .bitrate = 90 }, { .bitrate = 120 }, { .bitrate = 180 }, { .bitrate = 240 }, { .bitrate = 360 }, { .bitrate = 480 }, { .bitrate = 540 } }; #define OUI_QCA 0x001374 #define QCA_NL80211_SUBCMD_TEST 1 enum qca_nl80211_vendor_subcmds { QCA_WLAN_VENDOR_ATTR_TEST = 8, QCA_WLAN_VENDOR_ATTR_MAX = QCA_WLAN_VENDOR_ATTR_TEST }; static const struct nla_policy hwsim_vendor_test_policy[QCA_WLAN_VENDOR_ATTR_MAX + 1] = { [QCA_WLAN_VENDOR_ATTR_MAX] = { .type = NLA_U32 }, }; static int mac80211_hwsim_vendor_cmd_test(struct wiphy *wiphy, struct wireless_dev *wdev, const void *data, int data_len) { struct sk_buff *skb; struct nlattr *tb[QCA_WLAN_VENDOR_ATTR_MAX + 1]; int err; u32 val; err = nla_parse(tb, QCA_WLAN_VENDOR_ATTR_MAX, data, data_len, hwsim_vendor_test_policy, NULL); if (err) return err; if (!tb[QCA_WLAN_VENDOR_ATTR_TEST]) return -EINVAL; val = nla_get_u32(tb[QCA_WLAN_VENDOR_ATTR_TEST]); wiphy_dbg(wiphy, "%s: test=%u\n", __func__, val); /* Send a vendor event as a test. Note that this would not normally be * done within a command handler, but rather, based on some other * trigger. For simplicity, this command is used to trigger the event * here. * * event_idx = 0 (index in mac80211_hwsim_vendor_commands) */ skb = cfg80211_vendor_event_alloc(wiphy, wdev, 100, 0, GFP_KERNEL); if (skb) { /* skb_put() or nla_put() will fill up data within * NL80211_ATTR_VENDOR_DATA. */ /* Add vendor data */ nla_put_u32(skb, QCA_WLAN_VENDOR_ATTR_TEST, val + 1); /* Send the event - this will call nla_nest_end() */ cfg80211_vendor_event(skb, GFP_KERNEL); } /* Send a response to the command */ skb = cfg80211_vendor_cmd_alloc_reply_skb(wiphy, 10); if (!skb) return -ENOMEM; /* skb_put() or nla_put() will fill up data within * NL80211_ATTR_VENDOR_DATA */ nla_put_u32(skb, QCA_WLAN_VENDOR_ATTR_TEST, val + 2); return cfg80211_vendor_cmd_reply(skb); } static struct wiphy_vendor_command mac80211_hwsim_vendor_commands[] = { { .info = { .vendor_id = OUI_QCA, .subcmd = QCA_NL80211_SUBCMD_TEST }, .flags = WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mac80211_hwsim_vendor_cmd_test, } }; /* Advertise support vendor specific events */ static const struct nl80211_vendor_cmd_info mac80211_hwsim_vendor_events[] = { { .vendor_id = OUI_QCA, .subcmd = 1 }, }; static const struct ieee80211_iface_limit hwsim_if_limits[] = { { .max = 1, .types = BIT(NL80211_IFTYPE_ADHOC) }, { .max = 2048, .types = BIT(NL80211_IFTYPE_STATION) | BIT(NL80211_IFTYPE_P2P_CLIENT) | #ifdef CONFIG_MAC80211_MESH BIT(NL80211_IFTYPE_MESH_POINT) | #endif BIT(NL80211_IFTYPE_AP) | BIT(NL80211_IFTYPE_P2P_GO) }, /* must be last, see hwsim_if_comb */ { .max = 1, .types = BIT(NL80211_IFTYPE_P2P_DEVICE) } }; static const struct ieee80211_iface_combination hwsim_if_comb[] = { { .limits = hwsim_if_limits, /* remove the last entry which is P2P_DEVICE */ .n_limits = ARRAY_SIZE(hwsim_if_limits) - 1, .max_interfaces = 2048, .num_different_channels = 1, .radar_detect_widths = BIT(NL80211_CHAN_WIDTH_20_NOHT) | BIT(NL80211_CHAN_WIDTH_20) | BIT(NL80211_CHAN_WIDTH_40) | BIT(NL80211_CHAN_WIDTH_80) | BIT(NL80211_CHAN_WIDTH_160), }, }; static const struct ieee80211_iface_combination hwsim_if_comb_p2p_dev[] = { { .limits = hwsim_if_limits, .n_limits = ARRAY_SIZE(hwsim_if_limits), .max_interfaces = 2048, .num_different_channels = 1, .radar_detect_widths = BIT(NL80211_CHAN_WIDTH_20_NOHT) | BIT(NL80211_CHAN_WIDTH_20) | BIT(NL80211_CHAN_WIDTH_40) | BIT(NL80211_CHAN_WIDTH_80) | BIT(NL80211_CHAN_WIDTH_160), }, }; static spinlock_t hwsim_radio_lock; static LIST_HEAD(hwsim_radios); static struct rhashtable hwsim_radios_rht; static int hwsim_radio_idx; static struct platform_driver mac80211_hwsim_driver = { .driver = { .name = "mac80211_hwsim", }, }; struct mac80211_hwsim_data { struct list_head list; struct rhash_head rht; struct ieee80211_hw *hw; struct device *dev; struct ieee80211_supported_band bands[NUM_NL80211_BANDS]; struct ieee80211_channel channels_2ghz[ARRAY_SIZE(hwsim_channels_2ghz)]; struct ieee80211_channel channels_5ghz[ARRAY_SIZE(hwsim_channels_5ghz)]; struct ieee80211_rate rates[ARRAY_SIZE(hwsim_rates)]; struct ieee80211_iface_combination if_combination; struct mac_address addresses[2]; int channels, idx; bool use_chanctx; bool destroy_on_close; struct work_struct destroy_work; u32 portid; char alpha2[2]; const struct ieee80211_regdomain *regd; struct ieee80211_channel *tmp_chan; struct ieee80211_channel *roc_chan; u32 roc_duration; struct delayed_work roc_start; struct delayed_work roc_done; struct delayed_work hw_scan; struct cfg80211_scan_request *hw_scan_request; struct ieee80211_vif *hw_scan_vif; int scan_chan_idx; u8 scan_addr[ETH_ALEN]; struct { struct ieee80211_channel *channel; unsigned long next_start, start, end; } survey_data[ARRAY_SIZE(hwsim_channels_2ghz) + ARRAY_SIZE(hwsim_channels_5ghz)]; struct ieee80211_channel *channel; u64 beacon_int /* beacon interval in us */; unsigned int rx_filter; bool started, idle, scanning; struct mutex mutex; struct tasklet_hrtimer beacon_timer; enum ps_mode { PS_DISABLED, PS_ENABLED, PS_AUTO_POLL, PS_MANUAL_POLL } ps; bool ps_poll_pending; struct dentry *debugfs; uintptr_t pending_cookie; struct sk_buff_head pending; /* packets pending */ /* * Only radios in the same group can communicate together (the * channel has to match too). Each bit represents a group. A * radio can be in more than one group. */ u64 group; /* group shared by radios created in the same netns */ int netgroup; /* wmediumd portid responsible for netgroup of this radio */ u32 wmediumd; /* difference between this hw's clock and the real clock, in usecs */ s64 tsf_offset; s64 bcn_delta; /* absolute beacon transmission time. Used to cover up "tx" delay. */ u64 abs_bcn_ts; /* Stats */ u64 tx_pkts; u64 rx_pkts; u64 tx_bytes; u64 rx_bytes; u64 tx_dropped; u64 tx_failed; }; static const struct rhashtable_params hwsim_rht_params = { .nelem_hint = 2, .automatic_shrinking = true, .key_len = ETH_ALEN, .key_offset = offsetof(struct mac80211_hwsim_data, addresses[1]), .head_offset = offsetof(struct mac80211_hwsim_data, rht), }; struct hwsim_radiotap_hdr { struct ieee80211_radiotap_header hdr; __le64 rt_tsft; u8 rt_flags; u8 rt_rate; __le16 rt_channel; __le16 rt_chbitmask; } __packed; struct hwsim_radiotap_ack_hdr { struct ieee80211_radiotap_header hdr; u8 rt_flags; u8 pad; __le16 rt_channel; __le16 rt_chbitmask; } __packed; /* MAC80211_HWSIM netlink family */ static struct genl_family hwsim_genl_family; enum hwsim_multicast_groups { HWSIM_MCGRP_CONFIG, }; static const struct genl_multicast_group hwsim_mcgrps[] = { [HWSIM_MCGRP_CONFIG] = { .name = "config", }, }; /* MAC80211_HWSIM netlink policy */ static const struct nla_policy hwsim_genl_policy[HWSIM_ATTR_MAX + 1] = { [HWSIM_ATTR_ADDR_RECEIVER] = { .type = NLA_UNSPEC, .len = ETH_ALEN }, [HWSIM_ATTR_ADDR_TRANSMITTER] = { .type = NLA_UNSPEC, .len = ETH_ALEN }, [HWSIM_ATTR_FRAME] = { .type = NLA_BINARY, .len = IEEE80211_MAX_DATA_LEN }, [HWSIM_ATTR_FLAGS] = { .type = NLA_U32 }, [HWSIM_ATTR_RX_RATE] = { .type = NLA_U32 }, [HWSIM_ATTR_SIGNAL] = { .type = NLA_U32 }, [HWSIM_ATTR_TX_INFO] = { .type = NLA_UNSPEC, .len = IEEE80211_TX_MAX_RATES * sizeof(struct hwsim_tx_rate)}, [HWSIM_ATTR_COOKIE] = { .type = NLA_U64 }, [HWSIM_ATTR_CHANNELS] = { .type = NLA_U32 }, [HWSIM_ATTR_RADIO_ID] = { .type = NLA_U32 }, [HWSIM_ATTR_REG_HINT_ALPHA2] = { .type = NLA_STRING, .len = 2 }, [HWSIM_ATTR_REG_CUSTOM_REG] = { .type = NLA_U32 }, [HWSIM_ATTR_REG_STRICT_REG] = { .type = NLA_FLAG }, [HWSIM_ATTR_SUPPORT_P2P_DEVICE] = { .type = NLA_FLAG }, [HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE] = { .type = NLA_FLAG }, [HWSIM_ATTR_RADIO_NAME] = { .type = NLA_STRING }, [HWSIM_ATTR_NO_VIF] = { .type = NLA_FLAG }, [HWSIM_ATTR_FREQ] = { .type = NLA_U32 }, }; static void mac80211_hwsim_tx_frame(struct ieee80211_hw *hw, struct sk_buff *skb, struct ieee80211_channel *chan); /* sysfs attributes */ static void hwsim_send_ps_poll(void *dat, u8 *mac, struct ieee80211_vif *vif) { struct mac80211_hwsim_data *data = dat; struct hwsim_vif_priv *vp = (void *)vif->drv_priv; struct sk_buff *skb; struct ieee80211_pspoll *pspoll; if (!vp->assoc) return; wiphy_dbg(data->hw->wiphy, "%s: send PS-Poll to %pM for aid %d\n", __func__, vp->bssid, vp->aid); skb = dev_alloc_skb(sizeof(*pspoll)); if (!skb) return; pspoll = skb_put(skb, sizeof(*pspoll)); pspoll->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL | IEEE80211_STYPE_PSPOLL | IEEE80211_FCTL_PM); pspoll->aid = cpu_to_le16(0xc000 | vp->aid); memcpy(pspoll->bssid, vp->bssid, ETH_ALEN); memcpy(pspoll->ta, mac, ETH_ALEN); rcu_read_lock(); mac80211_hwsim_tx_frame(data->hw, skb, rcu_dereference(vif->chanctx_conf)->def.chan); rcu_read_unlock(); } static void hwsim_send_nullfunc(struct mac80211_hwsim_data *data, u8 *mac, struct ieee80211_vif *vif, int ps) { struct hwsim_vif_priv *vp = (void *)vif->drv_priv; struct sk_buff *skb; struct ieee80211_hdr *hdr; if (!vp->assoc) return; wiphy_dbg(data->hw->wiphy, "%s: send data::nullfunc to %pM ps=%d\n", __func__, vp->bssid, ps); skb = dev_alloc_skb(sizeof(*hdr)); if (!skb) return; hdr = skb_put(skb, sizeof(*hdr) - ETH_ALEN); hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA | IEEE80211_STYPE_NULLFUNC | IEEE80211_FCTL_TODS | (ps ? IEEE80211_FCTL_PM : 0)); hdr->duration_id = cpu_to_le16(0); memcpy(hdr->addr1, vp->bssid, ETH_ALEN); memcpy(hdr->addr2, mac, ETH_ALEN); memcpy(hdr->addr3, vp->bssid, ETH_ALEN); rcu_read_lock(); mac80211_hwsim_tx_frame(data->hw, skb, rcu_dereference(vif->chanctx_conf)->def.chan); rcu_read_unlock(); } static void hwsim_send_nullfunc_ps(void *dat, u8 *mac, struct ieee80211_vif *vif) { struct mac80211_hwsim_data *data = dat; hwsim_send_nullfunc(data, mac, vif, 1); } static void hwsim_send_nullfunc_no_ps(void *dat, u8 *mac, struct ieee80211_vif *vif) { struct mac80211_hwsim_data *data = dat; hwsim_send_nullfunc(data, mac, vif, 0); } static int hwsim_fops_ps_read(void *dat, u64 *val) { struct mac80211_hwsim_data *data = dat; *val = data->ps; return 0; } static int hwsim_fops_ps_write(void *dat, u64 val) { struct mac80211_hwsim_data *data = dat; enum ps_mode old_ps; if (val != PS_DISABLED && val != PS_ENABLED && val != PS_AUTO_POLL && val != PS_MANUAL_POLL) return -EINVAL; if (val == PS_MANUAL_POLL) { if (data->ps != PS_ENABLED) return -EINVAL; local_bh_disable(); ieee80211_iterate_active_interfaces_atomic( data->hw, IEEE80211_IFACE_ITER_NORMAL, hwsim_send_ps_poll, data); local_bh_enable(); return 0; } old_ps = data->ps; data->ps = val; local_bh_disable(); if (old_ps == PS_DISABLED && val != PS_DISABLED) { ieee80211_iterate_active_interfaces_atomic( data->hw, IEEE80211_IFACE_ITER_NORMAL, hwsim_send_nullfunc_ps, data); } else if (old_ps != PS_DISABLED && val == PS_DISABLED) { ieee80211_iterate_active_interfaces_atomic( data->hw, IEEE80211_IFACE_ITER_NORMAL, hwsim_send_nullfunc_no_ps, data); } local_bh_enable(); return 0; } DEFINE_SIMPLE_ATTRIBUTE(hwsim_fops_ps, hwsim_fops_ps_read, hwsim_fops_ps_write, "%llu\n"); static int hwsim_write_simulate_radar(void *dat, u64 val) { struct mac80211_hwsim_data *data = dat; ieee80211_radar_detected(data->hw); return 0; } DEFINE_SIMPLE_ATTRIBUTE(hwsim_simulate_radar, NULL, hwsim_write_simulate_radar, "%llu\n"); static int hwsim_fops_group_read(void *dat, u64 *val) { struct mac80211_hwsim_data *data = dat; *val = data->group; return 0; } static int hwsim_fops_group_write(void *dat, u64 val) { struct mac80211_hwsim_data *data = dat; data->group = val; return 0; } DEFINE_SIMPLE_ATTRIBUTE(hwsim_fops_group, hwsim_fops_group_read, hwsim_fops_group_write, "%llx\n"); static netdev_tx_t hwsim_mon_xmit(struct sk_buff *skb, struct net_device *dev) { /* TODO: allow packet injection */ dev_kfree_skb(skb); return NETDEV_TX_OK; } static inline u64 mac80211_hwsim_get_tsf_raw(void) { return ktime_to_us(ktime_get_real()); } static __le64 __mac80211_hwsim_get_tsf(struct mac80211_hwsim_data *data) { u64 now = mac80211_hwsim_get_tsf_raw(); return cpu_to_le64(now + data->tsf_offset); } static u64 mac80211_hwsim_get_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct mac80211_hwsim_data *data = hw->priv; return le64_to_cpu(__mac80211_hwsim_get_tsf(data)); } static void mac80211_hwsim_set_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u64 tsf) { struct mac80211_hwsim_data *data = hw->priv; u64 now = mac80211_hwsim_get_tsf(hw, vif); u32 bcn_int = data->beacon_int; u64 delta = abs(tsf - now); /* adjust after beaconing with new timestamp at old TBTT */ if (tsf > now) { data->tsf_offset += delta; data->bcn_delta = do_div(delta, bcn_int); } else { data->tsf_offset -= delta; data->bcn_delta = -(s64)do_div(delta, bcn_int); } } static void mac80211_hwsim_monitor_rx(struct ieee80211_hw *hw, struct sk_buff *tx_skb, struct ieee80211_channel *chan) { struct mac80211_hwsim_data *data = hw->priv; struct sk_buff *skb; struct hwsim_radiotap_hdr *hdr; u16 flags; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx_skb); struct ieee80211_rate *txrate = ieee80211_get_tx_rate(hw, info); if (WARN_ON(!txrate)) return; if (!netif_running(hwsim_mon)) return; skb = skb_copy_expand(tx_skb, sizeof(*hdr), 0, GFP_ATOMIC); if (skb == NULL) return; hdr = skb_push(skb, sizeof(*hdr)); hdr->hdr.it_version = PKTHDR_RADIOTAP_VERSION; hdr->hdr.it_pad = 0; hdr->hdr.it_len = cpu_to_le16(sizeof(*hdr)); hdr->hdr.it_present = cpu_to_le32((1 << IEEE80211_RADIOTAP_FLAGS) | (1 << IEEE80211_RADIOTAP_RATE) | (1 << IEEE80211_RADIOTAP_TSFT) | (1 << IEEE80211_RADIOTAP_CHANNEL)); hdr->rt_tsft = __mac80211_hwsim_get_tsf(data); hdr->rt_flags = 0; hdr->rt_rate = txrate->bitrate / 5; hdr->rt_channel = cpu_to_le16(chan->center_freq); flags = IEEE80211_CHAN_2GHZ; if (txrate->flags & IEEE80211_RATE_ERP_G) flags |= IEEE80211_CHAN_OFDM; else flags |= IEEE80211_CHAN_CCK; hdr->rt_chbitmask = cpu_to_le16(flags); skb->dev = hwsim_mon; skb_reset_mac_header(skb); skb->ip_summed = CHECKSUM_UNNECESSARY; skb->pkt_type = PACKET_OTHERHOST; skb->protocol = htons(ETH_P_802_2); memset(skb->cb, 0, sizeof(skb->cb)); netif_rx(skb); } static void mac80211_hwsim_monitor_ack(struct ieee80211_channel *chan, const u8 *addr) { struct sk_buff *skb; struct hwsim_radiotap_ack_hdr *hdr; u16 flags; struct ieee80211_hdr *hdr11; if (!netif_running(hwsim_mon)) return; skb = dev_alloc_skb(100); if (skb == NULL) return; hdr = skb_put(skb, sizeof(*hdr)); hdr->hdr.it_version = PKTHDR_RADIOTAP_VERSION; hdr->hdr.it_pad = 0; hdr->hdr.it_len = cpu_to_le16(sizeof(*hdr)); hdr->hdr.it_present = cpu_to_le32((1 << IEEE80211_RADIOTAP_FLAGS) | (1 << IEEE80211_RADIOTAP_CHANNEL)); hdr->rt_flags = 0; hdr->pad = 0; hdr->rt_channel = cpu_to_le16(chan->center_freq); flags = IEEE80211_CHAN_2GHZ; hdr->rt_chbitmask = cpu_to_le16(flags); hdr11 = skb_put(skb, 10); hdr11->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL | IEEE80211_STYPE_ACK); hdr11->duration_id = cpu_to_le16(0); memcpy(hdr11->addr1, addr, ETH_ALEN); skb->dev = hwsim_mon; skb_reset_mac_header(skb); skb->ip_summed = CHECKSUM_UNNECESSARY; skb->pkt_type = PACKET_OTHERHOST; skb->protocol = htons(ETH_P_802_2); memset(skb->cb, 0, sizeof(skb->cb)); netif_rx(skb); } struct mac80211_hwsim_addr_match_data { u8 addr[ETH_ALEN]; bool ret; }; static void mac80211_hwsim_addr_iter(void *data, u8 *mac, struct ieee80211_vif *vif) { struct mac80211_hwsim_addr_match_data *md = data; if (memcmp(mac, md->addr, ETH_ALEN) == 0) md->ret = true; } static bool mac80211_hwsim_addr_match(struct mac80211_hwsim_data *data, const u8 *addr) { struct mac80211_hwsim_addr_match_data md = { .ret = false, }; if (data->scanning && memcmp(addr, data->scan_addr, ETH_ALEN) == 0) return true; memcpy(md.addr, addr, ETH_ALEN); ieee80211_iterate_active_interfaces_atomic(data->hw, IEEE80211_IFACE_ITER_NORMAL, mac80211_hwsim_addr_iter, &md); return md.ret; } static bool hwsim_ps_rx_ok(struct mac80211_hwsim_data *data, struct sk_buff *skb) { switch (data->ps) { case PS_DISABLED: return true; case PS_ENABLED: return false; case PS_AUTO_POLL: /* TODO: accept (some) Beacons by default and other frames only * if pending PS-Poll has been sent */ return true; case PS_MANUAL_POLL: /* Allow unicast frames to own address if there is a pending * PS-Poll */ if (data->ps_poll_pending && mac80211_hwsim_addr_match(data, skb->data + 4)) { data->ps_poll_pending = false; return true; } return false; } return true; } static int hwsim_unicast_netgroup(struct mac80211_hwsim_data *data, struct sk_buff *skb, int portid) { struct net *net; bool found = false; int res = -ENOENT; rcu_read_lock(); for_each_net_rcu(net) { if (data->netgroup == hwsim_net_get_netgroup(net)) { res = genlmsg_unicast(net, skb, portid); found = true; break; } } rcu_read_unlock(); if (!found) nlmsg_free(skb); return res; } static inline u16 trans_tx_rate_flags_ieee2hwsim(struct ieee80211_tx_rate *rate) { u16 result = 0; if (rate->flags & IEEE80211_TX_RC_USE_RTS_CTS) result |= MAC80211_HWSIM_TX_RC_USE_RTS_CTS; if (rate->flags & IEEE80211_TX_RC_USE_CTS_PROTECT) result |= MAC80211_HWSIM_TX_RC_USE_CTS_PROTECT; if (rate->flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE) result |= MAC80211_HWSIM_TX_RC_USE_SHORT_PREAMBLE; if (rate->flags & IEEE80211_TX_RC_MCS) result |= MAC80211_HWSIM_TX_RC_MCS; if (rate->flags & IEEE80211_TX_RC_GREEN_FIELD) result |= MAC80211_HWSIM_TX_RC_GREEN_FIELD; if (rate->flags & IEEE80211_TX_RC_40_MHZ_WIDTH) result |= MAC80211_HWSIM_TX_RC_40_MHZ_WIDTH; if (rate->flags & IEEE80211_TX_RC_DUP_DATA) result |= MAC80211_HWSIM_TX_RC_DUP_DATA; if (rate->flags & IEEE80211_TX_RC_SHORT_GI) result |= MAC80211_HWSIM_TX_RC_SHORT_GI; if (rate->flags & IEEE80211_TX_RC_VHT_MCS) result |= MAC80211_HWSIM_TX_RC_VHT_MCS; if (rate->flags & IEEE80211_TX_RC_80_MHZ_WIDTH) result |= MAC80211_HWSIM_TX_RC_80_MHZ_WIDTH; if (rate->flags & IEEE80211_TX_RC_160_MHZ_WIDTH) result |= MAC80211_HWSIM_TX_RC_160_MHZ_WIDTH; return result; } static void mac80211_hwsim_tx_frame_nl(struct ieee80211_hw *hw, struct sk_buff *my_skb, int dst_portid) { struct sk_buff *skb; struct mac80211_hwsim_data *data = hw->priv; struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) my_skb->data; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(my_skb); void *msg_head; unsigned int hwsim_flags = 0; int i; struct hwsim_tx_rate tx_attempts[IEEE80211_TX_MAX_RATES]; struct hwsim_tx_rate_flag tx_attempts_flags[IEEE80211_TX_MAX_RATES]; uintptr_t cookie; if (data->ps != PS_DISABLED) hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM); /* If the queue contains MAX_QUEUE skb's drop some */ if (skb_queue_len(&data->pending) >= MAX_QUEUE) { /* Droping until WARN_QUEUE level */ while (skb_queue_len(&data->pending) >= WARN_QUEUE) { ieee80211_free_txskb(hw, skb_dequeue(&data->pending)); data->tx_dropped++; } } skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (skb == NULL) goto nla_put_failure; msg_head = genlmsg_put(skb, 0, 0, &hwsim_genl_family, 0, HWSIM_CMD_FRAME); if (msg_head == NULL) { pr_debug("mac80211_hwsim: problem with msg_head\n"); goto nla_put_failure; } if (nla_put(skb, HWSIM_ATTR_ADDR_TRANSMITTER, ETH_ALEN, data->addresses[1].addr)) goto nla_put_failure; /* We get the skb->data */ if (nla_put(skb, HWSIM_ATTR_FRAME, my_skb->len, my_skb->data)) goto nla_put_failure; /* We get the flags for this transmission, and we translate them to wmediumd flags */ if (info->flags & IEEE80211_TX_CTL_REQ_TX_STATUS) hwsim_flags |= HWSIM_TX_CTL_REQ_TX_STATUS; if (info->flags & IEEE80211_TX_CTL_NO_ACK) hwsim_flags |= HWSIM_TX_CTL_NO_ACK; if (nla_put_u32(skb, HWSIM_ATTR_FLAGS, hwsim_flags)) goto nla_put_failure; if (nla_put_u32(skb, HWSIM_ATTR_FREQ, data->channel->center_freq)) goto nla_put_failure; /* We get the tx control (rate and retries) info*/ for (i = 0; i < IEEE80211_TX_MAX_RATES; i++) { tx_attempts[i].idx = info->status.rates[i].idx; tx_attempts_flags[i].idx = info->status.rates[i].idx; tx_attempts[i].count = info->status.rates[i].count; tx_attempts_flags[i].flags = trans_tx_rate_flags_ieee2hwsim( &info->status.rates[i]); } if (nla_put(skb, HWSIM_ATTR_TX_INFO, sizeof(struct hwsim_tx_rate)*IEEE80211_TX_MAX_RATES, tx_attempts)) goto nla_put_failure; if (nla_put(skb, HWSIM_ATTR_TX_INFO_FLAGS, sizeof(struct hwsim_tx_rate_flag) * IEEE80211_TX_MAX_RATES, tx_attempts_flags)) goto nla_put_failure; /* We create a cookie to identify this skb */ data->pending_cookie++; cookie = data->pending_cookie; info->rate_driver_data[0] = (void *)cookie; if (nla_put_u64_64bit(skb, HWSIM_ATTR_COOKIE, cookie, HWSIM_ATTR_PAD)) goto nla_put_failure; genlmsg_end(skb, msg_head); if (hwsim_unicast_netgroup(data, skb, dst_portid)) goto err_free_txskb; /* Enqueue the packet */ skb_queue_tail(&data->pending, my_skb); data->tx_pkts++; data->tx_bytes += my_skb->len; return; nla_put_failure: nlmsg_free(skb); err_free_txskb: pr_debug("mac80211_hwsim: error occurred in %s\n", __func__); ieee80211_free_txskb(hw, my_skb); data->tx_failed++; } static bool hwsim_chans_compat(struct ieee80211_channel *c1, struct ieee80211_channel *c2) { if (!c1 || !c2) return false; return c1->center_freq == c2->center_freq; } struct tx_iter_data { struct ieee80211_channel *channel; bool receive; }; static void mac80211_hwsim_tx_iter(void *_data, u8 *addr, struct ieee80211_vif *vif) { struct tx_iter_data *data = _data; if (!vif->chanctx_conf) return; if (!hwsim_chans_compat(data->channel, rcu_dereference(vif->chanctx_conf)->def.chan)) return; data->receive = true; } static void mac80211_hwsim_add_vendor_rtap(struct sk_buff *skb) { /* * To enable this code, #define the HWSIM_RADIOTAP_OUI, * e.g. like this: * #define HWSIM_RADIOTAP_OUI "\x02\x00\x00" * (but you should use a valid OUI, not that) * * If anyone wants to 'donate' a radiotap OUI/subns code * please send a patch removing this #ifdef and changing * the values accordingly. */ #ifdef HWSIM_RADIOTAP_OUI struct ieee80211_vendor_radiotap *rtap; /* * Note that this code requires the headroom in the SKB * that was allocated earlier. */ rtap = skb_push(skb, sizeof(*rtap) + 8 + 4); rtap->oui[0] = HWSIM_RADIOTAP_OUI[0]; rtap->oui[1] = HWSIM_RADIOTAP_OUI[1]; rtap->oui[2] = HWSIM_RADIOTAP_OUI[2]; rtap->subns = 127; /* * Radiotap vendor namespaces can (and should) also be * split into fields by using the standard radiotap * presence bitmap mechanism. Use just BIT(0) here for * the presence bitmap. */ rtap->present = BIT(0); /* We have 8 bytes of (dummy) data */ rtap->len = 8; /* For testing, also require it to be aligned */ rtap->align = 8; /* And also test that padding works, 4 bytes */ rtap->pad = 4; /* push the data */ memcpy(rtap->data, "ABCDEFGH", 8); /* make sure to clear padding, mac80211 doesn't */ memset(rtap->data + 8, 0, 4); IEEE80211_SKB_RXCB(skb)->flag |= RX_FLAG_RADIOTAP_VENDOR_DATA; #endif } static bool mac80211_hwsim_tx_frame_no_nl(struct ieee80211_hw *hw, struct sk_buff *skb, struct ieee80211_channel *chan) { struct mac80211_hwsim_data *data = hw->priv, *data2; bool ack = false; struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_rx_status rx_status; u64 now; memset(&rx_status, 0, sizeof(rx_status)); rx_status.flag |= RX_FLAG_MACTIME_START; rx_status.freq = chan->center_freq; rx_status.band = chan->band; if (info->control.rates[0].flags & IEEE80211_TX_RC_VHT_MCS) { rx_status.rate_idx = ieee80211_rate_get_vht_mcs(&info->control.rates[0]); rx_status.nss = ieee80211_rate_get_vht_nss(&info->control.rates[0]); rx_status.encoding = RX_ENC_VHT; } else { rx_status.rate_idx = info->control.rates[0].idx; if (info->control.rates[0].flags & IEEE80211_TX_RC_MCS) rx_status.encoding = RX_ENC_HT; } if (info->control.rates[0].flags & IEEE80211_TX_RC_40_MHZ_WIDTH) rx_status.bw = RATE_INFO_BW_40; else if (info->control.rates[0].flags & IEEE80211_TX_RC_80_MHZ_WIDTH) rx_status.bw = RATE_INFO_BW_80; else if (info->control.rates[0].flags & IEEE80211_TX_RC_160_MHZ_WIDTH) rx_status.bw = RATE_INFO_BW_160; else rx_status.bw = RATE_INFO_BW_20; if (info->control.rates[0].flags & IEEE80211_TX_RC_SHORT_GI) rx_status.enc_flags |= RX_ENC_FLAG_SHORT_GI; /* TODO: simulate real signal strength (and optional packet loss) */ rx_status.signal = -50; if (info->control.vif) rx_status.signal += info->control.vif->bss_conf.txpower; if (data->ps != PS_DISABLED) hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM); /* release the skb's source info */ skb_orphan(skb); skb_dst_drop(skb); skb->mark = 0; secpath_reset(skb); nf_reset(skb); /* * Get absolute mactime here so all HWs RX at the "same time", and * absolute TX time for beacon mactime so the timestamp matches. * Giving beacons a different mactime than non-beacons looks messy, but * it helps the Toffset be exact and a ~10us mactime discrepancy * probably doesn't really matter. */ if (ieee80211_is_beacon(hdr->frame_control) || ieee80211_is_probe_resp(hdr->frame_control)) now = data->abs_bcn_ts; else now = mac80211_hwsim_get_tsf_raw(); /* Copy skb to all enabled radios that are on the current frequency */ spin_lock(&hwsim_radio_lock); list_for_each_entry(data2, &hwsim_radios, list) { struct sk_buff *nskb; struct tx_iter_data tx_iter_data = { .receive = false, .channel = chan, }; if (data == data2) continue; if (!data2->started || (data2->idle && !data2->tmp_chan) || !hwsim_ps_rx_ok(data2, skb)) continue; if (!(data->group & data2->group)) continue; if (data->netgroup != data2->netgroup) continue; if (!hwsim_chans_compat(chan, data2->tmp_chan) && !hwsim_chans_compat(chan, data2->channel)) { ieee80211_iterate_active_interfaces_atomic( data2->hw, IEEE80211_IFACE_ITER_NORMAL, mac80211_hwsim_tx_iter, &tx_iter_data); if (!tx_iter_data.receive) continue; } /* * reserve some space for our vendor and the normal * radiotap header, since we're copying anyway */ if (skb->len < PAGE_SIZE && paged_rx) { struct page *page = alloc_page(GFP_ATOMIC); if (!page) continue; nskb = dev_alloc_skb(128); if (!nskb) { __free_page(page); continue; } memcpy(page_address(page), skb->data, skb->len); skb_add_rx_frag(nskb, 0, page, 0, skb->len, skb->len); } else { nskb = skb_copy(skb, GFP_ATOMIC); if (!nskb) continue; } if (mac80211_hwsim_addr_match(data2, hdr->addr1)) ack = true; rx_status.mactime = now + data2->tsf_offset; memcpy(IEEE80211_SKB_RXCB(nskb), &rx_status, sizeof(rx_status)); mac80211_hwsim_add_vendor_rtap(nskb); data2->rx_pkts++; data2->rx_bytes += nskb->len; ieee80211_rx_irqsafe(data2->hw, nskb); } spin_unlock(&hwsim_radio_lock); return ack; } static void mac80211_hwsim_tx(struct ieee80211_hw *hw, struct ieee80211_tx_control *control, struct sk_buff *skb) { struct mac80211_hwsim_data *data = hw->priv; struct ieee80211_tx_info *txi = IEEE80211_SKB_CB(skb); struct ieee80211_hdr *hdr = (void *)skb->data; struct ieee80211_chanctx_conf *chanctx_conf; struct ieee80211_channel *channel; bool ack; u32 _portid; if (WARN_ON(skb->len < 10)) { /* Should not happen; just a sanity check for addr1 use */ ieee80211_free_txskb(hw, skb); return; } if (!data->use_chanctx) { channel = data->channel; } else if (txi->hw_queue == 4) { channel = data->tmp_chan; } else { chanctx_conf = rcu_dereference(txi->control.vif->chanctx_conf); if (chanctx_conf) channel = chanctx_conf->def.chan; else channel = NULL; } if (WARN(!channel, "TX w/o channel - queue = %d\n", txi->hw_queue)) { ieee80211_free_txskb(hw, skb); return; } if (data->idle && !data->tmp_chan) { wiphy_dbg(hw->wiphy, "Trying to TX when idle - reject\n"); ieee80211_free_txskb(hw, skb); return; } if (txi->control.vif) hwsim_check_magic(txi->control.vif); if (control->sta) hwsim_check_sta_magic(control->sta); if (ieee80211_hw_check(hw, SUPPORTS_RC_TABLE)) ieee80211_get_tx_rates(txi->control.vif, control->sta, skb, txi->control.rates, ARRAY_SIZE(txi->control.rates)); if (skb->len >= 24 + 8 && ieee80211_is_probe_resp(hdr->frame_control)) { /* fake header transmission time */ struct ieee80211_mgmt *mgmt; struct ieee80211_rate *txrate; u64 ts; mgmt = (struct ieee80211_mgmt *)skb->data; txrate = ieee80211_get_tx_rate(hw, txi); ts = mac80211_hwsim_get_tsf_raw(); mgmt->u.probe_resp.timestamp = cpu_to_le64(ts + data->tsf_offset + 24 * 8 * 10 / txrate->bitrate); } mac80211_hwsim_monitor_rx(hw, skb, channel); /* wmediumd mode check */ _portid = READ_ONCE(data->wmediumd); if (_portid) return mac80211_hwsim_tx_frame_nl(hw, skb, _portid); /* NO wmediumd detected, perfect medium simulation */ data->tx_pkts++; data->tx_bytes += skb->len; ack = mac80211_hwsim_tx_frame_no_nl(hw, skb, channel); if (ack && skb->len >= 16) mac80211_hwsim_monitor_ack(channel, hdr->addr2); ieee80211_tx_info_clear_status(txi); /* frame was transmitted at most favorable rate at first attempt */ txi->control.rates[0].count = 1; txi->control.rates[1].idx = -1; if (!(txi->flags & IEEE80211_TX_CTL_NO_ACK) && ack) txi->flags |= IEEE80211_TX_STAT_ACK; ieee80211_tx_status_irqsafe(hw, skb); } static int mac80211_hwsim_start(struct ieee80211_hw *hw) { struct mac80211_hwsim_data *data = hw->priv; wiphy_dbg(hw->wiphy, "%s\n", __func__); data->started = true; return 0; } static void mac80211_hwsim_stop(struct ieee80211_hw *hw) { struct mac80211_hwsim_data *data = hw->priv; data->started = false; tasklet_hrtimer_cancel(&data->beacon_timer); wiphy_dbg(hw->wiphy, "%s\n", __func__); } static int mac80211_hwsim_add_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { wiphy_dbg(hw->wiphy, "%s (type=%d mac_addr=%pM)\n", __func__, ieee80211_vif_type_p2p(vif), vif->addr); hwsim_set_magic(vif); vif->cab_queue = 0; vif->hw_queue[IEEE80211_AC_VO] = 0; vif->hw_queue[IEEE80211_AC_VI] = 1; vif->hw_queue[IEEE80211_AC_BE] = 2; vif->hw_queue[IEEE80211_AC_BK] = 3; return 0; } static int mac80211_hwsim_change_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum nl80211_iftype newtype, bool newp2p) { newtype = ieee80211_iftype_p2p(newtype, newp2p); wiphy_dbg(hw->wiphy, "%s (old type=%d, new type=%d, mac_addr=%pM)\n", __func__, ieee80211_vif_type_p2p(vif), newtype, vif->addr); hwsim_check_magic(vif); /* * interface may change from non-AP to AP in * which case this needs to be set up again */ vif->cab_queue = 0; return 0; } static void mac80211_hwsim_remove_interface( struct ieee80211_hw *hw, struct ieee80211_vif *vif) { wiphy_dbg(hw->wiphy, "%s (type=%d mac_addr=%pM)\n", __func__, ieee80211_vif_type_p2p(vif), vif->addr); hwsim_check_magic(vif); hwsim_clear_magic(vif); } static void mac80211_hwsim_tx_frame(struct ieee80211_hw *hw, struct sk_buff *skb, struct ieee80211_channel *chan) { struct mac80211_hwsim_data *data = hw->priv; u32 _pid = READ_ONCE(data->wmediumd); if (ieee80211_hw_check(hw, SUPPORTS_RC_TABLE)) { struct ieee80211_tx_info *txi = IEEE80211_SKB_CB(skb); ieee80211_get_tx_rates(txi->control.vif, NULL, skb, txi->control.rates, ARRAY_SIZE(txi->control.rates)); } mac80211_hwsim_monitor_rx(hw, skb, chan); if (_pid) return mac80211_hwsim_tx_frame_nl(hw, skb, _pid); mac80211_hwsim_tx_frame_no_nl(hw, skb, chan); dev_kfree_skb(skb); } static void mac80211_hwsim_beacon_tx(void *arg, u8 *mac, struct ieee80211_vif *vif) { struct mac80211_hwsim_data *data = arg; struct ieee80211_hw *hw = data->hw; struct ieee80211_tx_info *info; struct ieee80211_rate *txrate; struct ieee80211_mgmt *mgmt; struct sk_buff *skb; hwsim_check_magic(vif); if (vif->type != NL80211_IFTYPE_AP && vif->type != NL80211_IFTYPE_MESH_POINT && vif->type != NL80211_IFTYPE_ADHOC) return; skb = ieee80211_beacon_get(hw, vif); if (skb == NULL) return; info = IEEE80211_SKB_CB(skb); if (ieee80211_hw_check(hw, SUPPORTS_RC_TABLE)) ieee80211_get_tx_rates(vif, NULL, skb, info->control.rates, ARRAY_SIZE(info->control.rates)); txrate = ieee80211_get_tx_rate(hw, info); mgmt = (struct ieee80211_mgmt *) skb->data; /* fake header transmission time */ data->abs_bcn_ts = mac80211_hwsim_get_tsf_raw(); mgmt->u.beacon.timestamp = cpu_to_le64(data->abs_bcn_ts + data->tsf_offset + 24 * 8 * 10 / txrate->bitrate); mac80211_hwsim_tx_frame(hw, skb, rcu_dereference(vif->chanctx_conf)->def.chan); if (vif->csa_active && ieee80211_csa_is_complete(vif)) ieee80211_csa_finish(vif); } static enum hrtimer_restart mac80211_hwsim_beacon(struct hrtimer *timer) { struct mac80211_hwsim_data *data = container_of(timer, struct mac80211_hwsim_data, beacon_timer.timer); struct ieee80211_hw *hw = data->hw; u64 bcn_int = data->beacon_int; ktime_t next_bcn; if (!data->started) goto out; ieee80211_iterate_active_interfaces_atomic( hw, IEEE80211_IFACE_ITER_NORMAL, mac80211_hwsim_beacon_tx, data); /* beacon at new TBTT + beacon interval */ if (data->bcn_delta) { bcn_int -= data->bcn_delta; data->bcn_delta = 0; } next_bcn = ktime_add(hrtimer_get_expires(timer), ns_to_ktime(bcn_int * 1000)); tasklet_hrtimer_start(&data->beacon_timer, next_bcn, HRTIMER_MODE_ABS); out: return HRTIMER_NORESTART; } static const char * const hwsim_chanwidths[] = { [NL80211_CHAN_WIDTH_20_NOHT] = "noht", [NL80211_CHAN_WIDTH_20] = "ht20", [NL80211_CHAN_WIDTH_40] = "ht40", [NL80211_CHAN_WIDTH_80] = "vht80", [NL80211_CHAN_WIDTH_80P80] = "vht80p80", [NL80211_CHAN_WIDTH_160] = "vht160", }; static int mac80211_hwsim_config(struct ieee80211_hw *hw, u32 changed) { struct mac80211_hwsim_data *data = hw->priv; struct ieee80211_conf *conf = &hw->conf; static const char *smps_modes[IEEE80211_SMPS_NUM_MODES] = { [IEEE80211_SMPS_AUTOMATIC] = "auto", [IEEE80211_SMPS_OFF] = "off", [IEEE80211_SMPS_STATIC] = "static", [IEEE80211_SMPS_DYNAMIC] = "dynamic", }; int idx; if (conf->chandef.chan) wiphy_dbg(hw->wiphy, "%s (freq=%d(%d - %d)/%s idle=%d ps=%d smps=%s)\n", __func__, conf->chandef.chan->center_freq, conf->chandef.center_freq1, conf->chandef.center_freq2, hwsim_chanwidths[conf->chandef.width], !!(conf->flags & IEEE80211_CONF_IDLE), !!(conf->flags & IEEE80211_CONF_PS), smps_modes[conf->smps_mode]); else wiphy_dbg(hw->wiphy, "%s (freq=0 idle=%d ps=%d smps=%s)\n", __func__, !!(conf->flags & IEEE80211_CONF_IDLE), !!(conf->flags & IEEE80211_CONF_PS), smps_modes[conf->smps_mode]); data->idle = !!(conf->flags & IEEE80211_CONF_IDLE); WARN_ON(conf->chandef.chan && data->use_chanctx); mutex_lock(&data->mutex); if (data->scanning && conf->chandef.chan) { for (idx = 0; idx < ARRAY_SIZE(data->survey_data); idx++) { if (data->survey_data[idx].channel == data->channel) { data->survey_data[idx].start = data->survey_data[idx].next_start; data->survey_data[idx].end = jiffies; break; } } data->channel = conf->chandef.chan; for (idx = 0; idx < ARRAY_SIZE(data->survey_data); idx++) { if (data->survey_data[idx].channel && data->survey_data[idx].channel != data->channel) continue; data->survey_data[idx].channel = data->channel; data->survey_data[idx].next_start = jiffies; break; } } else { data->channel = conf->chandef.chan; } mutex_unlock(&data->mutex); if (!data->started || !data->beacon_int) tasklet_hrtimer_cancel(&data->beacon_timer); else if (!hrtimer_is_queued(&data->beacon_timer.timer)) { u64 tsf = mac80211_hwsim_get_tsf(hw, NULL); u32 bcn_int = data->beacon_int; u64 until_tbtt = bcn_int - do_div(tsf, bcn_int); tasklet_hrtimer_start(&data->beacon_timer, ns_to_ktime(until_tbtt * 1000), HRTIMER_MODE_REL); } return 0; } static void mac80211_hwsim_configure_filter(struct ieee80211_hw *hw, unsigned int changed_flags, unsigned int *total_flags,u64 multicast) { struct mac80211_hwsim_data *data = hw->priv; wiphy_dbg(hw->wiphy, "%s\n", __func__); data->rx_filter = 0; if (*total_flags & FIF_ALLMULTI) data->rx_filter |= FIF_ALLMULTI; *total_flags = data->rx_filter; } static void mac80211_hwsim_bcn_en_iter(void *data, u8 *mac, struct ieee80211_vif *vif) { unsigned int *count = data; struct hwsim_vif_priv *vp = (void *)vif->drv_priv; if (vp->bcn_en) (*count)++; } static void mac80211_hwsim_bss_info_changed(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_bss_conf *info, u32 changed) { struct hwsim_vif_priv *vp = (void *)vif->drv_priv; struct mac80211_hwsim_data *data = hw->priv; hwsim_check_magic(vif); wiphy_dbg(hw->wiphy, "%s(changed=0x%x vif->addr=%pM)\n", __func__, changed, vif->addr); if (changed & BSS_CHANGED_BSSID) { wiphy_dbg(hw->wiphy, "%s: BSSID changed: %pM\n", __func__, info->bssid); memcpy(vp->bssid, info->bssid, ETH_ALEN); } if (changed & BSS_CHANGED_ASSOC) { wiphy_dbg(hw->wiphy, " ASSOC: assoc=%d aid=%d\n", info->assoc, info->aid); vp->assoc = info->assoc; vp->aid = info->aid; } if (changed & BSS_CHANGED_BEACON_ENABLED) { wiphy_dbg(hw->wiphy, " BCN EN: %d (BI=%u)\n", info->enable_beacon, info->beacon_int); vp->bcn_en = info->enable_beacon; if (data->started && !hrtimer_is_queued(&data->beacon_timer.timer) && info->enable_beacon) { u64 tsf, until_tbtt; u32 bcn_int; data->beacon_int = info->beacon_int * 1024; tsf = mac80211_hwsim_get_tsf(hw, vif); bcn_int = data->beacon_int; until_tbtt = bcn_int - do_div(tsf, bcn_int); tasklet_hrtimer_start(&data->beacon_timer, ns_to_ktime(until_tbtt * 1000), HRTIMER_MODE_REL); } else if (!info->enable_beacon) { unsigned int count = 0; ieee80211_iterate_active_interfaces_atomic( data->hw, IEEE80211_IFACE_ITER_NORMAL, mac80211_hwsim_bcn_en_iter, &count); wiphy_dbg(hw->wiphy, " beaconing vifs remaining: %u", count); if (count == 0) { tasklet_hrtimer_cancel(&data->beacon_timer); data->beacon_int = 0; } } } if (changed & BSS_CHANGED_ERP_CTS_PROT) { wiphy_dbg(hw->wiphy, " ERP_CTS_PROT: %d\n", info->use_cts_prot); } if (changed & BSS_CHANGED_ERP_PREAMBLE) { wiphy_dbg(hw->wiphy, " ERP_PREAMBLE: %d\n", info->use_short_preamble); } if (changed & BSS_CHANGED_ERP_SLOT) { wiphy_dbg(hw->wiphy, " ERP_SLOT: %d\n", info->use_short_slot); } if (changed & BSS_CHANGED_HT) { wiphy_dbg(hw->wiphy, " HT: op_mode=0x%x\n", info->ht_operation_mode); } if (changed & BSS_CHANGED_BASIC_RATES) { wiphy_dbg(hw->wiphy, " BASIC_RATES: 0x%llx\n", (unsigned long long) info->basic_rates); } if (changed & BSS_CHANGED_TXPOWER) wiphy_dbg(hw->wiphy, " TX Power: %d dBm\n", info->txpower); } static int mac80211_hwsim_sta_add(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta) { hwsim_check_magic(vif); hwsim_set_sta_magic(sta); return 0; } static int mac80211_hwsim_sta_remove(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta) { hwsim_check_magic(vif); hwsim_clear_sta_magic(sta); return 0; } static void mac80211_hwsim_sta_notify(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum sta_notify_cmd cmd, struct ieee80211_sta *sta) { hwsim_check_magic(vif); switch (cmd) { case STA_NOTIFY_SLEEP: case STA_NOTIFY_AWAKE: /* TODO: make good use of these flags */ break; default: WARN(1, "Invalid sta notify: %d\n", cmd); break; } } static int mac80211_hwsim_set_tim(struct ieee80211_hw *hw, struct ieee80211_sta *sta, bool set) { hwsim_check_sta_magic(sta); return 0; } static int mac80211_hwsim_conf_tx( struct ieee80211_hw *hw, struct ieee80211_vif *vif, u16 queue, const struct ieee80211_tx_queue_params *params) { wiphy_dbg(hw->wiphy, "%s (queue=%d txop=%d cw_min=%d cw_max=%d aifs=%d)\n", __func__, queue, params->txop, params->cw_min, params->cw_max, params->aifs); return 0; } static int mac80211_hwsim_get_survey(struct ieee80211_hw *hw, int idx, struct survey_info *survey) { struct mac80211_hwsim_data *hwsim = hw->priv; if (idx < 0 || idx >= ARRAY_SIZE(hwsim->survey_data)) return -ENOENT; mutex_lock(&hwsim->mutex); survey->channel = hwsim->survey_data[idx].channel; if (!survey->channel) { mutex_unlock(&hwsim->mutex); return -ENOENT; } /* * Magically conjured dummy values --- this is only ok for simulated hardware. * * A real driver which cannot determine real values noise MUST NOT * report any, especially not a magically conjured ones :-) */ survey->filled = SURVEY_INFO_NOISE_DBM | SURVEY_INFO_TIME | SURVEY_INFO_TIME_BUSY; survey->noise = -92; survey->time = jiffies_to_msecs(hwsim->survey_data[idx].end - hwsim->survey_data[idx].start); /* report 12.5% of channel time is used */ survey->time_busy = survey->time/8; mutex_unlock(&hwsim->mutex); return 0; } #ifdef CONFIG_NL80211_TESTMODE /* * This section contains example code for using netlink * attributes with the testmode command in nl80211. */ /* These enums need to be kept in sync with userspace */ enum hwsim_testmode_attr { __HWSIM_TM_ATTR_INVALID = 0, HWSIM_TM_ATTR_CMD = 1, HWSIM_TM_ATTR_PS = 2, /* keep last */ __HWSIM_TM_ATTR_AFTER_LAST, HWSIM_TM_ATTR_MAX = __HWSIM_TM_ATTR_AFTER_LAST - 1 }; enum hwsim_testmode_cmd { HWSIM_TM_CMD_SET_PS = 0, HWSIM_TM_CMD_GET_PS = 1, HWSIM_TM_CMD_STOP_QUEUES = 2, HWSIM_TM_CMD_WAKE_QUEUES = 3, }; static const struct nla_policy hwsim_testmode_policy[HWSIM_TM_ATTR_MAX + 1] = { [HWSIM_TM_ATTR_CMD] = { .type = NLA_U32 }, [HWSIM_TM_ATTR_PS] = { .type = NLA_U32 }, }; static int mac80211_hwsim_testmode_cmd(struct ieee80211_hw *hw, struct ieee80211_vif *vif, void *data, int len) { struct mac80211_hwsim_data *hwsim = hw->priv; struct nlattr *tb[HWSIM_TM_ATTR_MAX + 1]; struct sk_buff *skb; int err, ps; err = nla_parse(tb, HWSIM_TM_ATTR_MAX, data, len, hwsim_testmode_policy, NULL); if (err) return err; if (!tb[HWSIM_TM_ATTR_CMD]) return -EINVAL; switch (nla_get_u32(tb[HWSIM_TM_ATTR_CMD])) { case HWSIM_TM_CMD_SET_PS: if (!tb[HWSIM_TM_ATTR_PS]) return -EINVAL; ps = nla_get_u32(tb[HWSIM_TM_ATTR_PS]); return hwsim_fops_ps_write(hwsim, ps); case HWSIM_TM_CMD_GET_PS: skb = cfg80211_testmode_alloc_reply_skb(hw->wiphy, nla_total_size(sizeof(u32))); if (!skb) return -ENOMEM; if (nla_put_u32(skb, HWSIM_TM_ATTR_PS, hwsim->ps)) goto nla_put_failure; return cfg80211_testmode_reply(skb); case HWSIM_TM_CMD_STOP_QUEUES: ieee80211_stop_queues(hw); return 0; case HWSIM_TM_CMD_WAKE_QUEUES: ieee80211_wake_queues(hw); return 0; default: return -EOPNOTSUPP; } nla_put_failure: kfree_skb(skb); return -ENOBUFS; } #endif static int mac80211_hwsim_ampdu_action(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_ampdu_params *params) { struct ieee80211_sta *sta = params->sta; enum ieee80211_ampdu_mlme_action action = params->action; u16 tid = params->tid; switch (action) { case IEEE80211_AMPDU_TX_START: ieee80211_start_tx_ba_cb_irqsafe(vif, sta->addr, tid); break; case IEEE80211_AMPDU_TX_STOP_CONT: case IEEE80211_AMPDU_TX_STOP_FLUSH: case IEEE80211_AMPDU_TX_STOP_FLUSH_CONT: ieee80211_stop_tx_ba_cb_irqsafe(vif, sta->addr, tid); break; case IEEE80211_AMPDU_TX_OPERATIONAL: break; case IEEE80211_AMPDU_RX_START: case IEEE80211_AMPDU_RX_STOP: break; default: return -EOPNOTSUPP; } return 0; } static void mac80211_hwsim_flush(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u32 queues, bool drop) { /* Not implemented, queues only on kernel side */ } static void hw_scan_work(struct work_struct *work) { struct mac80211_hwsim_data *hwsim = container_of(work, struct mac80211_hwsim_data, hw_scan.work); struct cfg80211_scan_request *req = hwsim->hw_scan_request; int dwell, i; mutex_lock(&hwsim->mutex); if (hwsim->scan_chan_idx >= req->n_channels) { struct cfg80211_scan_info info = { .aborted = false, }; wiphy_dbg(hwsim->hw->wiphy, "hw scan complete\n"); ieee80211_scan_completed(hwsim->hw, &info); hwsim->hw_scan_request = NULL; hwsim->hw_scan_vif = NULL; hwsim->tmp_chan = NULL; mutex_unlock(&hwsim->mutex); return; } wiphy_dbg(hwsim->hw->wiphy, "hw scan %d MHz\n", req->channels[hwsim->scan_chan_idx]->center_freq); hwsim->tmp_chan = req->channels[hwsim->scan_chan_idx]; if (hwsim->tmp_chan->flags & (IEEE80211_CHAN_NO_IR | IEEE80211_CHAN_RADAR) || !req->n_ssids) { dwell = 120; } else { dwell = 30; /* send probes */ for (i = 0; i < req->n_ssids; i++) { struct sk_buff *probe; struct ieee80211_mgmt *mgmt; probe = ieee80211_probereq_get(hwsim->hw, hwsim->scan_addr, req->ssids[i].ssid, req->ssids[i].ssid_len, req->ie_len); if (!probe) continue; mgmt = (struct ieee80211_mgmt *) probe->data; memcpy(mgmt->da, req->bssid, ETH_ALEN); memcpy(mgmt->bssid, req->bssid, ETH_ALEN); if (req->ie_len) skb_put_data(probe, req->ie, req->ie_len); local_bh_disable(); mac80211_hwsim_tx_frame(hwsim->hw, probe, hwsim->tmp_chan); local_bh_enable(); } } ieee80211_queue_delayed_work(hwsim->hw, &hwsim->hw_scan, msecs_to_jiffies(dwell)); hwsim->survey_data[hwsim->scan_chan_idx].channel = hwsim->tmp_chan; hwsim->survey_data[hwsim->scan_chan_idx].start = jiffies; hwsim->survey_data[hwsim->scan_chan_idx].end = jiffies + msecs_to_jiffies(dwell); hwsim->scan_chan_idx++; mutex_unlock(&hwsim->mutex); } static int mac80211_hwsim_hw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_scan_request *hw_req) { struct mac80211_hwsim_data *hwsim = hw->priv; struct cfg80211_scan_request *req = &hw_req->req; mutex_lock(&hwsim->mutex); if (WARN_ON(hwsim->tmp_chan || hwsim->hw_scan_request)) { mutex_unlock(&hwsim->mutex); return -EBUSY; } hwsim->hw_scan_request = req; hwsim->hw_scan_vif = vif; hwsim->scan_chan_idx = 0; if (req->flags & NL80211_SCAN_FLAG_RANDOM_ADDR) get_random_mask_addr(hwsim->scan_addr, hw_req->req.mac_addr, hw_req->req.mac_addr_mask); else memcpy(hwsim->scan_addr, vif->addr, ETH_ALEN); memset(hwsim->survey_data, 0, sizeof(hwsim->survey_data)); mutex_unlock(&hwsim->mutex); wiphy_dbg(hw->wiphy, "hwsim hw_scan request\n"); ieee80211_queue_delayed_work(hwsim->hw, &hwsim->hw_scan, 0); return 0; } static void mac80211_hwsim_cancel_hw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct mac80211_hwsim_data *hwsim = hw->priv; struct cfg80211_scan_info info = { .aborted = true, }; wiphy_dbg(hw->wiphy, "hwsim cancel_hw_scan\n"); cancel_delayed_work_sync(&hwsim->hw_scan); mutex_lock(&hwsim->mutex); ieee80211_scan_completed(hwsim->hw, &info); hwsim->tmp_chan = NULL; hwsim->hw_scan_request = NULL; hwsim->hw_scan_vif = NULL; mutex_unlock(&hwsim->mutex); } static void mac80211_hwsim_sw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const u8 *mac_addr) { struct mac80211_hwsim_data *hwsim = hw->priv; mutex_lock(&hwsim->mutex); if (hwsim->scanning) { pr_debug("two hwsim sw_scans detected!\n"); goto out; } pr_debug("hwsim sw_scan request, prepping stuff\n"); memcpy(hwsim->scan_addr, mac_addr, ETH_ALEN); hwsim->scanning = true; memset(hwsim->survey_data, 0, sizeof(hwsim->survey_data)); out: mutex_unlock(&hwsim->mutex); } static void mac80211_hwsim_sw_scan_complete(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct mac80211_hwsim_data *hwsim = hw->priv; mutex_lock(&hwsim->mutex); pr_debug("hwsim sw_scan_complete\n"); hwsim->scanning = false; eth_zero_addr(hwsim->scan_addr); mutex_unlock(&hwsim->mutex); } static void hw_roc_start(struct work_struct *work) { struct mac80211_hwsim_data *hwsim = container_of(work, struct mac80211_hwsim_data, roc_start.work); mutex_lock(&hwsim->mutex); wiphy_dbg(hwsim->hw->wiphy, "hwsim ROC begins\n"); hwsim->tmp_chan = hwsim->roc_chan; ieee80211_ready_on_channel(hwsim->hw); ieee80211_queue_delayed_work(hwsim->hw, &hwsim->roc_done, msecs_to_jiffies(hwsim->roc_duration)); mutex_unlock(&hwsim->mutex); } static void hw_roc_done(struct work_struct *work) { struct mac80211_hwsim_data *hwsim = container_of(work, struct mac80211_hwsim_data, roc_done.work); mutex_lock(&hwsim->mutex); ieee80211_remain_on_channel_expired(hwsim->hw); hwsim->tmp_chan = NULL; mutex_unlock(&hwsim->mutex); wiphy_dbg(hwsim->hw->wiphy, "hwsim ROC expired\n"); } static int mac80211_hwsim_roc(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_channel *chan, int duration, enum ieee80211_roc_type type) { struct mac80211_hwsim_data *hwsim = hw->priv; mutex_lock(&hwsim->mutex); if (WARN_ON(hwsim->tmp_chan || hwsim->hw_scan_request)) { mutex_unlock(&hwsim->mutex); return -EBUSY; } hwsim->roc_chan = chan; hwsim->roc_duration = duration; mutex_unlock(&hwsim->mutex); wiphy_dbg(hw->wiphy, "hwsim ROC (%d MHz, %d ms)\n", chan->center_freq, duration); ieee80211_queue_delayed_work(hw, &hwsim->roc_start, HZ/50); return 0; } static int mac80211_hwsim_croc(struct ieee80211_hw *hw) { struct mac80211_hwsim_data *hwsim = hw->priv; cancel_delayed_work_sync(&hwsim->roc_start); cancel_delayed_work_sync(&hwsim->roc_done); mutex_lock(&hwsim->mutex); hwsim->tmp_chan = NULL; mutex_unlock(&hwsim->mutex); wiphy_dbg(hw->wiphy, "hwsim ROC canceled\n"); return 0; } static int mac80211_hwsim_add_chanctx(struct ieee80211_hw *hw, struct ieee80211_chanctx_conf *ctx) { hwsim_set_chanctx_magic(ctx); wiphy_dbg(hw->wiphy, "add channel context control: %d MHz/width: %d/cfreqs:%d/%d MHz\n", ctx->def.chan->center_freq, ctx->def.width, ctx->def.center_freq1, ctx->def.center_freq2); return 0; } static void mac80211_hwsim_remove_chanctx(struct ieee80211_hw *hw, struct ieee80211_chanctx_conf *ctx) { wiphy_dbg(hw->wiphy, "remove channel context control: %d MHz/width: %d/cfreqs:%d/%d MHz\n", ctx->def.chan->center_freq, ctx->def.width, ctx->def.center_freq1, ctx->def.center_freq2); hwsim_check_chanctx_magic(ctx); hwsim_clear_chanctx_magic(ctx); } static void mac80211_hwsim_change_chanctx(struct ieee80211_hw *hw, struct ieee80211_chanctx_conf *ctx, u32 changed) { hwsim_check_chanctx_magic(ctx); wiphy_dbg(hw->wiphy, "change channel context control: %d MHz/width: %d/cfreqs:%d/%d MHz\n", ctx->def.chan->center_freq, ctx->def.width, ctx->def.center_freq1, ctx->def.center_freq2); } static int mac80211_hwsim_assign_vif_chanctx(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_chanctx_conf *ctx) { hwsim_check_magic(vif); hwsim_check_chanctx_magic(ctx); return 0; } static void mac80211_hwsim_unassign_vif_chanctx(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_chanctx_conf *ctx) { hwsim_check_magic(vif); hwsim_check_chanctx_magic(ctx); } static const char mac80211_hwsim_gstrings_stats[][ETH_GSTRING_LEN] = { "tx_pkts_nic", "tx_bytes_nic", "rx_pkts_nic", "rx_bytes_nic", "d_tx_dropped", "d_tx_failed", "d_ps_mode", "d_group", }; #define MAC80211_HWSIM_SSTATS_LEN ARRAY_SIZE(mac80211_hwsim_gstrings_stats) static void mac80211_hwsim_get_et_strings(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u32 sset, u8 *data) { if (sset == ETH_SS_STATS) memcpy(data, *mac80211_hwsim_gstrings_stats, sizeof(mac80211_hwsim_gstrings_stats)); } static int mac80211_hwsim_get_et_sset_count(struct ieee80211_hw *hw, struct ieee80211_vif *vif, int sset) { if (sset == ETH_SS_STATS) return MAC80211_HWSIM_SSTATS_LEN; return 0; } static void mac80211_hwsim_get_et_stats(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ethtool_stats *stats, u64 *data) { struct mac80211_hwsim_data *ar = hw->priv; int i = 0; data[i++] = ar->tx_pkts; data[i++] = ar->tx_bytes; data[i++] = ar->rx_pkts; data[i++] = ar->rx_bytes; data[i++] = ar->tx_dropped; data[i++] = ar->tx_failed; data[i++] = ar->ps; data[i++] = ar->group; WARN_ON(i != MAC80211_HWSIM_SSTATS_LEN); } #define HWSIM_COMMON_OPS \ .tx = mac80211_hwsim_tx, \ .start = mac80211_hwsim_start, \ .stop = mac80211_hwsim_stop, \ .add_interface = mac80211_hwsim_add_interface, \ .change_interface = mac80211_hwsim_change_interface, \ .remove_interface = mac80211_hwsim_remove_interface, \ .config = mac80211_hwsim_config, \ .configure_filter = mac80211_hwsim_configure_filter, \ .bss_info_changed = mac80211_hwsim_bss_info_changed, \ .sta_add = mac80211_hwsim_sta_add, \ .sta_remove = mac80211_hwsim_sta_remove, \ .sta_notify = mac80211_hwsim_sta_notify, \ .set_tim = mac80211_hwsim_set_tim, \ .conf_tx = mac80211_hwsim_conf_tx, \ .get_survey = mac80211_hwsim_get_survey, \ CFG80211_TESTMODE_CMD(mac80211_hwsim_testmode_cmd) \ .ampdu_action = mac80211_hwsim_ampdu_action, \ .flush = mac80211_hwsim_flush, \ .get_tsf = mac80211_hwsim_get_tsf, \ .set_tsf = mac80211_hwsim_set_tsf, \ .get_et_sset_count = mac80211_hwsim_get_et_sset_count, \ .get_et_stats = mac80211_hwsim_get_et_stats, \ .get_et_strings = mac80211_hwsim_get_et_strings, static const struct ieee80211_ops mac80211_hwsim_ops = { HWSIM_COMMON_OPS .sw_scan_start = mac80211_hwsim_sw_scan, .sw_scan_complete = mac80211_hwsim_sw_scan_complete, }; static const struct ieee80211_ops mac80211_hwsim_mchan_ops = { HWSIM_COMMON_OPS .hw_scan = mac80211_hwsim_hw_scan, .cancel_hw_scan = mac80211_hwsim_cancel_hw_scan, .sw_scan_start = NULL, .sw_scan_complete = NULL, .remain_on_channel = mac80211_hwsim_roc, .cancel_remain_on_channel = mac80211_hwsim_croc, .add_chanctx = mac80211_hwsim_add_chanctx, .remove_chanctx = mac80211_hwsim_remove_chanctx, .change_chanctx = mac80211_hwsim_change_chanctx, .assign_vif_chanctx = mac80211_hwsim_assign_vif_chanctx, .unassign_vif_chanctx = mac80211_hwsim_unassign_vif_chanctx, }; struct hwsim_new_radio_params { unsigned int channels; const char *reg_alpha2; const struct ieee80211_regdomain *regd; bool reg_strict; bool p2p_device; bool use_chanctx; bool destroy_on_close; const char *hwname; bool no_vif; }; static void hwsim_mcast_config_msg(struct sk_buff *mcast_skb, struct genl_info *info) { if (info) genl_notify(&hwsim_genl_family, mcast_skb, info, HWSIM_MCGRP_CONFIG, GFP_KERNEL); else genlmsg_multicast(&hwsim_genl_family, mcast_skb, 0, HWSIM_MCGRP_CONFIG, GFP_KERNEL); } static int append_radio_msg(struct sk_buff *skb, int id, struct hwsim_new_radio_params *param) { int ret; ret = nla_put_u32(skb, HWSIM_ATTR_RADIO_ID, id); if (ret < 0) return ret; if (param->channels) { ret = nla_put_u32(skb, HWSIM_ATTR_CHANNELS, param->channels); if (ret < 0) return ret; } if (param->reg_alpha2) { ret = nla_put(skb, HWSIM_ATTR_REG_HINT_ALPHA2, 2, param->reg_alpha2); if (ret < 0) return ret; } if (param->regd) { int i; for (i = 0; i < ARRAY_SIZE(hwsim_world_regdom_custom); i++) { if (hwsim_world_regdom_custom[i] != param->regd) continue; ret = nla_put_u32(skb, HWSIM_ATTR_REG_CUSTOM_REG, i); if (ret < 0) return ret; break; } } if (param->reg_strict) { ret = nla_put_flag(skb, HWSIM_ATTR_REG_STRICT_REG); if (ret < 0) return ret; } if (param->p2p_device) { ret = nla_put_flag(skb, HWSIM_ATTR_SUPPORT_P2P_DEVICE); if (ret < 0) return ret; } if (param->use_chanctx) { ret = nla_put_flag(skb, HWSIM_ATTR_USE_CHANCTX); if (ret < 0) return ret; } if (param->hwname) { ret = nla_put(skb, HWSIM_ATTR_RADIO_NAME, strlen(param->hwname), param->hwname); if (ret < 0) return ret; } return 0; } static void hwsim_mcast_new_radio(int id, struct genl_info *info, struct hwsim_new_radio_params *param) { struct sk_buff *mcast_skb; void *data; mcast_skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!mcast_skb) return; data = genlmsg_put(mcast_skb, 0, 0, &hwsim_genl_family, 0, HWSIM_CMD_NEW_RADIO); if (!data) goto out_err; if (append_radio_msg(mcast_skb, id, param) < 0) goto out_err; genlmsg_end(mcast_skb, data); hwsim_mcast_config_msg(mcast_skb, info); return; out_err: genlmsg_cancel(mcast_skb, data); nlmsg_free(mcast_skb); } static int mac80211_hwsim_new_radio(struct genl_info *info, struct hwsim_new_radio_params *param) { int err; u8 addr[ETH_ALEN]; struct mac80211_hwsim_data *data; struct ieee80211_hw *hw; enum nl80211_band band; const struct ieee80211_ops *ops = &mac80211_hwsim_ops; struct net *net; int idx; if (WARN_ON(param->channels > 1 && !param->use_chanctx)) return -EINVAL; spin_lock_bh(&hwsim_radio_lock); idx = hwsim_radio_idx++; spin_unlock_bh(&hwsim_radio_lock); if (param->use_chanctx) ops = &mac80211_hwsim_mchan_ops; hw = ieee80211_alloc_hw_nm(sizeof(*data), ops, param->hwname); if (!hw) { pr_debug("mac80211_hwsim: ieee80211_alloc_hw failed\n"); err = -ENOMEM; goto failed; } /* ieee80211_alloc_hw_nm may have used a default name */ param->hwname = wiphy_name(hw->wiphy); if (info) net = genl_info_net(info); else net = &init_net; wiphy_net_set(hw->wiphy, net); data = hw->priv; data->hw = hw; data->dev = device_create(hwsim_class, NULL, 0, hw, "hwsim%d", idx); if (IS_ERR(data->dev)) { printk(KERN_DEBUG "mac80211_hwsim: device_create failed (%ld)\n", PTR_ERR(data->dev)); err = -ENOMEM; goto failed_drvdata; } data->dev->driver = &mac80211_hwsim_driver.driver; err = device_bind_driver(data->dev); if (err != 0) { pr_debug("mac80211_hwsim: device_bind_driver failed (%d)\n", err); goto failed_bind; } skb_queue_head_init(&data->pending); SET_IEEE80211_DEV(hw, data->dev); eth_zero_addr(addr); addr[0] = 0x02; addr[3] = idx >> 8; addr[4] = idx; memcpy(data->addresses[0].addr, addr, ETH_ALEN); memcpy(data->addresses[1].addr, addr, ETH_ALEN); data->addresses[1].addr[0] |= 0x40; hw->wiphy->n_addresses = 2; hw->wiphy->addresses = data->addresses; data->channels = param->channels; data->use_chanctx = param->use_chanctx; data->idx = idx; data->destroy_on_close = param->destroy_on_close; if (info) data->portid = info->snd_portid; if (data->use_chanctx) { hw->wiphy->max_scan_ssids = 255; hw->wiphy->max_scan_ie_len = IEEE80211_MAX_DATA_LEN; hw->wiphy->max_remain_on_channel_duration = 1000; hw->wiphy->iface_combinations = &data->if_combination; if (param->p2p_device) data->if_combination = hwsim_if_comb_p2p_dev[0]; else data->if_combination = hwsim_if_comb[0]; hw->wiphy->n_iface_combinations = 1; /* For channels > 1 DFS is not allowed */ data->if_combination.radar_detect_widths = 0; data->if_combination.num_different_channels = data->channels; } else if (param->p2p_device) { hw->wiphy->iface_combinations = hwsim_if_comb_p2p_dev; hw->wiphy->n_iface_combinations = ARRAY_SIZE(hwsim_if_comb_p2p_dev); } else { hw->wiphy->iface_combinations = hwsim_if_comb; hw->wiphy->n_iface_combinations = ARRAY_SIZE(hwsim_if_comb); } INIT_DELAYED_WORK(&data->roc_start, hw_roc_start); INIT_DELAYED_WORK(&data->roc_done, hw_roc_done); INIT_DELAYED_WORK(&data->hw_scan, hw_scan_work); hw->queues = 5; hw->offchannel_tx_hw_queue = 4; hw->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) | BIT(NL80211_IFTYPE_AP) | BIT(NL80211_IFTYPE_P2P_CLIENT) | BIT(NL80211_IFTYPE_P2P_GO) | BIT(NL80211_IFTYPE_ADHOC) | BIT(NL80211_IFTYPE_MESH_POINT); if (param->p2p_device) hw->wiphy->interface_modes |= BIT(NL80211_IFTYPE_P2P_DEVICE); ieee80211_hw_set(hw, SUPPORT_FAST_XMIT); ieee80211_hw_set(hw, CHANCTX_STA_CSA); ieee80211_hw_set(hw, SUPPORTS_HT_CCK_RATES); ieee80211_hw_set(hw, QUEUE_CONTROL); ieee80211_hw_set(hw, WANT_MONITOR_VIF); ieee80211_hw_set(hw, AMPDU_AGGREGATION); ieee80211_hw_set(hw, MFP_CAPABLE); ieee80211_hw_set(hw, SIGNAL_DBM); ieee80211_hw_set(hw, TDLS_WIDER_BW); if (rctbl) ieee80211_hw_set(hw, SUPPORTS_RC_TABLE); hw->wiphy->flags |= WIPHY_FLAG_SUPPORTS_TDLS | WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL | WIPHY_FLAG_AP_UAPSD | WIPHY_FLAG_HAS_CHANNEL_SWITCH; hw->wiphy->features |= NL80211_FEATURE_ACTIVE_MONITOR | NL80211_FEATURE_AP_MODE_CHAN_WIDTH_CHANGE | NL80211_FEATURE_STATIC_SMPS | NL80211_FEATURE_DYNAMIC_SMPS | NL80211_FEATURE_SCAN_RANDOM_MAC_ADDR; wiphy_ext_feature_set(hw->wiphy, NL80211_EXT_FEATURE_VHT_IBSS); /* ask mac80211 to reserve space for magic */ hw->vif_data_size = sizeof(struct hwsim_vif_priv); hw->sta_data_size = sizeof(struct hwsim_sta_priv); hw->chanctx_data_size = sizeof(struct hwsim_chanctx_priv); memcpy(data->channels_2ghz, hwsim_channels_2ghz, sizeof(hwsim_channels_2ghz)); memcpy(data->channels_5ghz, hwsim_channels_5ghz, sizeof(hwsim_channels_5ghz)); memcpy(data->rates, hwsim_rates, sizeof(hwsim_rates)); for (band = NL80211_BAND_2GHZ; band < NUM_NL80211_BANDS; band++) { struct ieee80211_supported_band *sband = &data->bands[band]; switch (band) { case NL80211_BAND_2GHZ: sband->channels = data->channels_2ghz; sband->n_channels = ARRAY_SIZE(hwsim_channels_2ghz); sband->bitrates = data->rates; sband->n_bitrates = ARRAY_SIZE(hwsim_rates); break; case NL80211_BAND_5GHZ: sband->channels = data->channels_5ghz; sband->n_channels = ARRAY_SIZE(hwsim_channels_5ghz); sband->bitrates = data->rates + 4; sband->n_bitrates = ARRAY_SIZE(hwsim_rates) - 4; sband->vht_cap.vht_supported = true; sband->vht_cap.cap = IEEE80211_VHT_CAP_MAX_MPDU_LENGTH_11454 | IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160_80PLUS80MHZ | IEEE80211_VHT_CAP_RXLDPC | IEEE80211_VHT_CAP_SHORT_GI_80 | IEEE80211_VHT_CAP_SHORT_GI_160 | IEEE80211_VHT_CAP_TXSTBC | IEEE80211_VHT_CAP_RXSTBC_1 | IEEE80211_VHT_CAP_RXSTBC_2 | IEEE80211_VHT_CAP_RXSTBC_3 | IEEE80211_VHT_CAP_RXSTBC_4 | IEEE80211_VHT_CAP_MAX_A_MPDU_LENGTH_EXPONENT_MASK; sband->vht_cap.vht_mcs.rx_mcs_map = cpu_to_le16(IEEE80211_VHT_MCS_SUPPORT_0_9 << 0 | IEEE80211_VHT_MCS_SUPPORT_0_9 << 2 | IEEE80211_VHT_MCS_SUPPORT_0_9 << 4 | IEEE80211_VHT_MCS_SUPPORT_0_9 << 6 | IEEE80211_VHT_MCS_SUPPORT_0_9 << 8 | IEEE80211_VHT_MCS_SUPPORT_0_9 << 10 | IEEE80211_VHT_MCS_SUPPORT_0_9 << 12 | IEEE80211_VHT_MCS_SUPPORT_0_9 << 14); sband->vht_cap.vht_mcs.tx_mcs_map = sband->vht_cap.vht_mcs.rx_mcs_map; break; default: continue; } sband->ht_cap.ht_supported = true; sband->ht_cap.cap = IEEE80211_HT_CAP_SUP_WIDTH_20_40 | IEEE80211_HT_CAP_GRN_FLD | IEEE80211_HT_CAP_SGI_20 | IEEE80211_HT_CAP_SGI_40 | IEEE80211_HT_CAP_DSSSCCK40; sband->ht_cap.ampdu_factor = 0x3; sband->ht_cap.ampdu_density = 0x6; memset(&sband->ht_cap.mcs, 0, sizeof(sband->ht_cap.mcs)); sband->ht_cap.mcs.rx_mask[0] = 0xff; sband->ht_cap.mcs.rx_mask[1] = 0xff; sband->ht_cap.mcs.tx_params = IEEE80211_HT_MCS_TX_DEFINED; hw->wiphy->bands[band] = sband; } /* By default all radios belong to the first group */ data->group = 1; mutex_init(&data->mutex); data->netgroup = hwsim_net_get_netgroup(net); /* Enable frame retransmissions for lossy channels */ hw->max_rates = 4; hw->max_rate_tries = 11; hw->wiphy->vendor_commands = mac80211_hwsim_vendor_commands; hw->wiphy->n_vendor_commands = ARRAY_SIZE(mac80211_hwsim_vendor_commands); hw->wiphy->vendor_events = mac80211_hwsim_vendor_events; hw->wiphy->n_vendor_events = ARRAY_SIZE(mac80211_hwsim_vendor_events); if (param->reg_strict) hw->wiphy->regulatory_flags |= REGULATORY_STRICT_REG; if (param->regd) { data->regd = param->regd; hw->wiphy->regulatory_flags |= REGULATORY_CUSTOM_REG; wiphy_apply_custom_regulatory(hw->wiphy, param->regd); /* give the regulatory workqueue a chance to run */ schedule_timeout_interruptible(1); } if (param->no_vif) ieee80211_hw_set(hw, NO_AUTO_VIF); wiphy_ext_feature_set(hw->wiphy, NL80211_EXT_FEATURE_CQM_RSSI_LIST); err = ieee80211_register_hw(hw); if (err < 0) { pr_debug("mac80211_hwsim: ieee80211_register_hw failed (%d)\n", err); goto failed_hw; } wiphy_dbg(hw->wiphy, "hwaddr %pM registered\n", hw->wiphy->perm_addr); if (param->reg_alpha2) { data->alpha2[0] = param->reg_alpha2[0]; data->alpha2[1] = param->reg_alpha2[1]; regulatory_hint(hw->wiphy, param->reg_alpha2); } data->debugfs = debugfs_create_dir("hwsim", hw->wiphy->debugfsdir); debugfs_create_file("ps", 0666, data->debugfs, data, &hwsim_fops_ps); debugfs_create_file("group", 0666, data->debugfs, data, &hwsim_fops_group); if (!data->use_chanctx) debugfs_create_file("dfs_simulate_radar", 0222, data->debugfs, data, &hwsim_simulate_radar); tasklet_hrtimer_init(&data->beacon_timer, mac80211_hwsim_beacon, CLOCK_MONOTONIC, HRTIMER_MODE_ABS); spin_lock_bh(&hwsim_radio_lock); err = rhashtable_insert_fast(&hwsim_radios_rht, &data->rht, hwsim_rht_params); if (err < 0) { pr_debug("mac80211_hwsim: radio index %d already present\n", idx); spin_unlock_bh(&hwsim_radio_lock); goto failed_final_insert; } list_add_tail(&data->list, &hwsim_radios); spin_unlock_bh(&hwsim_radio_lock); if (idx > 0) hwsim_mcast_new_radio(idx, info, param); return idx; failed_final_insert: debugfs_remove_recursive(data->debugfs); ieee80211_unregister_hw(data->hw); failed_hw: device_release_driver(data->dev); failed_bind: device_unregister(data->dev); failed_drvdata: ieee80211_free_hw(hw); failed: return err; } static void hwsim_mcast_del_radio(int id, const char *hwname, struct genl_info *info) { struct sk_buff *skb; void *data; int ret; skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!skb) return; data = genlmsg_put(skb, 0, 0, &hwsim_genl_family, 0, HWSIM_CMD_DEL_RADIO); if (!data) goto error; ret = nla_put_u32(skb, HWSIM_ATTR_RADIO_ID, id); if (ret < 0) goto error; ret = nla_put(skb, HWSIM_ATTR_RADIO_NAME, strlen(hwname), hwname); if (ret < 0) goto error; genlmsg_end(skb, data); hwsim_mcast_config_msg(skb, info); return; error: nlmsg_free(skb); } static void mac80211_hwsim_del_radio(struct mac80211_hwsim_data *data, const char *hwname, struct genl_info *info) { hwsim_mcast_del_radio(data->idx, hwname, info); debugfs_remove_recursive(data->debugfs); ieee80211_unregister_hw(data->hw); device_release_driver(data->dev); device_unregister(data->dev); ieee80211_free_hw(data->hw); } static int mac80211_hwsim_get_radio(struct sk_buff *skb, struct mac80211_hwsim_data *data, u32 portid, u32 seq, struct netlink_callback *cb, int flags) { void *hdr; struct hwsim_new_radio_params param = { }; int res = -EMSGSIZE; hdr = genlmsg_put(skb, portid, seq, &hwsim_genl_family, flags, HWSIM_CMD_GET_RADIO); if (!hdr) return -EMSGSIZE; if (cb) genl_dump_check_consistent(cb, hdr); if (data->alpha2[0] && data->alpha2[1]) param.reg_alpha2 = data->alpha2; param.reg_strict = !!(data->hw->wiphy->regulatory_flags & REGULATORY_STRICT_REG); param.p2p_device = !!(data->hw->wiphy->interface_modes & BIT(NL80211_IFTYPE_P2P_DEVICE)); param.use_chanctx = data->use_chanctx; param.regd = data->regd; param.channels = data->channels; param.hwname = wiphy_name(data->hw->wiphy); res = append_radio_msg(skb, data->idx, &param); if (res < 0) goto out_err; genlmsg_end(skb, hdr); return 0; out_err: genlmsg_cancel(skb, hdr); return res; } static void mac80211_hwsim_free(void) { struct mac80211_hwsim_data *data; spin_lock_bh(&hwsim_radio_lock); while ((data = list_first_entry_or_null(&hwsim_radios, struct mac80211_hwsim_data, list))) { list_del(&data->list); spin_unlock_bh(&hwsim_radio_lock); mac80211_hwsim_del_radio(data, wiphy_name(data->hw->wiphy), NULL); spin_lock_bh(&hwsim_radio_lock); } spin_unlock_bh(&hwsim_radio_lock); class_destroy(hwsim_class); } static const struct net_device_ops hwsim_netdev_ops = { .ndo_start_xmit = hwsim_mon_xmit, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, }; static void hwsim_mon_setup(struct net_device *dev) { dev->netdev_ops = &hwsim_netdev_ops; dev->needs_free_netdev = true; ether_setup(dev); dev->priv_flags |= IFF_NO_QUEUE; dev->type = ARPHRD_IEEE80211_RADIOTAP; eth_zero_addr(dev->dev_addr); dev->dev_addr[0] = 0x12; } static struct mac80211_hwsim_data *get_hwsim_data_ref_from_addr(const u8 *addr) { return rhashtable_lookup_fast(&hwsim_radios_rht, addr, hwsim_rht_params); } static void hwsim_register_wmediumd(struct net *net, u32 portid) { struct mac80211_hwsim_data *data; hwsim_net_set_wmediumd(net, portid); spin_lock_bh(&hwsim_radio_lock); list_for_each_entry(data, &hwsim_radios, list) { if (data->netgroup == hwsim_net_get_netgroup(net)) data->wmediumd = portid; } spin_unlock_bh(&hwsim_radio_lock); } static int hwsim_tx_info_frame_received_nl(struct sk_buff *skb_2, struct genl_info *info) { struct ieee80211_hdr *hdr; struct mac80211_hwsim_data *data2; struct ieee80211_tx_info *txi; struct hwsim_tx_rate *tx_attempts; u64 ret_skb_cookie; struct sk_buff *skb, *tmp; const u8 *src; unsigned int hwsim_flags; int i; bool found = false; if (!info->attrs[HWSIM_ATTR_ADDR_TRANSMITTER] || !info->attrs[HWSIM_ATTR_FLAGS] || !info->attrs[HWSIM_ATTR_COOKIE] || !info->attrs[HWSIM_ATTR_SIGNAL] || !info->attrs[HWSIM_ATTR_TX_INFO]) goto out; src = (void *)nla_data(info->attrs[HWSIM_ATTR_ADDR_TRANSMITTER]); hwsim_flags = nla_get_u32(info->attrs[HWSIM_ATTR_FLAGS]); ret_skb_cookie = nla_get_u64(info->attrs[HWSIM_ATTR_COOKIE]); data2 = get_hwsim_data_ref_from_addr(src); if (!data2) goto out; if (hwsim_net_get_netgroup(genl_info_net(info)) != data2->netgroup) goto out; if (info->snd_portid != data2->wmediumd) goto out; /* look for the skb matching the cookie passed back from user */ skb_queue_walk_safe(&data2->pending, skb, tmp) { u64 skb_cookie; txi = IEEE80211_SKB_CB(skb); skb_cookie = (u64)(uintptr_t)txi->rate_driver_data[0]; if (skb_cookie == ret_skb_cookie) { skb_unlink(skb, &data2->pending); found = true; break; } } /* not found */ if (!found) goto out; /* Tx info received because the frame was broadcasted on user space, so we get all the necessary info: tx attempts and skb control buff */ tx_attempts = (struct hwsim_tx_rate *)nla_data( info->attrs[HWSIM_ATTR_TX_INFO]); /* now send back TX status */ txi = IEEE80211_SKB_CB(skb); ieee80211_tx_info_clear_status(txi); for (i = 0; i < IEEE80211_TX_MAX_RATES; i++) { txi->status.rates[i].idx = tx_attempts[i].idx; txi->status.rates[i].count = tx_attempts[i].count; } txi->status.ack_signal = nla_get_u32(info->attrs[HWSIM_ATTR_SIGNAL]); if (!(hwsim_flags & HWSIM_TX_CTL_NO_ACK) && (hwsim_flags & HWSIM_TX_STAT_ACK)) { if (skb->len >= 16) { hdr = (struct ieee80211_hdr *) skb->data; mac80211_hwsim_monitor_ack(data2->channel, hdr->addr2); } txi->flags |= IEEE80211_TX_STAT_ACK; } ieee80211_tx_status_irqsafe(data2->hw, skb); return 0; out: return -EINVAL; } static int hwsim_cloned_frame_received_nl(struct sk_buff *skb_2, struct genl_info *info) { struct mac80211_hwsim_data *data2; struct ieee80211_rx_status rx_status; const u8 *dst; int frame_data_len; void *frame_data; struct sk_buff *skb = NULL; if (!info->attrs[HWSIM_ATTR_ADDR_RECEIVER] || !info->attrs[HWSIM_ATTR_FRAME] || !info->attrs[HWSIM_ATTR_RX_RATE] || !info->attrs[HWSIM_ATTR_SIGNAL]) goto out; dst = (void *)nla_data(info->attrs[HWSIM_ATTR_ADDR_RECEIVER]); frame_data_len = nla_len(info->attrs[HWSIM_ATTR_FRAME]); frame_data = (void *)nla_data(info->attrs[HWSIM_ATTR_FRAME]); /* Allocate new skb here */ skb = alloc_skb(frame_data_len, GFP_KERNEL); if (skb == NULL) goto err; if (frame_data_len > IEEE80211_MAX_DATA_LEN) goto err; /* Copy the data */ skb_put_data(skb, frame_data, frame_data_len); data2 = get_hwsim_data_ref_from_addr(dst); if (!data2) goto out; if (hwsim_net_get_netgroup(genl_info_net(info)) != data2->netgroup) goto out; if (info->snd_portid != data2->wmediumd) goto out; /* check if radio is configured properly */ if (data2->idle || !data2->started) goto out; /* A frame is received from user space */ memset(&rx_status, 0, sizeof(rx_status)); if (info->attrs[HWSIM_ATTR_FREQ]) { /* throw away off-channel packets, but allow both the temporary * ("hw" scan/remain-on-channel) and regular channel, since the * internal datapath also allows this */ mutex_lock(&data2->mutex); rx_status.freq = nla_get_u32(info->attrs[HWSIM_ATTR_FREQ]); if (rx_status.freq != data2->channel->center_freq && (!data2->tmp_chan || rx_status.freq != data2->tmp_chan->center_freq)) { mutex_unlock(&data2->mutex); goto out; } mutex_unlock(&data2->mutex); } else { rx_status.freq = data2->channel->center_freq; } rx_status.band = data2->channel->band; rx_status.rate_idx = nla_get_u32(info->attrs[HWSIM_ATTR_RX_RATE]); rx_status.signal = nla_get_u32(info->attrs[HWSIM_ATTR_SIGNAL]); memcpy(IEEE80211_SKB_RXCB(skb), &rx_status, sizeof(rx_status)); data2->rx_pkts++; data2->rx_bytes += skb->len; ieee80211_rx_irqsafe(data2->hw, skb); return 0; err: pr_debug("mac80211_hwsim: error occurred in %s\n", __func__); out: dev_kfree_skb(skb); return -EINVAL; } static int hwsim_register_received_nl(struct sk_buff *skb_2, struct genl_info *info) { struct net *net = genl_info_net(info); struct mac80211_hwsim_data *data; int chans = 1; spin_lock_bh(&hwsim_radio_lock); list_for_each_entry(data, &hwsim_radios, list) chans = max(chans, data->channels); spin_unlock_bh(&hwsim_radio_lock); /* In the future we should revise the userspace API and allow it * to set a flag that it does support multi-channel, then we can * let this pass conditionally on the flag. * For current userspace, prohibit it since it won't work right. */ if (chans > 1) return -EOPNOTSUPP; if (hwsim_net_get_wmediumd(net)) return -EBUSY; hwsim_register_wmediumd(net, info->snd_portid); pr_debug("mac80211_hwsim: received a REGISTER, " "switching to wmediumd mode with pid %d\n", info->snd_portid); return 0; } static int hwsim_new_radio_nl(struct sk_buff *msg, struct genl_info *info) { struct hwsim_new_radio_params param = { 0 }; const char *hwname = NULL; int ret; param.reg_strict = info->attrs[HWSIM_ATTR_REG_STRICT_REG]; param.p2p_device = info->attrs[HWSIM_ATTR_SUPPORT_P2P_DEVICE]; param.channels = channels; param.destroy_on_close = info->attrs[HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE]; if (info->attrs[HWSIM_ATTR_CHANNELS]) param.channels = nla_get_u32(info->attrs[HWSIM_ATTR_CHANNELS]); if (info->attrs[HWSIM_ATTR_NO_VIF]) param.no_vif = true; if (info->attrs[HWSIM_ATTR_RADIO_NAME]) { hwname = kasprintf(GFP_KERNEL, "%.*s", nla_len(info->attrs[HWSIM_ATTR_RADIO_NAME]), (char *)nla_data(info->attrs[HWSIM_ATTR_RADIO_NAME])); if (!hwname) return -ENOMEM; param.hwname = hwname; } if (info->attrs[HWSIM_ATTR_USE_CHANCTX]) param.use_chanctx = true; else param.use_chanctx = (param.channels > 1); if (info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2]) param.reg_alpha2 = nla_data(info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2]); if (info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]) { u32 idx = nla_get_u32(info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]); if (idx >= ARRAY_SIZE(hwsim_world_regdom_custom)) return -EINVAL; param.regd = hwsim_world_regdom_custom[idx]; } ret = mac80211_hwsim_new_radio(info, &param); kfree(hwname); return ret; } static int hwsim_del_radio_nl(struct sk_buff *msg, struct genl_info *info) { struct mac80211_hwsim_data *data; s64 idx = -1; const char *hwname = NULL; if (info->attrs[HWSIM_ATTR_RADIO_ID]) { idx = nla_get_u32(info->attrs[HWSIM_ATTR_RADIO_ID]); } else if (info->attrs[HWSIM_ATTR_RADIO_NAME]) { hwname = kasprintf(GFP_KERNEL, "%.*s", nla_len(info->attrs[HWSIM_ATTR_RADIO_NAME]), (char *)nla_data(info->attrs[HWSIM_ATTR_RADIO_NAME])); if (!hwname) return -ENOMEM; } else return -EINVAL; spin_lock_bh(&hwsim_radio_lock); list_for_each_entry(data, &hwsim_radios, list) { if (idx >= 0) { if (data->idx != idx) continue; } else { if (!hwname || strcmp(hwname, wiphy_name(data->hw->wiphy))) continue; } if (!net_eq(wiphy_net(data->hw->wiphy), genl_info_net(info))) continue; list_del(&data->list); rhashtable_remove_fast(&hwsim_radios_rht, &data->rht, hwsim_rht_params); spin_unlock_bh(&hwsim_radio_lock); mac80211_hwsim_del_radio(data, wiphy_name(data->hw->wiphy), info); kfree(hwname); return 0; } spin_unlock_bh(&hwsim_radio_lock); kfree(hwname); return -ENODEV; } static int hwsim_get_radio_nl(struct sk_buff *msg, struct genl_info *info) { struct mac80211_hwsim_data *data; struct sk_buff *skb; int idx, res = -ENODEV; if (!info->attrs[HWSIM_ATTR_RADIO_ID]) return -EINVAL; idx = nla_get_u32(info->attrs[HWSIM_ATTR_RADIO_ID]); spin_lock_bh(&hwsim_radio_lock); list_for_each_entry(data, &hwsim_radios, list) { if (data->idx != idx) continue; if (!net_eq(wiphy_net(data->hw->wiphy), genl_info_net(info))) continue; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!skb) { res = -ENOMEM; goto out_err; } res = mac80211_hwsim_get_radio(skb, data, info->snd_portid, info->snd_seq, NULL, 0); if (res < 0) { nlmsg_free(skb); goto out_err; } genlmsg_reply(skb, info); break; } out_err: spin_unlock_bh(&hwsim_radio_lock); return res; } static int hwsim_dump_radio_nl(struct sk_buff *skb, struct netlink_callback *cb) { int idx = cb->args[0]; struct mac80211_hwsim_data *data = NULL; int res; spin_lock_bh(&hwsim_radio_lock); if (idx == hwsim_radio_idx) goto done; list_for_each_entry(data, &hwsim_radios, list) { if (data->idx < idx) continue; if (!net_eq(wiphy_net(data->hw->wiphy), sock_net(skb->sk))) continue; res = mac80211_hwsim_get_radio(skb, data, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, cb, NLM_F_MULTI); if (res < 0) break; idx = data->idx + 1; } cb->args[0] = idx; done: spin_unlock_bh(&hwsim_radio_lock); return skb->len; } /* Generic Netlink operations array */ static const struct genl_ops hwsim_ops[] = { { .cmd = HWSIM_CMD_REGISTER, .policy = hwsim_genl_policy, .doit = hwsim_register_received_nl, .flags = GENL_UNS_ADMIN_PERM, }, { .cmd = HWSIM_CMD_FRAME, .policy = hwsim_genl_policy, .doit = hwsim_cloned_frame_received_nl, }, { .cmd = HWSIM_CMD_TX_INFO_FRAME, .policy = hwsim_genl_policy, .doit = hwsim_tx_info_frame_received_nl, }, { .cmd = HWSIM_CMD_NEW_RADIO, .policy = hwsim_genl_policy, .doit = hwsim_new_radio_nl, .flags = GENL_UNS_ADMIN_PERM, }, { .cmd = HWSIM_CMD_DEL_RADIO, .policy = hwsim_genl_policy, .doit = hwsim_del_radio_nl, .flags = GENL_UNS_ADMIN_PERM, }, { .cmd = HWSIM_CMD_GET_RADIO, .policy = hwsim_genl_policy, .doit = hwsim_get_radio_nl, .dumpit = hwsim_dump_radio_nl, }, }; static struct genl_family hwsim_genl_family __ro_after_init = { .name = "MAC80211_HWSIM", .version = 1, .maxattr = HWSIM_ATTR_MAX, .netnsok = true, .module = THIS_MODULE, .ops = hwsim_ops, .n_ops = ARRAY_SIZE(hwsim_ops), .mcgrps = hwsim_mcgrps, .n_mcgrps = ARRAY_SIZE(hwsim_mcgrps), }; static void destroy_radio(struct work_struct *work) { struct mac80211_hwsim_data *data = container_of(work, struct mac80211_hwsim_data, destroy_work); mac80211_hwsim_del_radio(data, wiphy_name(data->hw->wiphy), NULL); } static void remove_user_radios(u32 portid) { struct mac80211_hwsim_data *entry, *tmp; spin_lock_bh(&hwsim_radio_lock); list_for_each_entry_safe(entry, tmp, &hwsim_radios, list) { if (entry->destroy_on_close && entry->portid == portid) { list_del(&entry->list); rhashtable_remove_fast(&hwsim_radios_rht, &entry->rht, hwsim_rht_params); INIT_WORK(&entry->destroy_work, destroy_radio); schedule_work(&entry->destroy_work); } } spin_unlock_bh(&hwsim_radio_lock); } static int mac80211_hwsim_netlink_notify(struct notifier_block *nb, unsigned long state, void *_notify) { struct netlink_notify *notify = _notify; if (state != NETLINK_URELEASE) return NOTIFY_DONE; remove_user_radios(notify->portid); if (notify->portid == hwsim_net_get_wmediumd(notify->net)) { printk(KERN_INFO "mac80211_hwsim: wmediumd released netlink" " socket, switching to perfect channel medium\n"); hwsim_register_wmediumd(notify->net, 0); } return NOTIFY_DONE; } static struct notifier_block hwsim_netlink_notifier = { .notifier_call = mac80211_hwsim_netlink_notify, }; static int __init hwsim_init_netlink(void) { int rc; printk(KERN_INFO "mac80211_hwsim: initializing netlink\n"); rc = genl_register_family(&hwsim_genl_family); if (rc) goto failure; rc = netlink_register_notifier(&hwsim_netlink_notifier); if (rc) { genl_unregister_family(&hwsim_genl_family); goto failure; } return 0; failure: pr_debug("mac80211_hwsim: error occurred in %s\n", __func__); return -EINVAL; } static __net_init int hwsim_init_net(struct net *net) { hwsim_net_set_netgroup(net); return 0; } static void __net_exit hwsim_exit_net(struct net *net) { struct mac80211_hwsim_data *data, *tmp; spin_lock_bh(&hwsim_radio_lock); list_for_each_entry_safe(data, tmp, &hwsim_radios, list) { if (!net_eq(wiphy_net(data->hw->wiphy), net)) continue; /* Radios created in init_net are returned to init_net. */ if (data->netgroup == hwsim_net_get_netgroup(&init_net)) continue; list_del(&data->list); rhashtable_remove_fast(&hwsim_radios_rht, &data->rht, hwsim_rht_params); INIT_WORK(&data->destroy_work, destroy_radio); schedule_work(&data->destroy_work); } spin_unlock_bh(&hwsim_radio_lock); } static struct pernet_operations hwsim_net_ops = { .init = hwsim_init_net, .exit = hwsim_exit_net, .id = &hwsim_net_id, .size = sizeof(struct hwsim_net), }; static void hwsim_exit_netlink(void) { /* unregister the notifier */ netlink_unregister_notifier(&hwsim_netlink_notifier); /* unregister the family */ genl_unregister_family(&hwsim_genl_family); } static int __init init_mac80211_hwsim(void) { int i, err; if (radios < 0 || radios > 100) return -EINVAL; if (channels < 1) return -EINVAL; spin_lock_init(&hwsim_radio_lock); rhashtable_init(&hwsim_radios_rht, &hwsim_rht_params); err = register_pernet_device(&hwsim_net_ops); if (err) return err; err = platform_driver_register(&mac80211_hwsim_driver); if (err) goto out_unregister_pernet; hwsim_class = class_create(THIS_MODULE, "mac80211_hwsim"); if (IS_ERR(hwsim_class)) { err = PTR_ERR(hwsim_class); goto out_unregister_driver; } err = hwsim_init_netlink(); if (err < 0) goto out_unregister_driver; for (i = 0; i < radios; i++) { struct hwsim_new_radio_params param = { 0 }; param.channels = channels; switch (regtest) { case HWSIM_REGTEST_DIFF_COUNTRY: if (i < ARRAY_SIZE(hwsim_alpha2s)) param.reg_alpha2 = hwsim_alpha2s[i]; break; case HWSIM_REGTEST_DRIVER_REG_FOLLOW: if (!i) param.reg_alpha2 = hwsim_alpha2s[0]; break; case HWSIM_REGTEST_STRICT_ALL: param.reg_strict = true; case HWSIM_REGTEST_DRIVER_REG_ALL: param.reg_alpha2 = hwsim_alpha2s[0]; break; case HWSIM_REGTEST_WORLD_ROAM: if (i == 0) param.regd = &hwsim_world_regdom_custom_01; break; case HWSIM_REGTEST_CUSTOM_WORLD: param.regd = &hwsim_world_regdom_custom_01; break; case HWSIM_REGTEST_CUSTOM_WORLD_2: if (i == 0) param.regd = &hwsim_world_regdom_custom_01; else if (i == 1) param.regd = &hwsim_world_regdom_custom_02; break; case HWSIM_REGTEST_STRICT_FOLLOW: if (i == 0) { param.reg_strict = true; param.reg_alpha2 = hwsim_alpha2s[0]; } break; case HWSIM_REGTEST_STRICT_AND_DRIVER_REG: if (i == 0) { param.reg_strict = true; param.reg_alpha2 = hwsim_alpha2s[0]; } else if (i == 1) { param.reg_alpha2 = hwsim_alpha2s[1]; } break; case HWSIM_REGTEST_ALL: switch (i) { case 0: param.regd = &hwsim_world_regdom_custom_01; break; case 1: param.regd = &hwsim_world_regdom_custom_02; break; case 2: param.reg_alpha2 = hwsim_alpha2s[0]; break; case 3: param.reg_alpha2 = hwsim_alpha2s[1]; break; case 4: param.reg_strict = true; param.reg_alpha2 = hwsim_alpha2s[2]; break; } break; default: break; } param.p2p_device = support_p2p_device; param.use_chanctx = channels > 1; err = mac80211_hwsim_new_radio(NULL, &param); if (err < 0) goto out_free_radios; } hwsim_mon = alloc_netdev(0, "hwsim%d", NET_NAME_UNKNOWN, hwsim_mon_setup); if (hwsim_mon == NULL) { err = -ENOMEM; goto out_free_radios; } rtnl_lock(); err = dev_alloc_name(hwsim_mon, hwsim_mon->name); if (err < 0) { rtnl_unlock(); goto out_free_radios; } err = register_netdevice(hwsim_mon); if (err < 0) { rtnl_unlock(); goto out_free_mon; } rtnl_unlock(); return 0; out_free_mon: free_netdev(hwsim_mon); out_free_radios: mac80211_hwsim_free(); out_unregister_driver: platform_driver_unregister(&mac80211_hwsim_driver); out_unregister_pernet: unregister_pernet_device(&hwsim_net_ops); return err; } module_init(init_mac80211_hwsim); static void __exit exit_mac80211_hwsim(void) { pr_debug("mac80211_hwsim: unregister radios\n"); hwsim_exit_netlink(); mac80211_hwsim_free(); rhashtable_destroy(&hwsim_radios_rht); unregister_netdev(hwsim_mon); platform_driver_unregister(&mac80211_hwsim_driver); unregister_pernet_device(&hwsim_net_ops); } module_exit(exit_mac80211_hwsim);
./CrossVul/dataset_final_sorted/CWE-772/c/bad_661_0
crossvul-cpp_data_bad_2603_0
/* * Copyright (C) 2001 Jens Axboe <axboe@kernel.dk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public Licens * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111- * */ #include <linux/mm.h> #include <linux/swap.h> #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/uio.h> #include <linux/iocontext.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/export.h> #include <linux/mempool.h> #include <linux/workqueue.h> #include <linux/cgroup.h> #include <trace/events/block.h> #include "blk.h" /* * Test patch to inline a certain number of bi_io_vec's inside the bio * itself, to shrink a bio data allocation from two mempool calls to one */ #define BIO_INLINE_VECS 4 /* * if you change this list, also change bvec_alloc or things will * break badly! cannot be bigger than what you can fit into an * unsigned short */ #define BV(x) { .nr_vecs = x, .name = "biovec-"__stringify(x) } static struct biovec_slab bvec_slabs[BVEC_POOL_NR] __read_mostly = { BV(1), BV(4), BV(16), BV(64), BV(128), BV(BIO_MAX_PAGES), }; #undef BV /* * fs_bio_set is the bio_set containing bio and iovec memory pools used by * IO code that does not need private memory pools. */ struct bio_set *fs_bio_set; EXPORT_SYMBOL(fs_bio_set); /* * Our slab pool management */ struct bio_slab { struct kmem_cache *slab; unsigned int slab_ref; unsigned int slab_size; char name[8]; }; static DEFINE_MUTEX(bio_slab_lock); static struct bio_slab *bio_slabs; static unsigned int bio_slab_nr, bio_slab_max; static struct kmem_cache *bio_find_or_create_slab(unsigned int extra_size) { unsigned int sz = sizeof(struct bio) + extra_size; struct kmem_cache *slab = NULL; struct bio_slab *bslab, *new_bio_slabs; unsigned int new_bio_slab_max; unsigned int i, entry = -1; mutex_lock(&bio_slab_lock); i = 0; while (i < bio_slab_nr) { bslab = &bio_slabs[i]; if (!bslab->slab && entry == -1) entry = i; else if (bslab->slab_size == sz) { slab = bslab->slab; bslab->slab_ref++; break; } i++; } if (slab) goto out_unlock; if (bio_slab_nr == bio_slab_max && entry == -1) { new_bio_slab_max = bio_slab_max << 1; new_bio_slabs = krealloc(bio_slabs, new_bio_slab_max * sizeof(struct bio_slab), GFP_KERNEL); if (!new_bio_slabs) goto out_unlock; bio_slab_max = new_bio_slab_max; bio_slabs = new_bio_slabs; } if (entry == -1) entry = bio_slab_nr++; bslab = &bio_slabs[entry]; snprintf(bslab->name, sizeof(bslab->name), "bio-%d", entry); slab = kmem_cache_create(bslab->name, sz, ARCH_KMALLOC_MINALIGN, SLAB_HWCACHE_ALIGN, NULL); if (!slab) goto out_unlock; bslab->slab = slab; bslab->slab_ref = 1; bslab->slab_size = sz; out_unlock: mutex_unlock(&bio_slab_lock); return slab; } static void bio_put_slab(struct bio_set *bs) { struct bio_slab *bslab = NULL; unsigned int i; mutex_lock(&bio_slab_lock); for (i = 0; i < bio_slab_nr; i++) { if (bs->bio_slab == bio_slabs[i].slab) { bslab = &bio_slabs[i]; break; } } if (WARN(!bslab, KERN_ERR "bio: unable to find slab!\n")) goto out; WARN_ON(!bslab->slab_ref); if (--bslab->slab_ref) goto out; kmem_cache_destroy(bslab->slab); bslab->slab = NULL; out: mutex_unlock(&bio_slab_lock); } unsigned int bvec_nr_vecs(unsigned short idx) { return bvec_slabs[idx].nr_vecs; } void bvec_free(mempool_t *pool, struct bio_vec *bv, unsigned int idx) { if (!idx) return; idx--; BIO_BUG_ON(idx >= BVEC_POOL_NR); if (idx == BVEC_POOL_MAX) { mempool_free(bv, pool); } else { struct biovec_slab *bvs = bvec_slabs + idx; kmem_cache_free(bvs->slab, bv); } } struct bio_vec *bvec_alloc(gfp_t gfp_mask, int nr, unsigned long *idx, mempool_t *pool) { struct bio_vec *bvl; /* * see comment near bvec_array define! */ switch (nr) { case 1: *idx = 0; break; case 2 ... 4: *idx = 1; break; case 5 ... 16: *idx = 2; break; case 17 ... 64: *idx = 3; break; case 65 ... 128: *idx = 4; break; case 129 ... BIO_MAX_PAGES: *idx = 5; break; default: return NULL; } /* * idx now points to the pool we want to allocate from. only the * 1-vec entry pool is mempool backed. */ if (*idx == BVEC_POOL_MAX) { fallback: bvl = mempool_alloc(pool, gfp_mask); } else { struct biovec_slab *bvs = bvec_slabs + *idx; gfp_t __gfp_mask = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_IO); /* * Make this allocation restricted and don't dump info on * allocation failures, since we'll fallback to the mempool * in case of failure. */ __gfp_mask |= __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN; /* * Try a slab allocation. If this fails and __GFP_DIRECT_RECLAIM * is set, retry with the 1-entry mempool */ bvl = kmem_cache_alloc(bvs->slab, __gfp_mask); if (unlikely(!bvl && (gfp_mask & __GFP_DIRECT_RECLAIM))) { *idx = BVEC_POOL_MAX; goto fallback; } } (*idx)++; return bvl; } void bio_uninit(struct bio *bio) { bio_disassociate_task(bio); } EXPORT_SYMBOL(bio_uninit); static void bio_free(struct bio *bio) { struct bio_set *bs = bio->bi_pool; void *p; bio_uninit(bio); if (bs) { bvec_free(bs->bvec_pool, bio->bi_io_vec, BVEC_POOL_IDX(bio)); /* * If we have front padding, adjust the bio pointer before freeing */ p = bio; p -= bs->front_pad; mempool_free(p, bs->bio_pool); } else { /* Bio was allocated by bio_kmalloc() */ kfree(bio); } } /* * Users of this function have their own bio allocation. Subsequently, * they must remember to pair any call to bio_init() with bio_uninit() * when IO has completed, or when the bio is released. */ void bio_init(struct bio *bio, struct bio_vec *table, unsigned short max_vecs) { memset(bio, 0, sizeof(*bio)); atomic_set(&bio->__bi_remaining, 1); atomic_set(&bio->__bi_cnt, 1); bio->bi_io_vec = table; bio->bi_max_vecs = max_vecs; } EXPORT_SYMBOL(bio_init); /** * bio_reset - reinitialize a bio * @bio: bio to reset * * Description: * After calling bio_reset(), @bio will be in the same state as a freshly * allocated bio returned bio bio_alloc_bioset() - the only fields that are * preserved are the ones that are initialized by bio_alloc_bioset(). See * comment in struct bio. */ void bio_reset(struct bio *bio) { unsigned long flags = bio->bi_flags & (~0UL << BIO_RESET_BITS); bio_uninit(bio); memset(bio, 0, BIO_RESET_BYTES); bio->bi_flags = flags; atomic_set(&bio->__bi_remaining, 1); } EXPORT_SYMBOL(bio_reset); static struct bio *__bio_chain_endio(struct bio *bio) { struct bio *parent = bio->bi_private; if (!parent->bi_status) parent->bi_status = bio->bi_status; bio_put(bio); return parent; } static void bio_chain_endio(struct bio *bio) { bio_endio(__bio_chain_endio(bio)); } /** * bio_chain - chain bio completions * @bio: the target bio * @parent: the @bio's parent bio * * The caller won't have a bi_end_io called when @bio completes - instead, * @parent's bi_end_io won't be called until both @parent and @bio have * completed; the chained bio will also be freed when it completes. * * The caller must not set bi_private or bi_end_io in @bio. */ void bio_chain(struct bio *bio, struct bio *parent) { BUG_ON(bio->bi_private || bio->bi_end_io); bio->bi_private = parent; bio->bi_end_io = bio_chain_endio; bio_inc_remaining(parent); } EXPORT_SYMBOL(bio_chain); static void bio_alloc_rescue(struct work_struct *work) { struct bio_set *bs = container_of(work, struct bio_set, rescue_work); struct bio *bio; while (1) { spin_lock(&bs->rescue_lock); bio = bio_list_pop(&bs->rescue_list); spin_unlock(&bs->rescue_lock); if (!bio) break; generic_make_request(bio); } } static void punt_bios_to_rescuer(struct bio_set *bs) { struct bio_list punt, nopunt; struct bio *bio; if (WARN_ON_ONCE(!bs->rescue_workqueue)) return; /* * In order to guarantee forward progress we must punt only bios that * were allocated from this bio_set; otherwise, if there was a bio on * there for a stacking driver higher up in the stack, processing it * could require allocating bios from this bio_set, and doing that from * our own rescuer would be bad. * * Since bio lists are singly linked, pop them all instead of trying to * remove from the middle of the list: */ bio_list_init(&punt); bio_list_init(&nopunt); while ((bio = bio_list_pop(&current->bio_list[0]))) bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio); current->bio_list[0] = nopunt; bio_list_init(&nopunt); while ((bio = bio_list_pop(&current->bio_list[1]))) bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio); current->bio_list[1] = nopunt; spin_lock(&bs->rescue_lock); bio_list_merge(&bs->rescue_list, &punt); spin_unlock(&bs->rescue_lock); queue_work(bs->rescue_workqueue, &bs->rescue_work); } /** * bio_alloc_bioset - allocate a bio for I/O * @gfp_mask: the GFP_ mask given to the slab allocator * @nr_iovecs: number of iovecs to pre-allocate * @bs: the bio_set to allocate from. * * Description: * If @bs is NULL, uses kmalloc() to allocate the bio; else the allocation is * backed by the @bs's mempool. * * When @bs is not NULL, if %__GFP_DIRECT_RECLAIM is set then bio_alloc will * always be able to allocate a bio. This is due to the mempool guarantees. * To make this work, callers must never allocate more than 1 bio at a time * from this pool. Callers that need to allocate more than 1 bio must always * submit the previously allocated bio for IO before attempting to allocate * a new one. Failure to do so can cause deadlocks under memory pressure. * * Note that when running under generic_make_request() (i.e. any block * driver), bios are not submitted until after you return - see the code in * generic_make_request() that converts recursion into iteration, to prevent * stack overflows. * * This would normally mean allocating multiple bios under * generic_make_request() would be susceptible to deadlocks, but we have * deadlock avoidance code that resubmits any blocked bios from a rescuer * thread. * * However, we do not guarantee forward progress for allocations from other * mempools. Doing multiple allocations from the same mempool under * generic_make_request() should be avoided - instead, use bio_set's front_pad * for per bio allocations. * * RETURNS: * Pointer to new bio on success, NULL on failure. */ struct bio *bio_alloc_bioset(gfp_t gfp_mask, unsigned int nr_iovecs, struct bio_set *bs) { gfp_t saved_gfp = gfp_mask; unsigned front_pad; unsigned inline_vecs; struct bio_vec *bvl = NULL; struct bio *bio; void *p; if (!bs) { if (nr_iovecs > UIO_MAXIOV) return NULL; p = kmalloc(sizeof(struct bio) + nr_iovecs * sizeof(struct bio_vec), gfp_mask); front_pad = 0; inline_vecs = nr_iovecs; } else { /* should not use nobvec bioset for nr_iovecs > 0 */ if (WARN_ON_ONCE(!bs->bvec_pool && nr_iovecs > 0)) return NULL; /* * generic_make_request() converts recursion to iteration; this * means if we're running beneath it, any bios we allocate and * submit will not be submitted (and thus freed) until after we * return. * * This exposes us to a potential deadlock if we allocate * multiple bios from the same bio_set() while running * underneath generic_make_request(). If we were to allocate * multiple bios (say a stacking block driver that was splitting * bios), we would deadlock if we exhausted the mempool's * reserve. * * We solve this, and guarantee forward progress, with a rescuer * workqueue per bio_set. If we go to allocate and there are * bios on current->bio_list, we first try the allocation * without __GFP_DIRECT_RECLAIM; if that fails, we punt those * bios we would be blocking to the rescuer workqueue before * we retry with the original gfp_flags. */ if (current->bio_list && (!bio_list_empty(&current->bio_list[0]) || !bio_list_empty(&current->bio_list[1])) && bs->rescue_workqueue) gfp_mask &= ~__GFP_DIRECT_RECLAIM; p = mempool_alloc(bs->bio_pool, gfp_mask); if (!p && gfp_mask != saved_gfp) { punt_bios_to_rescuer(bs); gfp_mask = saved_gfp; p = mempool_alloc(bs->bio_pool, gfp_mask); } front_pad = bs->front_pad; inline_vecs = BIO_INLINE_VECS; } if (unlikely(!p)) return NULL; bio = p + front_pad; bio_init(bio, NULL, 0); if (nr_iovecs > inline_vecs) { unsigned long idx = 0; bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx, bs->bvec_pool); if (!bvl && gfp_mask != saved_gfp) { punt_bios_to_rescuer(bs); gfp_mask = saved_gfp; bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx, bs->bvec_pool); } if (unlikely(!bvl)) goto err_free; bio->bi_flags |= idx << BVEC_POOL_OFFSET; } else if (nr_iovecs) { bvl = bio->bi_inline_vecs; } bio->bi_pool = bs; bio->bi_max_vecs = nr_iovecs; bio->bi_io_vec = bvl; return bio; err_free: mempool_free(p, bs->bio_pool); return NULL; } EXPORT_SYMBOL(bio_alloc_bioset); void zero_fill_bio(struct bio *bio) { unsigned long flags; struct bio_vec bv; struct bvec_iter iter; bio_for_each_segment(bv, bio, iter) { char *data = bvec_kmap_irq(&bv, &flags); memset(data, 0, bv.bv_len); flush_dcache_page(bv.bv_page); bvec_kunmap_irq(data, &flags); } } EXPORT_SYMBOL(zero_fill_bio); /** * bio_put - release a reference to a bio * @bio: bio to release reference to * * Description: * Put a reference to a &struct bio, either one you have gotten with * bio_alloc, bio_get or bio_clone_*. The last put of a bio will free it. **/ void bio_put(struct bio *bio) { if (!bio_flagged(bio, BIO_REFFED)) bio_free(bio); else { BIO_BUG_ON(!atomic_read(&bio->__bi_cnt)); /* * last put frees it */ if (atomic_dec_and_test(&bio->__bi_cnt)) bio_free(bio); } } EXPORT_SYMBOL(bio_put); inline int bio_phys_segments(struct request_queue *q, struct bio *bio) { if (unlikely(!bio_flagged(bio, BIO_SEG_VALID))) blk_recount_segments(q, bio); return bio->bi_phys_segments; } EXPORT_SYMBOL(bio_phys_segments); /** * __bio_clone_fast - clone a bio that shares the original bio's biovec * @bio: destination bio * @bio_src: bio to clone * * Clone a &bio. Caller will own the returned bio, but not * the actual data it points to. Reference count of returned * bio will be one. * * Caller must ensure that @bio_src is not freed before @bio. */ void __bio_clone_fast(struct bio *bio, struct bio *bio_src) { BUG_ON(bio->bi_pool && BVEC_POOL_IDX(bio)); /* * most users will be overriding ->bi_disk with a new target, * so we don't set nor calculate new physical/hw segment counts here */ bio->bi_disk = bio_src->bi_disk; bio_set_flag(bio, BIO_CLONED); bio->bi_opf = bio_src->bi_opf; bio->bi_write_hint = bio_src->bi_write_hint; bio->bi_iter = bio_src->bi_iter; bio->bi_io_vec = bio_src->bi_io_vec; bio_clone_blkcg_association(bio, bio_src); } EXPORT_SYMBOL(__bio_clone_fast); /** * bio_clone_fast - clone a bio that shares the original bio's biovec * @bio: bio to clone * @gfp_mask: allocation priority * @bs: bio_set to allocate from * * Like __bio_clone_fast, only also allocates the returned bio */ struct bio *bio_clone_fast(struct bio *bio, gfp_t gfp_mask, struct bio_set *bs) { struct bio *b; b = bio_alloc_bioset(gfp_mask, 0, bs); if (!b) return NULL; __bio_clone_fast(b, bio); if (bio_integrity(bio)) { int ret; ret = bio_integrity_clone(b, bio, gfp_mask); if (ret < 0) { bio_put(b); return NULL; } } return b; } EXPORT_SYMBOL(bio_clone_fast); /** * bio_clone_bioset - clone a bio * @bio_src: bio to clone * @gfp_mask: allocation priority * @bs: bio_set to allocate from * * Clone bio. Caller will own the returned bio, but not the actual data it * points to. Reference count of returned bio will be one. */ struct bio *bio_clone_bioset(struct bio *bio_src, gfp_t gfp_mask, struct bio_set *bs) { struct bvec_iter iter; struct bio_vec bv; struct bio *bio; /* * Pre immutable biovecs, __bio_clone() used to just do a memcpy from * bio_src->bi_io_vec to bio->bi_io_vec. * * We can't do that anymore, because: * * - The point of cloning the biovec is to produce a bio with a biovec * the caller can modify: bi_idx and bi_bvec_done should be 0. * * - The original bio could've had more than BIO_MAX_PAGES biovecs; if * we tried to clone the whole thing bio_alloc_bioset() would fail. * But the clone should succeed as long as the number of biovecs we * actually need to allocate is fewer than BIO_MAX_PAGES. * * - Lastly, bi_vcnt should not be looked at or relied upon by code * that does not own the bio - reason being drivers don't use it for * iterating over the biovec anymore, so expecting it to be kept up * to date (i.e. for clones that share the parent biovec) is just * asking for trouble and would force extra work on * __bio_clone_fast() anyways. */ bio = bio_alloc_bioset(gfp_mask, bio_segments(bio_src), bs); if (!bio) return NULL; bio->bi_disk = bio_src->bi_disk; bio->bi_opf = bio_src->bi_opf; bio->bi_write_hint = bio_src->bi_write_hint; bio->bi_iter.bi_sector = bio_src->bi_iter.bi_sector; bio->bi_iter.bi_size = bio_src->bi_iter.bi_size; switch (bio_op(bio)) { case REQ_OP_DISCARD: case REQ_OP_SECURE_ERASE: case REQ_OP_WRITE_ZEROES: break; case REQ_OP_WRITE_SAME: bio->bi_io_vec[bio->bi_vcnt++] = bio_src->bi_io_vec[0]; break; default: bio_for_each_segment(bv, bio_src, iter) bio->bi_io_vec[bio->bi_vcnt++] = bv; break; } if (bio_integrity(bio_src)) { int ret; ret = bio_integrity_clone(bio, bio_src, gfp_mask); if (ret < 0) { bio_put(bio); return NULL; } } bio_clone_blkcg_association(bio, bio_src); return bio; } EXPORT_SYMBOL(bio_clone_bioset); /** * bio_add_pc_page - attempt to add page to bio * @q: the target queue * @bio: destination bio * @page: page to add * @len: vec entry length * @offset: vec entry offset * * Attempt to add a page to the bio_vec maplist. This can fail for a * number of reasons, such as the bio being full or target block device * limitations. The target block device must allow bio's up to PAGE_SIZE, * so it is always possible to add a single page to an empty bio. * * This should only be used by REQ_PC bios. */ int bio_add_pc_page(struct request_queue *q, struct bio *bio, struct page *page, unsigned int len, unsigned int offset) { int retried_segments = 0; struct bio_vec *bvec; /* * cloned bio must not modify vec list */ if (unlikely(bio_flagged(bio, BIO_CLONED))) return 0; if (((bio->bi_iter.bi_size + len) >> 9) > queue_max_hw_sectors(q)) return 0; /* * For filesystems with a blocksize smaller than the pagesize * we will often be called with the same page as last time and * a consecutive offset. Optimize this special case. */ if (bio->bi_vcnt > 0) { struct bio_vec *prev = &bio->bi_io_vec[bio->bi_vcnt - 1]; if (page == prev->bv_page && offset == prev->bv_offset + prev->bv_len) { prev->bv_len += len; bio->bi_iter.bi_size += len; goto done; } /* * If the queue doesn't support SG gaps and adding this * offset would create a gap, disallow it. */ if (bvec_gap_to_prev(q, prev, offset)) return 0; } if (bio->bi_vcnt >= bio->bi_max_vecs) return 0; /* * setup the new entry, we might clear it again later if we * cannot add the page */ bvec = &bio->bi_io_vec[bio->bi_vcnt]; bvec->bv_page = page; bvec->bv_len = len; bvec->bv_offset = offset; bio->bi_vcnt++; bio->bi_phys_segments++; bio->bi_iter.bi_size += len; /* * Perform a recount if the number of segments is greater * than queue_max_segments(q). */ while (bio->bi_phys_segments > queue_max_segments(q)) { if (retried_segments) goto failed; retried_segments = 1; blk_recount_segments(q, bio); } /* If we may be able to merge these biovecs, force a recount */ if (bio->bi_vcnt > 1 && (BIOVEC_PHYS_MERGEABLE(bvec-1, bvec))) bio_clear_flag(bio, BIO_SEG_VALID); done: return len; failed: bvec->bv_page = NULL; bvec->bv_len = 0; bvec->bv_offset = 0; bio->bi_vcnt--; bio->bi_iter.bi_size -= len; blk_recount_segments(q, bio); return 0; } EXPORT_SYMBOL(bio_add_pc_page); /** * bio_add_page - attempt to add page to bio * @bio: destination bio * @page: page to add * @len: vec entry length * @offset: vec entry offset * * Attempt to add a page to the bio_vec maplist. This will only fail * if either bio->bi_vcnt == bio->bi_max_vecs or it's a cloned bio. */ int bio_add_page(struct bio *bio, struct page *page, unsigned int len, unsigned int offset) { struct bio_vec *bv; /* * cloned bio must not modify vec list */ if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED))) return 0; /* * For filesystems with a blocksize smaller than the pagesize * we will often be called with the same page as last time and * a consecutive offset. Optimize this special case. */ if (bio->bi_vcnt > 0) { bv = &bio->bi_io_vec[bio->bi_vcnt - 1]; if (page == bv->bv_page && offset == bv->bv_offset + bv->bv_len) { bv->bv_len += len; goto done; } } if (bio->bi_vcnt >= bio->bi_max_vecs) return 0; bv = &bio->bi_io_vec[bio->bi_vcnt]; bv->bv_page = page; bv->bv_len = len; bv->bv_offset = offset; bio->bi_vcnt++; done: bio->bi_iter.bi_size += len; return len; } EXPORT_SYMBOL(bio_add_page); /** * bio_iov_iter_get_pages - pin user or kernel pages and add them to a bio * @bio: bio to add pages to * @iter: iov iterator describing the region to be mapped * * Pins as many pages from *iter and appends them to @bio's bvec array. The * pages will have to be released using put_page() when done. */ int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter) { unsigned short nr_pages = bio->bi_max_vecs - bio->bi_vcnt; struct bio_vec *bv = bio->bi_io_vec + bio->bi_vcnt; struct page **pages = (struct page **)bv; size_t offset, diff; ssize_t size; size = iov_iter_get_pages(iter, pages, LONG_MAX, nr_pages, &offset); if (unlikely(size <= 0)) return size ? size : -EFAULT; nr_pages = (size + offset + PAGE_SIZE - 1) / PAGE_SIZE; /* * Deep magic below: We need to walk the pinned pages backwards * because we are abusing the space allocated for the bio_vecs * for the page array. Because the bio_vecs are larger than the * page pointers by definition this will always work. But it also * means we can't use bio_add_page, so any changes to it's semantics * need to be reflected here as well. */ bio->bi_iter.bi_size += size; bio->bi_vcnt += nr_pages; diff = (nr_pages * PAGE_SIZE - offset) - size; while (nr_pages--) { bv[nr_pages].bv_page = pages[nr_pages]; bv[nr_pages].bv_len = PAGE_SIZE; bv[nr_pages].bv_offset = 0; } bv[0].bv_offset += offset; bv[0].bv_len -= offset; if (diff) bv[bio->bi_vcnt - 1].bv_len -= diff; iov_iter_advance(iter, size); return 0; } EXPORT_SYMBOL_GPL(bio_iov_iter_get_pages); struct submit_bio_ret { struct completion event; int error; }; static void submit_bio_wait_endio(struct bio *bio) { struct submit_bio_ret *ret = bio->bi_private; ret->error = blk_status_to_errno(bio->bi_status); complete(&ret->event); } /** * submit_bio_wait - submit a bio, and wait until it completes * @bio: The &struct bio which describes the I/O * * Simple wrapper around submit_bio(). Returns 0 on success, or the error from * bio_endio() on failure. * * WARNING: Unlike to how submit_bio() is usually used, this function does not * result in bio reference to be consumed. The caller must drop the reference * on his own. */ int submit_bio_wait(struct bio *bio) { struct submit_bio_ret ret; init_completion(&ret.event); bio->bi_private = &ret; bio->bi_end_io = submit_bio_wait_endio; bio->bi_opf |= REQ_SYNC; submit_bio(bio); wait_for_completion_io(&ret.event); return ret.error; } EXPORT_SYMBOL(submit_bio_wait); /** * bio_advance - increment/complete a bio by some number of bytes * @bio: bio to advance * @bytes: number of bytes to complete * * This updates bi_sector, bi_size and bi_idx; if the number of bytes to * complete doesn't align with a bvec boundary, then bv_len and bv_offset will * be updated on the last bvec as well. * * @bio will then represent the remaining, uncompleted portion of the io. */ void bio_advance(struct bio *bio, unsigned bytes) { if (bio_integrity(bio)) bio_integrity_advance(bio, bytes); bio_advance_iter(bio, &bio->bi_iter, bytes); } EXPORT_SYMBOL(bio_advance); /** * bio_alloc_pages - allocates a single page for each bvec in a bio * @bio: bio to allocate pages for * @gfp_mask: flags for allocation * * Allocates pages up to @bio->bi_vcnt. * * Returns 0 on success, -ENOMEM on failure. On failure, any allocated pages are * freed. */ int bio_alloc_pages(struct bio *bio, gfp_t gfp_mask) { int i; struct bio_vec *bv; bio_for_each_segment_all(bv, bio, i) { bv->bv_page = alloc_page(gfp_mask); if (!bv->bv_page) { while (--bv >= bio->bi_io_vec) __free_page(bv->bv_page); return -ENOMEM; } } return 0; } EXPORT_SYMBOL(bio_alloc_pages); /** * bio_copy_data - copy contents of data buffers from one chain of bios to * another * @src: source bio list * @dst: destination bio list * * If @src and @dst are single bios, bi_next must be NULL - otherwise, treats * @src and @dst as linked lists of bios. * * Stops when it reaches the end of either @src or @dst - that is, copies * min(src->bi_size, dst->bi_size) bytes (or the equivalent for lists of bios). */ void bio_copy_data(struct bio *dst, struct bio *src) { struct bvec_iter src_iter, dst_iter; struct bio_vec src_bv, dst_bv; void *src_p, *dst_p; unsigned bytes; src_iter = src->bi_iter; dst_iter = dst->bi_iter; while (1) { if (!src_iter.bi_size) { src = src->bi_next; if (!src) break; src_iter = src->bi_iter; } if (!dst_iter.bi_size) { dst = dst->bi_next; if (!dst) break; dst_iter = dst->bi_iter; } src_bv = bio_iter_iovec(src, src_iter); dst_bv = bio_iter_iovec(dst, dst_iter); bytes = min(src_bv.bv_len, dst_bv.bv_len); src_p = kmap_atomic(src_bv.bv_page); dst_p = kmap_atomic(dst_bv.bv_page); memcpy(dst_p + dst_bv.bv_offset, src_p + src_bv.bv_offset, bytes); kunmap_atomic(dst_p); kunmap_atomic(src_p); bio_advance_iter(src, &src_iter, bytes); bio_advance_iter(dst, &dst_iter, bytes); } } EXPORT_SYMBOL(bio_copy_data); struct bio_map_data { int is_our_pages; struct iov_iter iter; struct iovec iov[]; }; static struct bio_map_data *bio_alloc_map_data(unsigned int iov_count, gfp_t gfp_mask) { if (iov_count > UIO_MAXIOV) return NULL; return kmalloc(sizeof(struct bio_map_data) + sizeof(struct iovec) * iov_count, gfp_mask); } /** * bio_copy_from_iter - copy all pages from iov_iter to bio * @bio: The &struct bio which describes the I/O as destination * @iter: iov_iter as source * * Copy all pages from iov_iter to bio. * Returns 0 on success, or error on failure. */ static int bio_copy_from_iter(struct bio *bio, struct iov_iter iter) { int i; struct bio_vec *bvec; bio_for_each_segment_all(bvec, bio, i) { ssize_t ret; ret = copy_page_from_iter(bvec->bv_page, bvec->bv_offset, bvec->bv_len, &iter); if (!iov_iter_count(&iter)) break; if (ret < bvec->bv_len) return -EFAULT; } return 0; } /** * bio_copy_to_iter - copy all pages from bio to iov_iter * @bio: The &struct bio which describes the I/O as source * @iter: iov_iter as destination * * Copy all pages from bio to iov_iter. * Returns 0 on success, or error on failure. */ static int bio_copy_to_iter(struct bio *bio, struct iov_iter iter) { int i; struct bio_vec *bvec; bio_for_each_segment_all(bvec, bio, i) { ssize_t ret; ret = copy_page_to_iter(bvec->bv_page, bvec->bv_offset, bvec->bv_len, &iter); if (!iov_iter_count(&iter)) break; if (ret < bvec->bv_len) return -EFAULT; } return 0; } void bio_free_pages(struct bio *bio) { struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) __free_page(bvec->bv_page); } EXPORT_SYMBOL(bio_free_pages); /** * bio_uncopy_user - finish previously mapped bio * @bio: bio being terminated * * Free pages allocated from bio_copy_user_iov() and write back data * to user space in case of a read. */ int bio_uncopy_user(struct bio *bio) { struct bio_map_data *bmd = bio->bi_private; int ret = 0; if (!bio_flagged(bio, BIO_NULL_MAPPED)) { /* * if we're in a workqueue, the request is orphaned, so * don't copy into a random user address space, just free * and return -EINTR so user space doesn't expect any data. */ if (!current->mm) ret = -EINTR; else if (bio_data_dir(bio) == READ) ret = bio_copy_to_iter(bio, bmd->iter); if (bmd->is_our_pages) bio_free_pages(bio); } kfree(bmd); bio_put(bio); return ret; } /** * bio_copy_user_iov - copy user data to bio * @q: destination block queue * @map_data: pointer to the rq_map_data holding pages (if necessary) * @iter: iovec iterator * @gfp_mask: memory allocation flags * * Prepares and returns a bio for indirect user io, bouncing data * to/from kernel pages as necessary. Must be paired with * call bio_uncopy_user() on io completion. */ struct bio *bio_copy_user_iov(struct request_queue *q, struct rq_map_data *map_data, const struct iov_iter *iter, gfp_t gfp_mask) { struct bio_map_data *bmd; struct page *page; struct bio *bio; int i, ret; int nr_pages = 0; unsigned int len = iter->count; unsigned int offset = map_data ? offset_in_page(map_data->offset) : 0; for (i = 0; i < iter->nr_segs; i++) { unsigned long uaddr; unsigned long end; unsigned long start; uaddr = (unsigned long) iter->iov[i].iov_base; end = (uaddr + iter->iov[i].iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT; start = uaddr >> PAGE_SHIFT; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages += end - start; } if (offset) nr_pages++; bmd = bio_alloc_map_data(iter->nr_segs, gfp_mask); if (!bmd) return ERR_PTR(-ENOMEM); /* * We need to do a deep copy of the iov_iter including the iovecs. * The caller provided iov might point to an on-stack or otherwise * shortlived one. */ bmd->is_our_pages = map_data ? 0 : 1; memcpy(bmd->iov, iter->iov, sizeof(struct iovec) * iter->nr_segs); iov_iter_init(&bmd->iter, iter->type, bmd->iov, iter->nr_segs, iter->count); ret = -ENOMEM; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) goto out_bmd; ret = 0; if (map_data) { nr_pages = 1 << map_data->page_order; i = map_data->offset / PAGE_SIZE; } while (len) { unsigned int bytes = PAGE_SIZE; bytes -= offset; if (bytes > len) bytes = len; if (map_data) { if (i == map_data->nr_entries * nr_pages) { ret = -ENOMEM; break; } page = map_data->pages[i / nr_pages]; page += (i % nr_pages); i++; } else { page = alloc_page(q->bounce_gfp | gfp_mask); if (!page) { ret = -ENOMEM; break; } } if (bio_add_pc_page(q, bio, page, bytes, offset) < bytes) break; len -= bytes; offset = 0; } if (ret) goto cleanup; /* * success */ if (((iter->type & WRITE) && (!map_data || !map_data->null_mapped)) || (map_data && map_data->from_user)) { ret = bio_copy_from_iter(bio, *iter); if (ret) goto cleanup; } bio->bi_private = bmd; return bio; cleanup: if (!map_data) bio_free_pages(bio); bio_put(bio); out_bmd: kfree(bmd); return ERR_PTR(ret); } /** * bio_map_user_iov - map user iovec into bio * @q: the struct request_queue for the bio * @iter: iovec iterator * @gfp_mask: memory allocation flags * * Map the user space address into a bio suitable for io to a block * device. Returns an error pointer in case of error. */ struct bio *bio_map_user_iov(struct request_queue *q, const struct iov_iter *iter, gfp_t gfp_mask) { int j; int nr_pages = 0; struct page **pages; struct bio *bio; int cur_page = 0; int ret, offset; struct iov_iter i; struct iovec iov; iov_for_each(iov, i, *iter) { unsigned long uaddr = (unsigned long) iov.iov_base; unsigned long len = iov.iov_len; unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = uaddr >> PAGE_SHIFT; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages += end - start; /* * buffer must be aligned to at least logical block size for now */ if (uaddr & queue_dma_alignment(q)) return ERR_PTR(-EINVAL); } if (!nr_pages) return ERR_PTR(-EINVAL); bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); ret = -ENOMEM; pages = kcalloc(nr_pages, sizeof(struct page *), gfp_mask); if (!pages) goto out; iov_for_each(iov, i, *iter) { unsigned long uaddr = (unsigned long) iov.iov_base; unsigned long len = iov.iov_len; unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = uaddr >> PAGE_SHIFT; const int local_nr_pages = end - start; const int page_limit = cur_page + local_nr_pages; ret = get_user_pages_fast(uaddr, local_nr_pages, (iter->type & WRITE) != WRITE, &pages[cur_page]); if (ret < local_nr_pages) { ret = -EFAULT; goto out_unmap; } offset = offset_in_page(uaddr); for (j = cur_page; j < page_limit; j++) { unsigned int bytes = PAGE_SIZE - offset; unsigned short prev_bi_vcnt = bio->bi_vcnt; if (len <= 0) break; if (bytes > len) bytes = len; /* * sorry... */ if (bio_add_pc_page(q, bio, pages[j], bytes, offset) < bytes) break; /* * check if vector was merged with previous * drop page reference if needed */ if (bio->bi_vcnt == prev_bi_vcnt) put_page(pages[j]); len -= bytes; offset = 0; } cur_page = j; /* * release the pages we didn't map into the bio, if any */ while (j < page_limit) put_page(pages[j++]); } kfree(pages); bio_set_flag(bio, BIO_USER_MAPPED); /* * subtle -- if bio_map_user_iov() ended up bouncing a bio, * it would normally disappear when its bi_end_io is run. * however, we need it for the unmap, so grab an extra * reference to it */ bio_get(bio); return bio; out_unmap: for (j = 0; j < nr_pages; j++) { if (!pages[j]) break; put_page(pages[j]); } out: kfree(pages); bio_put(bio); return ERR_PTR(ret); } static void __bio_unmap_user(struct bio *bio) { struct bio_vec *bvec; int i; /* * make sure we dirty pages we wrote to */ bio_for_each_segment_all(bvec, bio, i) { if (bio_data_dir(bio) == READ) set_page_dirty_lock(bvec->bv_page); put_page(bvec->bv_page); } bio_put(bio); } /** * bio_unmap_user - unmap a bio * @bio: the bio being unmapped * * Unmap a bio previously mapped by bio_map_user_iov(). Must be called from * process context. * * bio_unmap_user() may sleep. */ void bio_unmap_user(struct bio *bio) { __bio_unmap_user(bio); bio_put(bio); } static void bio_map_kern_endio(struct bio *bio) { bio_put(bio); } /** * bio_map_kern - map kernel address into bio * @q: the struct request_queue for the bio * @data: pointer to buffer to map * @len: length in bytes * @gfp_mask: allocation flags for bio allocation * * Map the kernel address into a bio suitable for io to a block * device. Returns an error pointer in case of error. */ struct bio *bio_map_kern(struct request_queue *q, void *data, unsigned int len, gfp_t gfp_mask) { unsigned long kaddr = (unsigned long)data; unsigned long end = (kaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = kaddr >> PAGE_SHIFT; const int nr_pages = end - start; int offset, i; struct bio *bio; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); offset = offset_in_page(kaddr); for (i = 0; i < nr_pages; i++) { unsigned int bytes = PAGE_SIZE - offset; if (len <= 0) break; if (bytes > len) bytes = len; if (bio_add_pc_page(q, bio, virt_to_page(data), bytes, offset) < bytes) { /* we don't support partial mappings */ bio_put(bio); return ERR_PTR(-EINVAL); } data += bytes; len -= bytes; offset = 0; } bio->bi_end_io = bio_map_kern_endio; return bio; } EXPORT_SYMBOL(bio_map_kern); static void bio_copy_kern_endio(struct bio *bio) { bio_free_pages(bio); bio_put(bio); } static void bio_copy_kern_endio_read(struct bio *bio) { char *p = bio->bi_private; struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) { memcpy(p, page_address(bvec->bv_page), bvec->bv_len); p += bvec->bv_len; } bio_copy_kern_endio(bio); } /** * bio_copy_kern - copy kernel address into bio * @q: the struct request_queue for the bio * @data: pointer to buffer to copy * @len: length in bytes * @gfp_mask: allocation flags for bio and page allocation * @reading: data direction is READ * * copy the kernel address into a bio suitable for io to a block * device. Returns an error pointer in case of error. */ struct bio *bio_copy_kern(struct request_queue *q, void *data, unsigned int len, gfp_t gfp_mask, int reading) { unsigned long kaddr = (unsigned long)data; unsigned long end = (kaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = kaddr >> PAGE_SHIFT; struct bio *bio; void *p = data; int nr_pages = 0; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages = end - start; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); while (len) { struct page *page; unsigned int bytes = PAGE_SIZE; if (bytes > len) bytes = len; page = alloc_page(q->bounce_gfp | gfp_mask); if (!page) goto cleanup; if (!reading) memcpy(page_address(page), p, bytes); if (bio_add_pc_page(q, bio, page, bytes, 0) < bytes) break; len -= bytes; p += bytes; } if (reading) { bio->bi_end_io = bio_copy_kern_endio_read; bio->bi_private = data; } else { bio->bi_end_io = bio_copy_kern_endio; } return bio; cleanup: bio_free_pages(bio); bio_put(bio); return ERR_PTR(-ENOMEM); } /* * bio_set_pages_dirty() and bio_check_pages_dirty() are support functions * for performing direct-IO in BIOs. * * The problem is that we cannot run set_page_dirty() from interrupt context * because the required locks are not interrupt-safe. So what we can do is to * mark the pages dirty _before_ performing IO. And in interrupt context, * check that the pages are still dirty. If so, fine. If not, redirty them * in process context. * * We special-case compound pages here: normally this means reads into hugetlb * pages. The logic in here doesn't really work right for compound pages * because the VM does not uniformly chase down the head page in all cases. * But dirtiness of compound pages is pretty meaningless anyway: the VM doesn't * handle them at all. So we skip compound pages here at an early stage. * * Note that this code is very hard to test under normal circumstances because * direct-io pins the pages with get_user_pages(). This makes * is_page_cache_freeable return false, and the VM will not clean the pages. * But other code (eg, flusher threads) could clean the pages if they are mapped * pagecache. * * Simply disabling the call to bio_set_pages_dirty() is a good way to test the * deferred bio dirtying paths. */ /* * bio_set_pages_dirty() will mark all the bio's pages as dirty. */ void bio_set_pages_dirty(struct bio *bio) { struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) { struct page *page = bvec->bv_page; if (page && !PageCompound(page)) set_page_dirty_lock(page); } } static void bio_release_pages(struct bio *bio) { struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) { struct page *page = bvec->bv_page; if (page) put_page(page); } } /* * bio_check_pages_dirty() will check that all the BIO's pages are still dirty. * If they are, then fine. If, however, some pages are clean then they must * have been written out during the direct-IO read. So we take another ref on * the BIO and the offending pages and re-dirty the pages in process context. * * It is expected that bio_check_pages_dirty() will wholly own the BIO from * here on. It will run one put_page() against each page and will run one * bio_put() against the BIO. */ static void bio_dirty_fn(struct work_struct *work); static DECLARE_WORK(bio_dirty_work, bio_dirty_fn); static DEFINE_SPINLOCK(bio_dirty_lock); static struct bio *bio_dirty_list; /* * This runs in process context */ static void bio_dirty_fn(struct work_struct *work) { unsigned long flags; struct bio *bio; spin_lock_irqsave(&bio_dirty_lock, flags); bio = bio_dirty_list; bio_dirty_list = NULL; spin_unlock_irqrestore(&bio_dirty_lock, flags); while (bio) { struct bio *next = bio->bi_private; bio_set_pages_dirty(bio); bio_release_pages(bio); bio_put(bio); bio = next; } } void bio_check_pages_dirty(struct bio *bio) { struct bio_vec *bvec; int nr_clean_pages = 0; int i; bio_for_each_segment_all(bvec, bio, i) { struct page *page = bvec->bv_page; if (PageDirty(page) || PageCompound(page)) { put_page(page); bvec->bv_page = NULL; } else { nr_clean_pages++; } } if (nr_clean_pages) { unsigned long flags; spin_lock_irqsave(&bio_dirty_lock, flags); bio->bi_private = bio_dirty_list; bio_dirty_list = bio; spin_unlock_irqrestore(&bio_dirty_lock, flags); schedule_work(&bio_dirty_work); } else { bio_put(bio); } } void generic_start_io_acct(struct request_queue *q, int rw, unsigned long sectors, struct hd_struct *part) { int cpu = part_stat_lock(); part_round_stats(q, cpu, part); part_stat_inc(cpu, part, ios[rw]); part_stat_add(cpu, part, sectors[rw], sectors); part_inc_in_flight(q, part, rw); part_stat_unlock(); } EXPORT_SYMBOL(generic_start_io_acct); void generic_end_io_acct(struct request_queue *q, int rw, struct hd_struct *part, unsigned long start_time) { unsigned long duration = jiffies - start_time; int cpu = part_stat_lock(); part_stat_add(cpu, part, ticks[rw], duration); part_round_stats(q, cpu, part); part_dec_in_flight(q, part, rw); part_stat_unlock(); } EXPORT_SYMBOL(generic_end_io_acct); #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE void bio_flush_dcache_pages(struct bio *bi) { struct bio_vec bvec; struct bvec_iter iter; bio_for_each_segment(bvec, bi, iter) flush_dcache_page(bvec.bv_page); } EXPORT_SYMBOL(bio_flush_dcache_pages); #endif static inline bool bio_remaining_done(struct bio *bio) { /* * If we're not chaining, then ->__bi_remaining is always 1 and * we always end io on the first invocation. */ if (!bio_flagged(bio, BIO_CHAIN)) return true; BUG_ON(atomic_read(&bio->__bi_remaining) <= 0); if (atomic_dec_and_test(&bio->__bi_remaining)) { bio_clear_flag(bio, BIO_CHAIN); return true; } return false; } /** * bio_endio - end I/O on a bio * @bio: bio * * Description: * bio_endio() will end I/O on the whole bio. bio_endio() is the preferred * way to end I/O on a bio. No one should call bi_end_io() directly on a * bio unless they own it and thus know that it has an end_io function. * * bio_endio() can be called several times on a bio that has been chained * using bio_chain(). The ->bi_end_io() function will only be called the * last time. At this point the BLK_TA_COMPLETE tracing event will be * generated if BIO_TRACE_COMPLETION is set. **/ void bio_endio(struct bio *bio) { again: if (!bio_remaining_done(bio)) return; if (!bio_integrity_endio(bio)) return; /* * Need to have a real endio function for chained bios, otherwise * various corner cases will break (like stacking block devices that * save/restore bi_end_io) - however, we want to avoid unbounded * recursion and blowing the stack. Tail call optimization would * handle this, but compiling with frame pointers also disables * gcc's sibling call optimization. */ if (bio->bi_end_io == bio_chain_endio) { bio = __bio_chain_endio(bio); goto again; } if (bio->bi_disk && bio_flagged(bio, BIO_TRACE_COMPLETION)) { trace_block_bio_complete(bio->bi_disk->queue, bio, blk_status_to_errno(bio->bi_status)); bio_clear_flag(bio, BIO_TRACE_COMPLETION); } blk_throtl_bio_endio(bio); /* release cgroup info */ bio_uninit(bio); if (bio->bi_end_io) bio->bi_end_io(bio); } EXPORT_SYMBOL(bio_endio); /** * bio_split - split a bio * @bio: bio to split * @sectors: number of sectors to split from the front of @bio * @gfp: gfp mask * @bs: bio set to allocate from * * Allocates and returns a new bio which represents @sectors from the start of * @bio, and updates @bio to represent the remaining sectors. * * Unless this is a discard request the newly allocated bio will point * to @bio's bi_io_vec; it is the caller's responsibility to ensure that * @bio is not freed before the split. */ struct bio *bio_split(struct bio *bio, int sectors, gfp_t gfp, struct bio_set *bs) { struct bio *split = NULL; BUG_ON(sectors <= 0); BUG_ON(sectors >= bio_sectors(bio)); split = bio_clone_fast(bio, gfp, bs); if (!split) return NULL; split->bi_iter.bi_size = sectors << 9; if (bio_integrity(split)) bio_integrity_trim(split); bio_advance(bio, split->bi_iter.bi_size); if (bio_flagged(bio, BIO_TRACE_COMPLETION)) bio_set_flag(bio, BIO_TRACE_COMPLETION); return split; } EXPORT_SYMBOL(bio_split); /** * bio_trim - trim a bio * @bio: bio to trim * @offset: number of sectors to trim from the front of @bio * @size: size we want to trim @bio to, in sectors */ void bio_trim(struct bio *bio, int offset, int size) { /* 'bio' is a cloned bio which we need to trim to match * the given offset and size. */ size <<= 9; if (offset == 0 && size == bio->bi_iter.bi_size) return; bio_clear_flag(bio, BIO_SEG_VALID); bio_advance(bio, offset << 9); bio->bi_iter.bi_size = size; if (bio_integrity(bio)) bio_integrity_trim(bio); } EXPORT_SYMBOL_GPL(bio_trim); /* * create memory pools for biovec's in a bio_set. * use the global biovec slabs created for general use. */ mempool_t *biovec_create_pool(int pool_entries) { struct biovec_slab *bp = bvec_slabs + BVEC_POOL_MAX; return mempool_create_slab_pool(pool_entries, bp->slab); } void bioset_free(struct bio_set *bs) { if (bs->rescue_workqueue) destroy_workqueue(bs->rescue_workqueue); if (bs->bio_pool) mempool_destroy(bs->bio_pool); if (bs->bvec_pool) mempool_destroy(bs->bvec_pool); bioset_integrity_free(bs); bio_put_slab(bs); kfree(bs); } EXPORT_SYMBOL(bioset_free); /** * bioset_create - Create a bio_set * @pool_size: Number of bio and bio_vecs to cache in the mempool * @front_pad: Number of bytes to allocate in front of the returned bio * @flags: Flags to modify behavior, currently %BIOSET_NEED_BVECS * and %BIOSET_NEED_RESCUER * * Description: * Set up a bio_set to be used with @bio_alloc_bioset. Allows the caller * to ask for a number of bytes to be allocated in front of the bio. * Front pad allocation is useful for embedding the bio inside * another structure, to avoid allocating extra data to go with the bio. * Note that the bio must be embedded at the END of that structure always, * or things will break badly. * If %BIOSET_NEED_BVECS is set in @flags, a separate pool will be allocated * for allocating iovecs. This pool is not needed e.g. for bio_clone_fast(). * If %BIOSET_NEED_RESCUER is set, a workqueue is created which can be used to * dispatch queued requests when the mempool runs out of space. * */ struct bio_set *bioset_create(unsigned int pool_size, unsigned int front_pad, int flags) { unsigned int back_pad = BIO_INLINE_VECS * sizeof(struct bio_vec); struct bio_set *bs; bs = kzalloc(sizeof(*bs), GFP_KERNEL); if (!bs) return NULL; bs->front_pad = front_pad; spin_lock_init(&bs->rescue_lock); bio_list_init(&bs->rescue_list); INIT_WORK(&bs->rescue_work, bio_alloc_rescue); bs->bio_slab = bio_find_or_create_slab(front_pad + back_pad); if (!bs->bio_slab) { kfree(bs); return NULL; } bs->bio_pool = mempool_create_slab_pool(pool_size, bs->bio_slab); if (!bs->bio_pool) goto bad; if (flags & BIOSET_NEED_BVECS) { bs->bvec_pool = biovec_create_pool(pool_size); if (!bs->bvec_pool) goto bad; } if (!(flags & BIOSET_NEED_RESCUER)) return bs; bs->rescue_workqueue = alloc_workqueue("bioset", WQ_MEM_RECLAIM, 0); if (!bs->rescue_workqueue) goto bad; return bs; bad: bioset_free(bs); return NULL; } EXPORT_SYMBOL(bioset_create); #ifdef CONFIG_BLK_CGROUP /** * bio_associate_blkcg - associate a bio with the specified blkcg * @bio: target bio * @blkcg_css: css of the blkcg to associate * * Associate @bio with the blkcg specified by @blkcg_css. Block layer will * treat @bio as if it were issued by a task which belongs to the blkcg. * * This function takes an extra reference of @blkcg_css which will be put * when @bio is released. The caller must own @bio and is responsible for * synchronizing calls to this function. */ int bio_associate_blkcg(struct bio *bio, struct cgroup_subsys_state *blkcg_css) { if (unlikely(bio->bi_css)) return -EBUSY; css_get(blkcg_css); bio->bi_css = blkcg_css; return 0; } EXPORT_SYMBOL_GPL(bio_associate_blkcg); /** * bio_associate_current - associate a bio with %current * @bio: target bio * * Associate @bio with %current if it hasn't been associated yet. Block * layer will treat @bio as if it were issued by %current no matter which * task actually issues it. * * This function takes an extra reference of @task's io_context and blkcg * which will be put when @bio is released. The caller must own @bio, * ensure %current->io_context exists, and is responsible for synchronizing * calls to this function. */ int bio_associate_current(struct bio *bio) { struct io_context *ioc; if (bio->bi_css) return -EBUSY; ioc = current->io_context; if (!ioc) return -ENOENT; get_io_context_active(ioc); bio->bi_ioc = ioc; bio->bi_css = task_get_css(current, io_cgrp_id); return 0; } EXPORT_SYMBOL_GPL(bio_associate_current); /** * bio_disassociate_task - undo bio_associate_current() * @bio: target bio */ void bio_disassociate_task(struct bio *bio) { if (bio->bi_ioc) { put_io_context(bio->bi_ioc); bio->bi_ioc = NULL; } if (bio->bi_css) { css_put(bio->bi_css); bio->bi_css = NULL; } } /** * bio_clone_blkcg_association - clone blkcg association from src to dst bio * @dst: destination bio * @src: source bio */ void bio_clone_blkcg_association(struct bio *dst, struct bio *src) { if (src->bi_css) WARN_ON(bio_associate_blkcg(dst, src->bi_css)); } EXPORT_SYMBOL_GPL(bio_clone_blkcg_association); #endif /* CONFIG_BLK_CGROUP */ static void __init biovec_init_slabs(void) { int i; for (i = 0; i < BVEC_POOL_NR; i++) { int size; struct biovec_slab *bvs = bvec_slabs + i; if (bvs->nr_vecs <= BIO_INLINE_VECS) { bvs->slab = NULL; continue; } size = bvs->nr_vecs * sizeof(struct bio_vec); bvs->slab = kmem_cache_create(bvs->name, size, 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); } } static int __init init_bio(void) { bio_slab_max = 2; bio_slab_nr = 0; bio_slabs = kzalloc(bio_slab_max * sizeof(struct bio_slab), GFP_KERNEL); if (!bio_slabs) panic("bio: can't allocate bios\n"); bio_integrity_init(); biovec_init_slabs(); fs_bio_set = bioset_create(BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS); if (!fs_bio_set) panic("bio: can't allocate bios\n"); if (bioset_integrity_create(fs_bio_set, BIO_POOL_SIZE)) panic("bio: can't create integrity pool\n"); return 0; } subsys_initcall(init_bio);
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2603_0
crossvul-cpp_data_bad_653_0
/* * Serial Attached SCSI (SAS) Expander discovery and configuration * * Copyright (C) 2005 Adaptec, Inc. All rights reserved. * Copyright (C) 2005 Luben Tuikov <luben_tuikov@adaptec.com> * * This file is licensed under GPLv2. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <linux/scatterlist.h> #include <linux/blkdev.h> #include <linux/slab.h> #include "sas_internal.h" #include <scsi/sas_ata.h> #include <scsi/scsi_transport.h> #include <scsi/scsi_transport_sas.h> #include "../scsi_sas_internal.h" static int sas_discover_expander(struct domain_device *dev); static int sas_configure_routing(struct domain_device *dev, u8 *sas_addr); static int sas_configure_phy(struct domain_device *dev, int phy_id, u8 *sas_addr, int include); static int sas_disable_routing(struct domain_device *dev, u8 *sas_addr); /* ---------- SMP task management ---------- */ static void smp_task_timedout(struct timer_list *t) { struct sas_task_slow *slow = from_timer(slow, t, timer); struct sas_task *task = slow->task; unsigned long flags; spin_lock_irqsave(&task->task_state_lock, flags); if (!(task->task_state_flags & SAS_TASK_STATE_DONE)) task->task_state_flags |= SAS_TASK_STATE_ABORTED; spin_unlock_irqrestore(&task->task_state_lock, flags); complete(&task->slow_task->completion); } static void smp_task_done(struct sas_task *task) { if (!del_timer(&task->slow_task->timer)) return; complete(&task->slow_task->completion); } /* Give it some long enough timeout. In seconds. */ #define SMP_TIMEOUT 10 static int smp_execute_task_sg(struct domain_device *dev, struct scatterlist *req, struct scatterlist *resp) { int res, retry; struct sas_task *task = NULL; struct sas_internal *i = to_sas_internal(dev->port->ha->core.shost->transportt); mutex_lock(&dev->ex_dev.cmd_mutex); for (retry = 0; retry < 3; retry++) { if (test_bit(SAS_DEV_GONE, &dev->state)) { res = -ECOMM; break; } task = sas_alloc_slow_task(GFP_KERNEL); if (!task) { res = -ENOMEM; break; } task->dev = dev; task->task_proto = dev->tproto; task->smp_task.smp_req = *req; task->smp_task.smp_resp = *resp; task->task_done = smp_task_done; task->slow_task->timer.function = smp_task_timedout; task->slow_task->timer.expires = jiffies + SMP_TIMEOUT*HZ; add_timer(&task->slow_task->timer); res = i->dft->lldd_execute_task(task, GFP_KERNEL); if (res) { del_timer(&task->slow_task->timer); SAS_DPRINTK("executing SMP task failed:%d\n", res); break; } wait_for_completion(&task->slow_task->completion); res = -ECOMM; if ((task->task_state_flags & SAS_TASK_STATE_ABORTED)) { SAS_DPRINTK("smp task timed out or aborted\n"); i->dft->lldd_abort_task(task); if (!(task->task_state_flags & SAS_TASK_STATE_DONE)) { SAS_DPRINTK("SMP task aborted and not done\n"); break; } } if (task->task_status.resp == SAS_TASK_COMPLETE && task->task_status.stat == SAM_STAT_GOOD) { res = 0; break; } if (task->task_status.resp == SAS_TASK_COMPLETE && task->task_status.stat == SAS_DATA_UNDERRUN) { /* no error, but return the number of bytes of * underrun */ res = task->task_status.residual; break; } if (task->task_status.resp == SAS_TASK_COMPLETE && task->task_status.stat == SAS_DATA_OVERRUN) { res = -EMSGSIZE; break; } if (task->task_status.resp == SAS_TASK_UNDELIVERED && task->task_status.stat == SAS_DEVICE_UNKNOWN) break; else { SAS_DPRINTK("%s: task to dev %016llx response: 0x%x " "status 0x%x\n", __func__, SAS_ADDR(dev->sas_addr), task->task_status.resp, task->task_status.stat); sas_free_task(task); task = NULL; } } mutex_unlock(&dev->ex_dev.cmd_mutex); BUG_ON(retry == 3 && task != NULL); sas_free_task(task); return res; } static int smp_execute_task(struct domain_device *dev, void *req, int req_size, void *resp, int resp_size) { struct scatterlist req_sg; struct scatterlist resp_sg; sg_init_one(&req_sg, req, req_size); sg_init_one(&resp_sg, resp, resp_size); return smp_execute_task_sg(dev, &req_sg, &resp_sg); } /* ---------- Allocations ---------- */ static inline void *alloc_smp_req(int size) { u8 *p = kzalloc(size, GFP_KERNEL); if (p) p[0] = SMP_REQUEST; return p; } static inline void *alloc_smp_resp(int size) { return kzalloc(size, GFP_KERNEL); } static char sas_route_char(struct domain_device *dev, struct ex_phy *phy) { switch (phy->routing_attr) { case TABLE_ROUTING: if (dev->ex_dev.t2t_supp) return 'U'; else return 'T'; case DIRECT_ROUTING: return 'D'; case SUBTRACTIVE_ROUTING: return 'S'; default: return '?'; } } static enum sas_device_type to_dev_type(struct discover_resp *dr) { /* This is detecting a failure to transmit initial dev to host * FIS as described in section J.5 of sas-2 r16 */ if (dr->attached_dev_type == SAS_PHY_UNUSED && dr->attached_sata_dev && dr->linkrate >= SAS_LINK_RATE_1_5_GBPS) return SAS_SATA_PENDING; else return dr->attached_dev_type; } static void sas_set_ex_phy(struct domain_device *dev, int phy_id, void *rsp) { enum sas_device_type dev_type; enum sas_linkrate linkrate; u8 sas_addr[SAS_ADDR_SIZE]; struct smp_resp *resp = rsp; struct discover_resp *dr = &resp->disc; struct sas_ha_struct *ha = dev->port->ha; struct expander_device *ex = &dev->ex_dev; struct ex_phy *phy = &ex->ex_phy[phy_id]; struct sas_rphy *rphy = dev->rphy; bool new_phy = !phy->phy; char *type; if (new_phy) { if (WARN_ON_ONCE(test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state))) return; phy->phy = sas_phy_alloc(&rphy->dev, phy_id); /* FIXME: error_handling */ BUG_ON(!phy->phy); } switch (resp->result) { case SMP_RESP_PHY_VACANT: phy->phy_state = PHY_VACANT; break; default: phy->phy_state = PHY_NOT_PRESENT; break; case SMP_RESP_FUNC_ACC: phy->phy_state = PHY_EMPTY; /* do not know yet */ break; } /* check if anything important changed to squelch debug */ dev_type = phy->attached_dev_type; linkrate = phy->linkrate; memcpy(sas_addr, phy->attached_sas_addr, SAS_ADDR_SIZE); /* Handle vacant phy - rest of dr data is not valid so skip it */ if (phy->phy_state == PHY_VACANT) { memset(phy->attached_sas_addr, 0, SAS_ADDR_SIZE); phy->attached_dev_type = SAS_PHY_UNUSED; if (!test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state)) { phy->phy_id = phy_id; goto skip; } else goto out; } phy->attached_dev_type = to_dev_type(dr); if (test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state)) goto out; phy->phy_id = phy_id; phy->linkrate = dr->linkrate; phy->attached_sata_host = dr->attached_sata_host; phy->attached_sata_dev = dr->attached_sata_dev; phy->attached_sata_ps = dr->attached_sata_ps; phy->attached_iproto = dr->iproto << 1; phy->attached_tproto = dr->tproto << 1; /* help some expanders that fail to zero sas_address in the 'no * device' case */ if (phy->attached_dev_type == SAS_PHY_UNUSED || phy->linkrate < SAS_LINK_RATE_1_5_GBPS) memset(phy->attached_sas_addr, 0, SAS_ADDR_SIZE); else memcpy(phy->attached_sas_addr, dr->attached_sas_addr, SAS_ADDR_SIZE); phy->attached_phy_id = dr->attached_phy_id; phy->phy_change_count = dr->change_count; phy->routing_attr = dr->routing_attr; phy->virtual = dr->virtual; phy->last_da_index = -1; phy->phy->identify.sas_address = SAS_ADDR(phy->attached_sas_addr); phy->phy->identify.device_type = dr->attached_dev_type; phy->phy->identify.initiator_port_protocols = phy->attached_iproto; phy->phy->identify.target_port_protocols = phy->attached_tproto; if (!phy->attached_tproto && dr->attached_sata_dev) phy->phy->identify.target_port_protocols = SAS_PROTOCOL_SATA; phy->phy->identify.phy_identifier = phy_id; phy->phy->minimum_linkrate_hw = dr->hmin_linkrate; phy->phy->maximum_linkrate_hw = dr->hmax_linkrate; phy->phy->minimum_linkrate = dr->pmin_linkrate; phy->phy->maximum_linkrate = dr->pmax_linkrate; phy->phy->negotiated_linkrate = phy->linkrate; skip: if (new_phy) if (sas_phy_add(phy->phy)) { sas_phy_free(phy->phy); return; } out: switch (phy->attached_dev_type) { case SAS_SATA_PENDING: type = "stp pending"; break; case SAS_PHY_UNUSED: type = "no device"; break; case SAS_END_DEVICE: if (phy->attached_iproto) { if (phy->attached_tproto) type = "host+target"; else type = "host"; } else { if (dr->attached_sata_dev) type = "stp"; else type = "ssp"; } break; case SAS_EDGE_EXPANDER_DEVICE: case SAS_FANOUT_EXPANDER_DEVICE: type = "smp"; break; default: type = "unknown"; } /* this routine is polled by libata error recovery so filter * unimportant messages */ if (new_phy || phy->attached_dev_type != dev_type || phy->linkrate != linkrate || SAS_ADDR(phy->attached_sas_addr) != SAS_ADDR(sas_addr)) /* pass */; else return; /* if the attached device type changed and ata_eh is active, * make sure we run revalidation when eh completes (see: * sas_enable_revalidation) */ if (test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state)) set_bit(DISCE_REVALIDATE_DOMAIN, &dev->port->disc.pending); SAS_DPRINTK("%sex %016llx phy%02d:%c:%X attached: %016llx (%s)\n", test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state) ? "ata: " : "", SAS_ADDR(dev->sas_addr), phy->phy_id, sas_route_char(dev, phy), phy->linkrate, SAS_ADDR(phy->attached_sas_addr), type); } /* check if we have an existing attached ata device on this expander phy */ struct domain_device *sas_ex_to_ata(struct domain_device *ex_dev, int phy_id) { struct ex_phy *ex_phy = &ex_dev->ex_dev.ex_phy[phy_id]; struct domain_device *dev; struct sas_rphy *rphy; if (!ex_phy->port) return NULL; rphy = ex_phy->port->rphy; if (!rphy) return NULL; dev = sas_find_dev_by_rphy(rphy); if (dev && dev_is_sata(dev)) return dev; return NULL; } #define DISCOVER_REQ_SIZE 16 #define DISCOVER_RESP_SIZE 56 static int sas_ex_phy_discover_helper(struct domain_device *dev, u8 *disc_req, u8 *disc_resp, int single) { struct discover_resp *dr; int res; disc_req[9] = single; res = smp_execute_task(dev, disc_req, DISCOVER_REQ_SIZE, disc_resp, DISCOVER_RESP_SIZE); if (res) return res; dr = &((struct smp_resp *)disc_resp)->disc; if (memcmp(dev->sas_addr, dr->attached_sas_addr, SAS_ADDR_SIZE) == 0) { sas_printk("Found loopback topology, just ignore it!\n"); return 0; } sas_set_ex_phy(dev, single, disc_resp); return 0; } int sas_ex_phy_discover(struct domain_device *dev, int single) { struct expander_device *ex = &dev->ex_dev; int res = 0; u8 *disc_req; u8 *disc_resp; disc_req = alloc_smp_req(DISCOVER_REQ_SIZE); if (!disc_req) return -ENOMEM; disc_resp = alloc_smp_resp(DISCOVER_RESP_SIZE); if (!disc_resp) { kfree(disc_req); return -ENOMEM; } disc_req[1] = SMP_DISCOVER; if (0 <= single && single < ex->num_phys) { res = sas_ex_phy_discover_helper(dev, disc_req, disc_resp, single); } else { int i; for (i = 0; i < ex->num_phys; i++) { res = sas_ex_phy_discover_helper(dev, disc_req, disc_resp, i); if (res) goto out_err; } } out_err: kfree(disc_resp); kfree(disc_req); return res; } static int sas_expander_discover(struct domain_device *dev) { struct expander_device *ex = &dev->ex_dev; int res = -ENOMEM; ex->ex_phy = kzalloc(sizeof(*ex->ex_phy)*ex->num_phys, GFP_KERNEL); if (!ex->ex_phy) return -ENOMEM; res = sas_ex_phy_discover(dev, -1); if (res) goto out_err; return 0; out_err: kfree(ex->ex_phy); ex->ex_phy = NULL; return res; } #define MAX_EXPANDER_PHYS 128 static void ex_assign_report_general(struct domain_device *dev, struct smp_resp *resp) { struct report_general_resp *rg = &resp->rg; dev->ex_dev.ex_change_count = be16_to_cpu(rg->change_count); dev->ex_dev.max_route_indexes = be16_to_cpu(rg->route_indexes); dev->ex_dev.num_phys = min(rg->num_phys, (u8)MAX_EXPANDER_PHYS); dev->ex_dev.t2t_supp = rg->t2t_supp; dev->ex_dev.conf_route_table = rg->conf_route_table; dev->ex_dev.configuring = rg->configuring; memcpy(dev->ex_dev.enclosure_logical_id, rg->enclosure_logical_id, 8); } #define RG_REQ_SIZE 8 #define RG_RESP_SIZE 32 static int sas_ex_general(struct domain_device *dev) { u8 *rg_req; struct smp_resp *rg_resp; int res; int i; rg_req = alloc_smp_req(RG_REQ_SIZE); if (!rg_req) return -ENOMEM; rg_resp = alloc_smp_resp(RG_RESP_SIZE); if (!rg_resp) { kfree(rg_req); return -ENOMEM; } rg_req[1] = SMP_REPORT_GENERAL; for (i = 0; i < 5; i++) { res = smp_execute_task(dev, rg_req, RG_REQ_SIZE, rg_resp, RG_RESP_SIZE); if (res) { SAS_DPRINTK("RG to ex %016llx failed:0x%x\n", SAS_ADDR(dev->sas_addr), res); goto out; } else if (rg_resp->result != SMP_RESP_FUNC_ACC) { SAS_DPRINTK("RG:ex %016llx returned SMP result:0x%x\n", SAS_ADDR(dev->sas_addr), rg_resp->result); res = rg_resp->result; goto out; } ex_assign_report_general(dev, rg_resp); if (dev->ex_dev.configuring) { SAS_DPRINTK("RG: ex %llx self-configuring...\n", SAS_ADDR(dev->sas_addr)); schedule_timeout_interruptible(5*HZ); } else break; } out: kfree(rg_req); kfree(rg_resp); return res; } static void ex_assign_manuf_info(struct domain_device *dev, void *_mi_resp) { u8 *mi_resp = _mi_resp; struct sas_rphy *rphy = dev->rphy; struct sas_expander_device *edev = rphy_to_expander_device(rphy); memcpy(edev->vendor_id, mi_resp + 12, SAS_EXPANDER_VENDOR_ID_LEN); memcpy(edev->product_id, mi_resp + 20, SAS_EXPANDER_PRODUCT_ID_LEN); memcpy(edev->product_rev, mi_resp + 36, SAS_EXPANDER_PRODUCT_REV_LEN); if (mi_resp[8] & 1) { memcpy(edev->component_vendor_id, mi_resp + 40, SAS_EXPANDER_COMPONENT_VENDOR_ID_LEN); edev->component_id = mi_resp[48] << 8 | mi_resp[49]; edev->component_revision_id = mi_resp[50]; } } #define MI_REQ_SIZE 8 #define MI_RESP_SIZE 64 static int sas_ex_manuf_info(struct domain_device *dev) { u8 *mi_req; u8 *mi_resp; int res; mi_req = alloc_smp_req(MI_REQ_SIZE); if (!mi_req) return -ENOMEM; mi_resp = alloc_smp_resp(MI_RESP_SIZE); if (!mi_resp) { kfree(mi_req); return -ENOMEM; } mi_req[1] = SMP_REPORT_MANUF_INFO; res = smp_execute_task(dev, mi_req, MI_REQ_SIZE, mi_resp,MI_RESP_SIZE); if (res) { SAS_DPRINTK("MI: ex %016llx failed:0x%x\n", SAS_ADDR(dev->sas_addr), res); goto out; } else if (mi_resp[2] != SMP_RESP_FUNC_ACC) { SAS_DPRINTK("MI ex %016llx returned SMP result:0x%x\n", SAS_ADDR(dev->sas_addr), mi_resp[2]); goto out; } ex_assign_manuf_info(dev, mi_resp); out: kfree(mi_req); kfree(mi_resp); return res; } #define PC_REQ_SIZE 44 #define PC_RESP_SIZE 8 int sas_smp_phy_control(struct domain_device *dev, int phy_id, enum phy_func phy_func, struct sas_phy_linkrates *rates) { u8 *pc_req; u8 *pc_resp; int res; pc_req = alloc_smp_req(PC_REQ_SIZE); if (!pc_req) return -ENOMEM; pc_resp = alloc_smp_resp(PC_RESP_SIZE); if (!pc_resp) { kfree(pc_req); return -ENOMEM; } pc_req[1] = SMP_PHY_CONTROL; pc_req[9] = phy_id; pc_req[10]= phy_func; if (rates) { pc_req[32] = rates->minimum_linkrate << 4; pc_req[33] = rates->maximum_linkrate << 4; } res = smp_execute_task(dev, pc_req, PC_REQ_SIZE, pc_resp,PC_RESP_SIZE); kfree(pc_resp); kfree(pc_req); return res; } static void sas_ex_disable_phy(struct domain_device *dev, int phy_id) { struct expander_device *ex = &dev->ex_dev; struct ex_phy *phy = &ex->ex_phy[phy_id]; sas_smp_phy_control(dev, phy_id, PHY_FUNC_DISABLE, NULL); phy->linkrate = SAS_PHY_DISABLED; } static void sas_ex_disable_port(struct domain_device *dev, u8 *sas_addr) { struct expander_device *ex = &dev->ex_dev; int i; for (i = 0; i < ex->num_phys; i++) { struct ex_phy *phy = &ex->ex_phy[i]; if (phy->phy_state == PHY_VACANT || phy->phy_state == PHY_NOT_PRESENT) continue; if (SAS_ADDR(phy->attached_sas_addr) == SAS_ADDR(sas_addr)) sas_ex_disable_phy(dev, i); } } static int sas_dev_present_in_domain(struct asd_sas_port *port, u8 *sas_addr) { struct domain_device *dev; if (SAS_ADDR(port->sas_addr) == SAS_ADDR(sas_addr)) return 1; list_for_each_entry(dev, &port->dev_list, dev_list_node) { if (SAS_ADDR(dev->sas_addr) == SAS_ADDR(sas_addr)) return 1; } return 0; } #define RPEL_REQ_SIZE 16 #define RPEL_RESP_SIZE 32 int sas_smp_get_phy_events(struct sas_phy *phy) { int res; u8 *req; u8 *resp; struct sas_rphy *rphy = dev_to_rphy(phy->dev.parent); struct domain_device *dev = sas_find_dev_by_rphy(rphy); req = alloc_smp_req(RPEL_REQ_SIZE); if (!req) return -ENOMEM; resp = alloc_smp_resp(RPEL_RESP_SIZE); if (!resp) { kfree(req); return -ENOMEM; } req[1] = SMP_REPORT_PHY_ERR_LOG; req[9] = phy->number; res = smp_execute_task(dev, req, RPEL_REQ_SIZE, resp, RPEL_RESP_SIZE); if (!res) goto out; phy->invalid_dword_count = scsi_to_u32(&resp[12]); phy->running_disparity_error_count = scsi_to_u32(&resp[16]); phy->loss_of_dword_sync_count = scsi_to_u32(&resp[20]); phy->phy_reset_problem_count = scsi_to_u32(&resp[24]); out: kfree(resp); return res; } #ifdef CONFIG_SCSI_SAS_ATA #define RPS_REQ_SIZE 16 #define RPS_RESP_SIZE 60 int sas_get_report_phy_sata(struct domain_device *dev, int phy_id, struct smp_resp *rps_resp) { int res; u8 *rps_req = alloc_smp_req(RPS_REQ_SIZE); u8 *resp = (u8 *)rps_resp; if (!rps_req) return -ENOMEM; rps_req[1] = SMP_REPORT_PHY_SATA; rps_req[9] = phy_id; res = smp_execute_task(dev, rps_req, RPS_REQ_SIZE, rps_resp, RPS_RESP_SIZE); /* 0x34 is the FIS type for the D2H fis. There's a potential * standards cockup here. sas-2 explicitly specifies the FIS * should be encoded so that FIS type is in resp[24]. * However, some expanders endian reverse this. Undo the * reversal here */ if (!res && resp[27] == 0x34 && resp[24] != 0x34) { int i; for (i = 0; i < 5; i++) { int j = 24 + (i*4); u8 a, b; a = resp[j + 0]; b = resp[j + 1]; resp[j + 0] = resp[j + 3]; resp[j + 1] = resp[j + 2]; resp[j + 2] = b; resp[j + 3] = a; } } kfree(rps_req); return res; } #endif static void sas_ex_get_linkrate(struct domain_device *parent, struct domain_device *child, struct ex_phy *parent_phy) { struct expander_device *parent_ex = &parent->ex_dev; struct sas_port *port; int i; child->pathways = 0; port = parent_phy->port; for (i = 0; i < parent_ex->num_phys; i++) { struct ex_phy *phy = &parent_ex->ex_phy[i]; if (phy->phy_state == PHY_VACANT || phy->phy_state == PHY_NOT_PRESENT) continue; if (SAS_ADDR(phy->attached_sas_addr) == SAS_ADDR(child->sas_addr)) { child->min_linkrate = min(parent->min_linkrate, phy->linkrate); child->max_linkrate = max(parent->max_linkrate, phy->linkrate); child->pathways++; sas_port_add_phy(port, phy->phy); } } child->linkrate = min(parent_phy->linkrate, child->max_linkrate); child->pathways = min(child->pathways, parent->pathways); } static struct domain_device *sas_ex_discover_end_dev( struct domain_device *parent, int phy_id) { struct expander_device *parent_ex = &parent->ex_dev; struct ex_phy *phy = &parent_ex->ex_phy[phy_id]; struct domain_device *child = NULL; struct sas_rphy *rphy; int res; if (phy->attached_sata_host || phy->attached_sata_ps) return NULL; child = sas_alloc_device(); if (!child) return NULL; kref_get(&parent->kref); child->parent = parent; child->port = parent->port; child->iproto = phy->attached_iproto; memcpy(child->sas_addr, phy->attached_sas_addr, SAS_ADDR_SIZE); sas_hash_addr(child->hashed_sas_addr, child->sas_addr); if (!phy->port) { phy->port = sas_port_alloc(&parent->rphy->dev, phy_id); if (unlikely(!phy->port)) goto out_err; if (unlikely(sas_port_add(phy->port) != 0)) { sas_port_free(phy->port); goto out_err; } } sas_ex_get_linkrate(parent, child, phy); sas_device_set_phy(child, phy->port); #ifdef CONFIG_SCSI_SAS_ATA if ((phy->attached_tproto & SAS_PROTOCOL_STP) || phy->attached_sata_dev) { res = sas_get_ata_info(child, phy); if (res) goto out_free; sas_init_dev(child); res = sas_ata_init(child); if (res) goto out_free; rphy = sas_end_device_alloc(phy->port); if (!rphy) goto out_free; child->rphy = rphy; get_device(&rphy->dev); list_add_tail(&child->disco_list_node, &parent->port->disco_list); res = sas_discover_sata(child); if (res) { SAS_DPRINTK("sas_discover_sata() for device %16llx at " "%016llx:0x%x returned 0x%x\n", SAS_ADDR(child->sas_addr), SAS_ADDR(parent->sas_addr), phy_id, res); goto out_list_del; } } else #endif if (phy->attached_tproto & SAS_PROTOCOL_SSP) { child->dev_type = SAS_END_DEVICE; rphy = sas_end_device_alloc(phy->port); /* FIXME: error handling */ if (unlikely(!rphy)) goto out_free; child->tproto = phy->attached_tproto; sas_init_dev(child); child->rphy = rphy; get_device(&rphy->dev); sas_fill_in_rphy(child, rphy); list_add_tail(&child->disco_list_node, &parent->port->disco_list); res = sas_discover_end_dev(child); if (res) { SAS_DPRINTK("sas_discover_end_dev() for device %16llx " "at %016llx:0x%x returned 0x%x\n", SAS_ADDR(child->sas_addr), SAS_ADDR(parent->sas_addr), phy_id, res); goto out_list_del; } } else { SAS_DPRINTK("target proto 0x%x at %016llx:0x%x not handled\n", phy->attached_tproto, SAS_ADDR(parent->sas_addr), phy_id); goto out_free; } list_add_tail(&child->siblings, &parent_ex->children); return child; out_list_del: sas_rphy_free(child->rphy); list_del(&child->disco_list_node); spin_lock_irq(&parent->port->dev_list_lock); list_del(&child->dev_list_node); spin_unlock_irq(&parent->port->dev_list_lock); out_free: sas_port_delete(phy->port); out_err: phy->port = NULL; sas_put_device(child); return NULL; } /* See if this phy is part of a wide port */ static bool sas_ex_join_wide_port(struct domain_device *parent, int phy_id) { struct ex_phy *phy = &parent->ex_dev.ex_phy[phy_id]; int i; for (i = 0; i < parent->ex_dev.num_phys; i++) { struct ex_phy *ephy = &parent->ex_dev.ex_phy[i]; if (ephy == phy) continue; if (!memcmp(phy->attached_sas_addr, ephy->attached_sas_addr, SAS_ADDR_SIZE) && ephy->port) { sas_port_add_phy(ephy->port, phy->phy); phy->port = ephy->port; phy->phy_state = PHY_DEVICE_DISCOVERED; return true; } } return false; } static struct domain_device *sas_ex_discover_expander( struct domain_device *parent, int phy_id) { struct sas_expander_device *parent_ex = rphy_to_expander_device(parent->rphy); struct ex_phy *phy = &parent->ex_dev.ex_phy[phy_id]; struct domain_device *child = NULL; struct sas_rphy *rphy; struct sas_expander_device *edev; struct asd_sas_port *port; int res; if (phy->routing_attr == DIRECT_ROUTING) { SAS_DPRINTK("ex %016llx:0x%x:D <--> ex %016llx:0x%x is not " "allowed\n", SAS_ADDR(parent->sas_addr), phy_id, SAS_ADDR(phy->attached_sas_addr), phy->attached_phy_id); return NULL; } child = sas_alloc_device(); if (!child) return NULL; phy->port = sas_port_alloc(&parent->rphy->dev, phy_id); /* FIXME: better error handling */ BUG_ON(sas_port_add(phy->port) != 0); switch (phy->attached_dev_type) { case SAS_EDGE_EXPANDER_DEVICE: rphy = sas_expander_alloc(phy->port, SAS_EDGE_EXPANDER_DEVICE); break; case SAS_FANOUT_EXPANDER_DEVICE: rphy = sas_expander_alloc(phy->port, SAS_FANOUT_EXPANDER_DEVICE); break; default: rphy = NULL; /* shut gcc up */ BUG(); } port = parent->port; child->rphy = rphy; get_device(&rphy->dev); edev = rphy_to_expander_device(rphy); child->dev_type = phy->attached_dev_type; kref_get(&parent->kref); child->parent = parent; child->port = port; child->iproto = phy->attached_iproto; child->tproto = phy->attached_tproto; memcpy(child->sas_addr, phy->attached_sas_addr, SAS_ADDR_SIZE); sas_hash_addr(child->hashed_sas_addr, child->sas_addr); sas_ex_get_linkrate(parent, child, phy); edev->level = parent_ex->level + 1; parent->port->disc.max_level = max(parent->port->disc.max_level, edev->level); sas_init_dev(child); sas_fill_in_rphy(child, rphy); sas_rphy_add(rphy); spin_lock_irq(&parent->port->dev_list_lock); list_add_tail(&child->dev_list_node, &parent->port->dev_list); spin_unlock_irq(&parent->port->dev_list_lock); res = sas_discover_expander(child); if (res) { sas_rphy_delete(rphy); spin_lock_irq(&parent->port->dev_list_lock); list_del(&child->dev_list_node); spin_unlock_irq(&parent->port->dev_list_lock); sas_put_device(child); return NULL; } list_add_tail(&child->siblings, &parent->ex_dev.children); return child; } static int sas_ex_discover_dev(struct domain_device *dev, int phy_id) { struct expander_device *ex = &dev->ex_dev; struct ex_phy *ex_phy = &ex->ex_phy[phy_id]; struct domain_device *child = NULL; int res = 0; /* Phy state */ if (ex_phy->linkrate == SAS_SATA_SPINUP_HOLD) { if (!sas_smp_phy_control(dev, phy_id, PHY_FUNC_LINK_RESET, NULL)) res = sas_ex_phy_discover(dev, phy_id); if (res) return res; } /* Parent and domain coherency */ if (!dev->parent && (SAS_ADDR(ex_phy->attached_sas_addr) == SAS_ADDR(dev->port->sas_addr))) { sas_add_parent_port(dev, phy_id); return 0; } if (dev->parent && (SAS_ADDR(ex_phy->attached_sas_addr) == SAS_ADDR(dev->parent->sas_addr))) { sas_add_parent_port(dev, phy_id); if (ex_phy->routing_attr == TABLE_ROUTING) sas_configure_phy(dev, phy_id, dev->port->sas_addr, 1); return 0; } if (sas_dev_present_in_domain(dev->port, ex_phy->attached_sas_addr)) sas_ex_disable_port(dev, ex_phy->attached_sas_addr); if (ex_phy->attached_dev_type == SAS_PHY_UNUSED) { if (ex_phy->routing_attr == DIRECT_ROUTING) { memset(ex_phy->attached_sas_addr, 0, SAS_ADDR_SIZE); sas_configure_routing(dev, ex_phy->attached_sas_addr); } return 0; } else if (ex_phy->linkrate == SAS_LINK_RATE_UNKNOWN) return 0; if (ex_phy->attached_dev_type != SAS_END_DEVICE && ex_phy->attached_dev_type != SAS_FANOUT_EXPANDER_DEVICE && ex_phy->attached_dev_type != SAS_EDGE_EXPANDER_DEVICE && ex_phy->attached_dev_type != SAS_SATA_PENDING) { SAS_DPRINTK("unknown device type(0x%x) attached to ex %016llx " "phy 0x%x\n", ex_phy->attached_dev_type, SAS_ADDR(dev->sas_addr), phy_id); return 0; } res = sas_configure_routing(dev, ex_phy->attached_sas_addr); if (res) { SAS_DPRINTK("configure routing for dev %016llx " "reported 0x%x. Forgotten\n", SAS_ADDR(ex_phy->attached_sas_addr), res); sas_disable_routing(dev, ex_phy->attached_sas_addr); return res; } if (sas_ex_join_wide_port(dev, phy_id)) { SAS_DPRINTK("Attaching ex phy%d to wide port %016llx\n", phy_id, SAS_ADDR(ex_phy->attached_sas_addr)); return res; } switch (ex_phy->attached_dev_type) { case SAS_END_DEVICE: case SAS_SATA_PENDING: child = sas_ex_discover_end_dev(dev, phy_id); break; case SAS_FANOUT_EXPANDER_DEVICE: if (SAS_ADDR(dev->port->disc.fanout_sas_addr)) { SAS_DPRINTK("second fanout expander %016llx phy 0x%x " "attached to ex %016llx phy 0x%x\n", SAS_ADDR(ex_phy->attached_sas_addr), ex_phy->attached_phy_id, SAS_ADDR(dev->sas_addr), phy_id); sas_ex_disable_phy(dev, phy_id); break; } else memcpy(dev->port->disc.fanout_sas_addr, ex_phy->attached_sas_addr, SAS_ADDR_SIZE); /* fallthrough */ case SAS_EDGE_EXPANDER_DEVICE: child = sas_ex_discover_expander(dev, phy_id); break; default: break; } if (child) { int i; for (i = 0; i < ex->num_phys; i++) { if (ex->ex_phy[i].phy_state == PHY_VACANT || ex->ex_phy[i].phy_state == PHY_NOT_PRESENT) continue; /* * Due to races, the phy might not get added to the * wide port, so we add the phy to the wide port here. */ if (SAS_ADDR(ex->ex_phy[i].attached_sas_addr) == SAS_ADDR(child->sas_addr)) { ex->ex_phy[i].phy_state= PHY_DEVICE_DISCOVERED; if (sas_ex_join_wide_port(dev, i)) SAS_DPRINTK("Attaching ex phy%d to wide port %016llx\n", i, SAS_ADDR(ex->ex_phy[i].attached_sas_addr)); } } } return res; } static int sas_find_sub_addr(struct domain_device *dev, u8 *sub_addr) { struct expander_device *ex = &dev->ex_dev; int i; for (i = 0; i < ex->num_phys; i++) { struct ex_phy *phy = &ex->ex_phy[i]; if (phy->phy_state == PHY_VACANT || phy->phy_state == PHY_NOT_PRESENT) continue; if ((phy->attached_dev_type == SAS_EDGE_EXPANDER_DEVICE || phy->attached_dev_type == SAS_FANOUT_EXPANDER_DEVICE) && phy->routing_attr == SUBTRACTIVE_ROUTING) { memcpy(sub_addr, phy->attached_sas_addr,SAS_ADDR_SIZE); return 1; } } return 0; } static int sas_check_level_subtractive_boundary(struct domain_device *dev) { struct expander_device *ex = &dev->ex_dev; struct domain_device *child; u8 sub_addr[8] = {0, }; list_for_each_entry(child, &ex->children, siblings) { if (child->dev_type != SAS_EDGE_EXPANDER_DEVICE && child->dev_type != SAS_FANOUT_EXPANDER_DEVICE) continue; if (sub_addr[0] == 0) { sas_find_sub_addr(child, sub_addr); continue; } else { u8 s2[8]; if (sas_find_sub_addr(child, s2) && (SAS_ADDR(sub_addr) != SAS_ADDR(s2))) { SAS_DPRINTK("ex %016llx->%016llx-?->%016llx " "diverges from subtractive " "boundary %016llx\n", SAS_ADDR(dev->sas_addr), SAS_ADDR(child->sas_addr), SAS_ADDR(s2), SAS_ADDR(sub_addr)); sas_ex_disable_port(child, s2); } } } return 0; } /** * sas_ex_discover_devices -- discover devices attached to this expander * dev: pointer to the expander domain device * single: if you want to do a single phy, else set to -1; * * Configure this expander for use with its devices and register the * devices of this expander. */ static int sas_ex_discover_devices(struct domain_device *dev, int single) { struct expander_device *ex = &dev->ex_dev; int i = 0, end = ex->num_phys; int res = 0; if (0 <= single && single < end) { i = single; end = i+1; } for ( ; i < end; i++) { struct ex_phy *ex_phy = &ex->ex_phy[i]; if (ex_phy->phy_state == PHY_VACANT || ex_phy->phy_state == PHY_NOT_PRESENT || ex_phy->phy_state == PHY_DEVICE_DISCOVERED) continue; switch (ex_phy->linkrate) { case SAS_PHY_DISABLED: case SAS_PHY_RESET_PROBLEM: case SAS_SATA_PORT_SELECTOR: continue; default: res = sas_ex_discover_dev(dev, i); if (res) break; continue; } } if (!res) sas_check_level_subtractive_boundary(dev); return res; } static int sas_check_ex_subtractive_boundary(struct domain_device *dev) { struct expander_device *ex = &dev->ex_dev; int i; u8 *sub_sas_addr = NULL; if (dev->dev_type != SAS_EDGE_EXPANDER_DEVICE) return 0; for (i = 0; i < ex->num_phys; i++) { struct ex_phy *phy = &ex->ex_phy[i]; if (phy->phy_state == PHY_VACANT || phy->phy_state == PHY_NOT_PRESENT) continue; if ((phy->attached_dev_type == SAS_FANOUT_EXPANDER_DEVICE || phy->attached_dev_type == SAS_EDGE_EXPANDER_DEVICE) && phy->routing_attr == SUBTRACTIVE_ROUTING) { if (!sub_sas_addr) sub_sas_addr = &phy->attached_sas_addr[0]; else if (SAS_ADDR(sub_sas_addr) != SAS_ADDR(phy->attached_sas_addr)) { SAS_DPRINTK("ex %016llx phy 0x%x " "diverges(%016llx) on subtractive " "boundary(%016llx). Disabled\n", SAS_ADDR(dev->sas_addr), i, SAS_ADDR(phy->attached_sas_addr), SAS_ADDR(sub_sas_addr)); sas_ex_disable_phy(dev, i); } } } return 0; } static void sas_print_parent_topology_bug(struct domain_device *child, struct ex_phy *parent_phy, struct ex_phy *child_phy) { static const char *ex_type[] = { [SAS_EDGE_EXPANDER_DEVICE] = "edge", [SAS_FANOUT_EXPANDER_DEVICE] = "fanout", }; struct domain_device *parent = child->parent; sas_printk("%s ex %016llx phy 0x%x <--> %s ex %016llx " "phy 0x%x has %c:%c routing link!\n", ex_type[parent->dev_type], SAS_ADDR(parent->sas_addr), parent_phy->phy_id, ex_type[child->dev_type], SAS_ADDR(child->sas_addr), child_phy->phy_id, sas_route_char(parent, parent_phy), sas_route_char(child, child_phy)); } static int sas_check_eeds(struct domain_device *child, struct ex_phy *parent_phy, struct ex_phy *child_phy) { int res = 0; struct domain_device *parent = child->parent; if (SAS_ADDR(parent->port->disc.fanout_sas_addr) != 0) { res = -ENODEV; SAS_DPRINTK("edge ex %016llx phy S:0x%x <--> edge ex %016llx " "phy S:0x%x, while there is a fanout ex %016llx\n", SAS_ADDR(parent->sas_addr), parent_phy->phy_id, SAS_ADDR(child->sas_addr), child_phy->phy_id, SAS_ADDR(parent->port->disc.fanout_sas_addr)); } else if (SAS_ADDR(parent->port->disc.eeds_a) == 0) { memcpy(parent->port->disc.eeds_a, parent->sas_addr, SAS_ADDR_SIZE); memcpy(parent->port->disc.eeds_b, child->sas_addr, SAS_ADDR_SIZE); } else if (((SAS_ADDR(parent->port->disc.eeds_a) == SAS_ADDR(parent->sas_addr)) || (SAS_ADDR(parent->port->disc.eeds_a) == SAS_ADDR(child->sas_addr))) && ((SAS_ADDR(parent->port->disc.eeds_b) == SAS_ADDR(parent->sas_addr)) || (SAS_ADDR(parent->port->disc.eeds_b) == SAS_ADDR(child->sas_addr)))) ; else { res = -ENODEV; SAS_DPRINTK("edge ex %016llx phy 0x%x <--> edge ex %016llx " "phy 0x%x link forms a third EEDS!\n", SAS_ADDR(parent->sas_addr), parent_phy->phy_id, SAS_ADDR(child->sas_addr), child_phy->phy_id); } return res; } /* Here we spill over 80 columns. It is intentional. */ static int sas_check_parent_topology(struct domain_device *child) { struct expander_device *child_ex = &child->ex_dev; struct expander_device *parent_ex; int i; int res = 0; if (!child->parent) return 0; if (child->parent->dev_type != SAS_EDGE_EXPANDER_DEVICE && child->parent->dev_type != SAS_FANOUT_EXPANDER_DEVICE) return 0; parent_ex = &child->parent->ex_dev; for (i = 0; i < parent_ex->num_phys; i++) { struct ex_phy *parent_phy = &parent_ex->ex_phy[i]; struct ex_phy *child_phy; if (parent_phy->phy_state == PHY_VACANT || parent_phy->phy_state == PHY_NOT_PRESENT) continue; if (SAS_ADDR(parent_phy->attached_sas_addr) != SAS_ADDR(child->sas_addr)) continue; child_phy = &child_ex->ex_phy[parent_phy->attached_phy_id]; switch (child->parent->dev_type) { case SAS_EDGE_EXPANDER_DEVICE: if (child->dev_type == SAS_FANOUT_EXPANDER_DEVICE) { if (parent_phy->routing_attr != SUBTRACTIVE_ROUTING || child_phy->routing_attr != TABLE_ROUTING) { sas_print_parent_topology_bug(child, parent_phy, child_phy); res = -ENODEV; } } else if (parent_phy->routing_attr == SUBTRACTIVE_ROUTING) { if (child_phy->routing_attr == SUBTRACTIVE_ROUTING) { res = sas_check_eeds(child, parent_phy, child_phy); } else if (child_phy->routing_attr != TABLE_ROUTING) { sas_print_parent_topology_bug(child, parent_phy, child_phy); res = -ENODEV; } } else if (parent_phy->routing_attr == TABLE_ROUTING) { if (child_phy->routing_attr == SUBTRACTIVE_ROUTING || (child_phy->routing_attr == TABLE_ROUTING && child_ex->t2t_supp && parent_ex->t2t_supp)) { /* All good */; } else { sas_print_parent_topology_bug(child, parent_phy, child_phy); res = -ENODEV; } } break; case SAS_FANOUT_EXPANDER_DEVICE: if (parent_phy->routing_attr != TABLE_ROUTING || child_phy->routing_attr != SUBTRACTIVE_ROUTING) { sas_print_parent_topology_bug(child, parent_phy, child_phy); res = -ENODEV; } break; default: break; } } return res; } #define RRI_REQ_SIZE 16 #define RRI_RESP_SIZE 44 static int sas_configure_present(struct domain_device *dev, int phy_id, u8 *sas_addr, int *index, int *present) { int i, res = 0; struct expander_device *ex = &dev->ex_dev; struct ex_phy *phy = &ex->ex_phy[phy_id]; u8 *rri_req; u8 *rri_resp; *present = 0; *index = 0; rri_req = alloc_smp_req(RRI_REQ_SIZE); if (!rri_req) return -ENOMEM; rri_resp = alloc_smp_resp(RRI_RESP_SIZE); if (!rri_resp) { kfree(rri_req); return -ENOMEM; } rri_req[1] = SMP_REPORT_ROUTE_INFO; rri_req[9] = phy_id; for (i = 0; i < ex->max_route_indexes ; i++) { *(__be16 *)(rri_req+6) = cpu_to_be16(i); res = smp_execute_task(dev, rri_req, RRI_REQ_SIZE, rri_resp, RRI_RESP_SIZE); if (res) goto out; res = rri_resp[2]; if (res == SMP_RESP_NO_INDEX) { SAS_DPRINTK("overflow of indexes: dev %016llx " "phy 0x%x index 0x%x\n", SAS_ADDR(dev->sas_addr), phy_id, i); goto out; } else if (res != SMP_RESP_FUNC_ACC) { SAS_DPRINTK("%s: dev %016llx phy 0x%x index 0x%x " "result 0x%x\n", __func__, SAS_ADDR(dev->sas_addr), phy_id, i, res); goto out; } if (SAS_ADDR(sas_addr) != 0) { if (SAS_ADDR(rri_resp+16) == SAS_ADDR(sas_addr)) { *index = i; if ((rri_resp[12] & 0x80) == 0x80) *present = 0; else *present = 1; goto out; } else if (SAS_ADDR(rri_resp+16) == 0) { *index = i; *present = 0; goto out; } } else if (SAS_ADDR(rri_resp+16) == 0 && phy->last_da_index < i) { phy->last_da_index = i; *index = i; *present = 0; goto out; } } res = -1; out: kfree(rri_req); kfree(rri_resp); return res; } #define CRI_REQ_SIZE 44 #define CRI_RESP_SIZE 8 static int sas_configure_set(struct domain_device *dev, int phy_id, u8 *sas_addr, int index, int include) { int res; u8 *cri_req; u8 *cri_resp; cri_req = alloc_smp_req(CRI_REQ_SIZE); if (!cri_req) return -ENOMEM; cri_resp = alloc_smp_resp(CRI_RESP_SIZE); if (!cri_resp) { kfree(cri_req); return -ENOMEM; } cri_req[1] = SMP_CONF_ROUTE_INFO; *(__be16 *)(cri_req+6) = cpu_to_be16(index); cri_req[9] = phy_id; if (SAS_ADDR(sas_addr) == 0 || !include) cri_req[12] |= 0x80; memcpy(cri_req+16, sas_addr, SAS_ADDR_SIZE); res = smp_execute_task(dev, cri_req, CRI_REQ_SIZE, cri_resp, CRI_RESP_SIZE); if (res) goto out; res = cri_resp[2]; if (res == SMP_RESP_NO_INDEX) { SAS_DPRINTK("overflow of indexes: dev %016llx phy 0x%x " "index 0x%x\n", SAS_ADDR(dev->sas_addr), phy_id, index); } out: kfree(cri_req); kfree(cri_resp); return res; } static int sas_configure_phy(struct domain_device *dev, int phy_id, u8 *sas_addr, int include) { int index; int present; int res; res = sas_configure_present(dev, phy_id, sas_addr, &index, &present); if (res) return res; if (include ^ present) return sas_configure_set(dev, phy_id, sas_addr, index,include); return res; } /** * sas_configure_parent -- configure routing table of parent * parent: parent expander * child: child expander * sas_addr: SAS port identifier of device directly attached to child */ static int sas_configure_parent(struct domain_device *parent, struct domain_device *child, u8 *sas_addr, int include) { struct expander_device *ex_parent = &parent->ex_dev; int res = 0; int i; if (parent->parent) { res = sas_configure_parent(parent->parent, parent, sas_addr, include); if (res) return res; } if (ex_parent->conf_route_table == 0) { SAS_DPRINTK("ex %016llx has self-configuring routing table\n", SAS_ADDR(parent->sas_addr)); return 0; } for (i = 0; i < ex_parent->num_phys; i++) { struct ex_phy *phy = &ex_parent->ex_phy[i]; if ((phy->routing_attr == TABLE_ROUTING) && (SAS_ADDR(phy->attached_sas_addr) == SAS_ADDR(child->sas_addr))) { res = sas_configure_phy(parent, i, sas_addr, include); if (res) return res; } } return res; } /** * sas_configure_routing -- configure routing * dev: expander device * sas_addr: port identifier of device directly attached to the expander device */ static int sas_configure_routing(struct domain_device *dev, u8 *sas_addr) { if (dev->parent) return sas_configure_parent(dev->parent, dev, sas_addr, 1); return 0; } static int sas_disable_routing(struct domain_device *dev, u8 *sas_addr) { if (dev->parent) return sas_configure_parent(dev->parent, dev, sas_addr, 0); return 0; } /** * sas_discover_expander -- expander discovery * @ex: pointer to expander domain device * * See comment in sas_discover_sata(). */ static int sas_discover_expander(struct domain_device *dev) { int res; res = sas_notify_lldd_dev_found(dev); if (res) return res; res = sas_ex_general(dev); if (res) goto out_err; res = sas_ex_manuf_info(dev); if (res) goto out_err; res = sas_expander_discover(dev); if (res) { SAS_DPRINTK("expander %016llx discovery failed(0x%x)\n", SAS_ADDR(dev->sas_addr), res); goto out_err; } sas_check_ex_subtractive_boundary(dev); res = sas_check_parent_topology(dev); if (res) goto out_err; return 0; out_err: sas_notify_lldd_dev_gone(dev); return res; } static int sas_ex_level_discovery(struct asd_sas_port *port, const int level) { int res = 0; struct domain_device *dev; list_for_each_entry(dev, &port->dev_list, dev_list_node) { if (dev->dev_type == SAS_EDGE_EXPANDER_DEVICE || dev->dev_type == SAS_FANOUT_EXPANDER_DEVICE) { struct sas_expander_device *ex = rphy_to_expander_device(dev->rphy); if (level == ex->level) res = sas_ex_discover_devices(dev, -1); else if (level > 0) res = sas_ex_discover_devices(port->port_dev, -1); } } return res; } static int sas_ex_bfs_disc(struct asd_sas_port *port) { int res; int level; do { level = port->disc.max_level; res = sas_ex_level_discovery(port, level); mb(); } while (level < port->disc.max_level); return res; } int sas_discover_root_expander(struct domain_device *dev) { int res; struct sas_expander_device *ex = rphy_to_expander_device(dev->rphy); res = sas_rphy_add(dev->rphy); if (res) goto out_err; ex->level = dev->port->disc.max_level; /* 0 */ res = sas_discover_expander(dev); if (res) goto out_err2; sas_ex_bfs_disc(dev->port); return res; out_err2: sas_rphy_remove(dev->rphy); out_err: return res; } /* ---------- Domain revalidation ---------- */ static int sas_get_phy_discover(struct domain_device *dev, int phy_id, struct smp_resp *disc_resp) { int res; u8 *disc_req; disc_req = alloc_smp_req(DISCOVER_REQ_SIZE); if (!disc_req) return -ENOMEM; disc_req[1] = SMP_DISCOVER; disc_req[9] = phy_id; res = smp_execute_task(dev, disc_req, DISCOVER_REQ_SIZE, disc_resp, DISCOVER_RESP_SIZE); if (res) goto out; else if (disc_resp->result != SMP_RESP_FUNC_ACC) { res = disc_resp->result; goto out; } out: kfree(disc_req); return res; } static int sas_get_phy_change_count(struct domain_device *dev, int phy_id, int *pcc) { int res; struct smp_resp *disc_resp; disc_resp = alloc_smp_resp(DISCOVER_RESP_SIZE); if (!disc_resp) return -ENOMEM; res = sas_get_phy_discover(dev, phy_id, disc_resp); if (!res) *pcc = disc_resp->disc.change_count; kfree(disc_resp); return res; } static int sas_get_phy_attached_dev(struct domain_device *dev, int phy_id, u8 *sas_addr, enum sas_device_type *type) { int res; struct smp_resp *disc_resp; struct discover_resp *dr; disc_resp = alloc_smp_resp(DISCOVER_RESP_SIZE); if (!disc_resp) return -ENOMEM; dr = &disc_resp->disc; res = sas_get_phy_discover(dev, phy_id, disc_resp); if (res == 0) { memcpy(sas_addr, disc_resp->disc.attached_sas_addr, 8); *type = to_dev_type(dr); if (*type == 0) memset(sas_addr, 0, 8); } kfree(disc_resp); return res; } static int sas_find_bcast_phy(struct domain_device *dev, int *phy_id, int from_phy, bool update) { struct expander_device *ex = &dev->ex_dev; int res = 0; int i; for (i = from_phy; i < ex->num_phys; i++) { int phy_change_count = 0; res = sas_get_phy_change_count(dev, i, &phy_change_count); switch (res) { case SMP_RESP_PHY_VACANT: case SMP_RESP_NO_PHY: continue; case SMP_RESP_FUNC_ACC: break; default: return res; } if (phy_change_count != ex->ex_phy[i].phy_change_count) { if (update) ex->ex_phy[i].phy_change_count = phy_change_count; *phy_id = i; return 0; } } return 0; } static int sas_get_ex_change_count(struct domain_device *dev, int *ecc) { int res; u8 *rg_req; struct smp_resp *rg_resp; rg_req = alloc_smp_req(RG_REQ_SIZE); if (!rg_req) return -ENOMEM; rg_resp = alloc_smp_resp(RG_RESP_SIZE); if (!rg_resp) { kfree(rg_req); return -ENOMEM; } rg_req[1] = SMP_REPORT_GENERAL; res = smp_execute_task(dev, rg_req, RG_REQ_SIZE, rg_resp, RG_RESP_SIZE); if (res) goto out; if (rg_resp->result != SMP_RESP_FUNC_ACC) { res = rg_resp->result; goto out; } *ecc = be16_to_cpu(rg_resp->rg.change_count); out: kfree(rg_resp); kfree(rg_req); return res; } /** * sas_find_bcast_dev - find the device issue BROADCAST(CHANGE). * @dev:domain device to be detect. * @src_dev: the device which originated BROADCAST(CHANGE). * * Add self-configuration expander support. Suppose two expander cascading, * when the first level expander is self-configuring, hotplug the disks in * second level expander, BROADCAST(CHANGE) will not only be originated * in the second level expander, but also be originated in the first level * expander (see SAS protocol SAS 2r-14, 7.11 for detail), it is to say, * expander changed count in two level expanders will all increment at least * once, but the phy which chang count has changed is the source device which * we concerned. */ static int sas_find_bcast_dev(struct domain_device *dev, struct domain_device **src_dev) { struct expander_device *ex = &dev->ex_dev; int ex_change_count = -1; int phy_id = -1; int res; struct domain_device *ch; res = sas_get_ex_change_count(dev, &ex_change_count); if (res) goto out; if (ex_change_count != -1 && ex_change_count != ex->ex_change_count) { /* Just detect if this expander phys phy change count changed, * in order to determine if this expander originate BROADCAST, * and do not update phy change count field in our structure. */ res = sas_find_bcast_phy(dev, &phy_id, 0, false); if (phy_id != -1) { *src_dev = dev; ex->ex_change_count = ex_change_count; SAS_DPRINTK("Expander phy change count has changed\n"); return res; } else SAS_DPRINTK("Expander phys DID NOT change\n"); } list_for_each_entry(ch, &ex->children, siblings) { if (ch->dev_type == SAS_EDGE_EXPANDER_DEVICE || ch->dev_type == SAS_FANOUT_EXPANDER_DEVICE) { res = sas_find_bcast_dev(ch, src_dev); if (*src_dev) return res; } } out: return res; } static void sas_unregister_ex_tree(struct asd_sas_port *port, struct domain_device *dev) { struct expander_device *ex = &dev->ex_dev; struct domain_device *child, *n; list_for_each_entry_safe(child, n, &ex->children, siblings) { set_bit(SAS_DEV_GONE, &child->state); if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE || child->dev_type == SAS_FANOUT_EXPANDER_DEVICE) sas_unregister_ex_tree(port, child); else sas_unregister_dev(port, child); } sas_unregister_dev(port, dev); } static void sas_unregister_devs_sas_addr(struct domain_device *parent, int phy_id, bool last) { struct expander_device *ex_dev = &parent->ex_dev; struct ex_phy *phy = &ex_dev->ex_phy[phy_id]; struct domain_device *child, *n, *found = NULL; if (last) { list_for_each_entry_safe(child, n, &ex_dev->children, siblings) { if (SAS_ADDR(child->sas_addr) == SAS_ADDR(phy->attached_sas_addr)) { set_bit(SAS_DEV_GONE, &child->state); if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE || child->dev_type == SAS_FANOUT_EXPANDER_DEVICE) sas_unregister_ex_tree(parent->port, child); else sas_unregister_dev(parent->port, child); found = child; break; } } sas_disable_routing(parent, phy->attached_sas_addr); } memset(phy->attached_sas_addr, 0, SAS_ADDR_SIZE); if (phy->port) { sas_port_delete_phy(phy->port, phy->phy); sas_device_set_phy(found, phy->port); if (phy->port->num_phys == 0) sas_port_delete(phy->port); phy->port = NULL; } } static int sas_discover_bfs_by_root_level(struct domain_device *root, const int level) { struct expander_device *ex_root = &root->ex_dev; struct domain_device *child; int res = 0; list_for_each_entry(child, &ex_root->children, siblings) { if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE || child->dev_type == SAS_FANOUT_EXPANDER_DEVICE) { struct sas_expander_device *ex = rphy_to_expander_device(child->rphy); if (level > ex->level) res = sas_discover_bfs_by_root_level(child, level); else if (level == ex->level) res = sas_ex_discover_devices(child, -1); } } return res; } static int sas_discover_bfs_by_root(struct domain_device *dev) { int res; struct sas_expander_device *ex = rphy_to_expander_device(dev->rphy); int level = ex->level+1; res = sas_ex_discover_devices(dev, -1); if (res) goto out; do { res = sas_discover_bfs_by_root_level(dev, level); mb(); level += 1; } while (level <= dev->port->disc.max_level); out: return res; } static int sas_discover_new(struct domain_device *dev, int phy_id) { struct ex_phy *ex_phy = &dev->ex_dev.ex_phy[phy_id]; struct domain_device *child; int res; SAS_DPRINTK("ex %016llx phy%d new device attached\n", SAS_ADDR(dev->sas_addr), phy_id); res = sas_ex_phy_discover(dev, phy_id); if (res) return res; if (sas_ex_join_wide_port(dev, phy_id)) return 0; res = sas_ex_discover_devices(dev, phy_id); if (res) return res; list_for_each_entry(child, &dev->ex_dev.children, siblings) { if (SAS_ADDR(child->sas_addr) == SAS_ADDR(ex_phy->attached_sas_addr)) { if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE || child->dev_type == SAS_FANOUT_EXPANDER_DEVICE) res = sas_discover_bfs_by_root(child); break; } } return res; } static bool dev_type_flutter(enum sas_device_type new, enum sas_device_type old) { if (old == new) return true; /* treat device directed resets as flutter, if we went * SAS_END_DEVICE to SAS_SATA_PENDING the link needs recovery */ if ((old == SAS_SATA_PENDING && new == SAS_END_DEVICE) || (old == SAS_END_DEVICE && new == SAS_SATA_PENDING)) return true; return false; } static int sas_rediscover_dev(struct domain_device *dev, int phy_id, bool last) { struct expander_device *ex = &dev->ex_dev; struct ex_phy *phy = &ex->ex_phy[phy_id]; enum sas_device_type type = SAS_PHY_UNUSED; u8 sas_addr[8]; int res; memset(sas_addr, 0, 8); res = sas_get_phy_attached_dev(dev, phy_id, sas_addr, &type); switch (res) { case SMP_RESP_NO_PHY: phy->phy_state = PHY_NOT_PRESENT; sas_unregister_devs_sas_addr(dev, phy_id, last); return res; case SMP_RESP_PHY_VACANT: phy->phy_state = PHY_VACANT; sas_unregister_devs_sas_addr(dev, phy_id, last); return res; case SMP_RESP_FUNC_ACC: break; case -ECOMM: break; default: return res; } if ((SAS_ADDR(sas_addr) == 0) || (res == -ECOMM)) { phy->phy_state = PHY_EMPTY; sas_unregister_devs_sas_addr(dev, phy_id, last); return res; } else if (SAS_ADDR(sas_addr) == SAS_ADDR(phy->attached_sas_addr) && dev_type_flutter(type, phy->attached_dev_type)) { struct domain_device *ata_dev = sas_ex_to_ata(dev, phy_id); char *action = ""; sas_ex_phy_discover(dev, phy_id); if (ata_dev && phy->attached_dev_type == SAS_SATA_PENDING) action = ", needs recovery"; SAS_DPRINTK("ex %016llx phy 0x%x broadcast flutter%s\n", SAS_ADDR(dev->sas_addr), phy_id, action); return res; } /* delete the old link */ if (SAS_ADDR(phy->attached_sas_addr) && SAS_ADDR(sas_addr) != SAS_ADDR(phy->attached_sas_addr)) { SAS_DPRINTK("ex %016llx phy 0x%x replace %016llx\n", SAS_ADDR(dev->sas_addr), phy_id, SAS_ADDR(phy->attached_sas_addr)); sas_unregister_devs_sas_addr(dev, phy_id, last); } return sas_discover_new(dev, phy_id); } /** * sas_rediscover - revalidate the domain. * @dev:domain device to be detect. * @phy_id: the phy id will be detected. * * NOTE: this process _must_ quit (return) as soon as any connection * errors are encountered. Connection recovery is done elsewhere. * Discover process only interrogates devices in order to discover the * domain.For plugging out, we un-register the device only when it is * the last phy in the port, for other phys in this port, we just delete it * from the port.For inserting, we do discovery when it is the * first phy,for other phys in this port, we add it to the port to * forming the wide-port. */ static int sas_rediscover(struct domain_device *dev, const int phy_id) { struct expander_device *ex = &dev->ex_dev; struct ex_phy *changed_phy = &ex->ex_phy[phy_id]; int res = 0; int i; bool last = true; /* is this the last phy of the port */ SAS_DPRINTK("ex %016llx phy%d originated BROADCAST(CHANGE)\n", SAS_ADDR(dev->sas_addr), phy_id); if (SAS_ADDR(changed_phy->attached_sas_addr) != 0) { for (i = 0; i < ex->num_phys; i++) { struct ex_phy *phy = &ex->ex_phy[i]; if (i == phy_id) continue; if (SAS_ADDR(phy->attached_sas_addr) == SAS_ADDR(changed_phy->attached_sas_addr)) { SAS_DPRINTK("phy%d part of wide port with " "phy%d\n", phy_id, i); last = false; break; } } res = sas_rediscover_dev(dev, phy_id, last); } else res = sas_discover_new(dev, phy_id); return res; } /** * sas_revalidate_domain -- revalidate the domain * @port: port to the domain of interest * * NOTE: this process _must_ quit (return) as soon as any connection * errors are encountered. Connection recovery is done elsewhere. * Discover process only interrogates devices in order to discover the * domain. */ int sas_ex_revalidate_domain(struct domain_device *port_dev) { int res; struct domain_device *dev = NULL; res = sas_find_bcast_dev(port_dev, &dev); while (res == 0 && dev) { struct expander_device *ex = &dev->ex_dev; int i = 0, phy_id; do { phy_id = -1; res = sas_find_bcast_phy(dev, &phy_id, i, true); if (phy_id == -1) break; res = sas_rediscover(dev, phy_id); i = phy_id + 1; } while (i < ex->num_phys); dev = NULL; res = sas_find_bcast_dev(port_dev, &dev); } return res; } void sas_smp_handler(struct bsg_job *job, struct Scsi_Host *shost, struct sas_rphy *rphy) { struct domain_device *dev; unsigned int reslen = 0; int ret = -EINVAL; /* no rphy means no smp target support (ie aic94xx host) */ if (!rphy) return sas_smp_host_handler(job, shost); switch (rphy->identify.device_type) { case SAS_EDGE_EXPANDER_DEVICE: case SAS_FANOUT_EXPANDER_DEVICE: break; default: printk("%s: can we send a smp request to a device?\n", __func__); goto out; } dev = sas_find_dev_by_rphy(rphy); if (!dev) { printk("%s: fail to find a domain_device?\n", __func__); goto out; } /* do we need to support multiple segments? */ if (job->request_payload.sg_cnt > 1 || job->reply_payload.sg_cnt > 1) { printk("%s: multiple segments req %u, rsp %u\n", __func__, job->request_payload.payload_len, job->reply_payload.payload_len); goto out; } ret = smp_execute_task_sg(dev, job->request_payload.sg_list, job->reply_payload.sg_list); if (ret > 0) { /* positive number is the untransferred residual */ reslen = ret; ret = 0; } out: bsg_job_done(job, ret, reslen); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_653_0
crossvul-cpp_data_bad_2616_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP DDDD FFFFF % % P P D D F % % PPPP D D FFF % % P D D F % % P DDDD F % % % % % % Read/Write Portable Document Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/compress.h" #include "magick/constitute.h" #include "magick/delegate.h" #include "magick/delegate-private.h" #include "magick/draw.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/magick-type.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/nt-base-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/signature.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/token.h" #include "magick/transform.h" #include "magick/utility.h" #include "magick/module.h" /* Define declarations. */ #if defined(MAGICKCORE_TIFF_DELEGATE) #define CCITTParam "-1" #else #define CCITTParam "0" #endif /* Forward declarations. */ static MagickBooleanType WritePDFImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v o k e P D F D e l e g a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InvokePDFDelegate() executes the PDF interpreter with the specified command. % % The format of the InvokePDFDelegate method is: % % MagickBooleanType InvokePDFDelegate(const MagickBooleanType verbose, % const char *command,ExceptionInfo *exception) % % A description of each parameter follows: % % o verbose: A value other than zero displays the command prior to % executing it. % % o command: the address of a character string containing the command to % execute. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT) static int MagickDLLCall PDFDelegateMessage(void *handle,const char *message, int length) { char **messages; ssize_t offset; offset=0; messages=(char **) handle; if (*messages == (char *) NULL) *messages=(char *) AcquireQuantumMemory(length+1,sizeof(char *)); else { offset=strlen(*messages); *messages=(char *) ResizeQuantumMemory(*messages,offset+length+1, sizeof(char *)); } (void) memcpy(*messages+offset,message,length); (*messages)[length+offset] ='\0'; return(length); } #endif static MagickBooleanType InvokePDFDelegate(const MagickBooleanType verbose, const char *command,char *message,ExceptionInfo *exception) { int status; #if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT) #define SetArgsStart(command,args_start) \ if (args_start == (const char *) NULL) \ { \ if (*command != '"') \ args_start=strchr(command,' '); \ else \ { \ args_start=strchr(command+1,'"'); \ if (args_start != (const char *) NULL) \ args_start++; \ } \ } #define ExecuteGhostscriptCommand(command,status) \ { \ status=ExternalDelegateCommand(MagickFalse,verbose,command,message, \ exception); \ if (status == 0) \ return(MagickTrue); \ if (status < 0) \ return(MagickFalse); \ (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, \ "FailedToExecuteCommand","`%s' (%d)",command,status); \ return(MagickFalse); \ } char **argv, *errors; const char *args_start=NULL; const GhostInfo *ghost_info; gs_main_instance *interpreter; gsapi_revision_t revision; int argc, code; register ssize_t i; #if defined(MAGICKCORE_WINDOWS_SUPPORT) ghost_info=NTGhostscriptDLLVectors(); #else GhostInfo ghost_info_struct; ghost_info=(&ghost_info_struct); (void) ResetMagickMemory(&ghost_info_struct,0,sizeof(ghost_info_struct)); ghost_info_struct.delete_instance=(void (*)(gs_main_instance *)) gsapi_delete_instance; ghost_info_struct.exit=(int (*)(gs_main_instance *)) gsapi_exit; ghost_info_struct.new_instance=(int (*)(gs_main_instance **,void *)) gsapi_new_instance; ghost_info_struct.init_with_args=(int (*)(gs_main_instance *,int,char **)) gsapi_init_with_args; ghost_info_struct.run_string=(int (*)(gs_main_instance *,const char *,int, int *)) gsapi_run_string; ghost_info_struct.set_stdio=(int (*)(gs_main_instance *,int(*)(void *,char *, int),int(*)(void *,const char *,int),int(*)(void *, const char *, int))) gsapi_set_stdio; ghost_info_struct.revision=(int (*)(gsapi_revision_t *,int)) gsapi_revision; #endif if (ghost_info == (GhostInfo *) NULL) ExecuteGhostscriptCommand(command,status); if ((ghost_info->revision)(&revision,sizeof(revision)) != 0) revision.revision=0; if (verbose != MagickFalse) { (void) fprintf(stdout,"[ghostscript library %.2f]",(double) revision.revision/100.0); SetArgsStart(command,args_start); (void) fputs(args_start,stdout); } errors=(char *) NULL; status=(ghost_info->new_instance)(&interpreter,(void *) &errors); if (status < 0) ExecuteGhostscriptCommand(command,status); code=0; argv=StringToArgv(command,&argc); if (argv == (char **) NULL) { (ghost_info->delete_instance)(interpreter); return(MagickFalse); } (void) (ghost_info->set_stdio)(interpreter,(int(MagickDLLCall *)(void *, char *,int)) NULL,PDFDelegateMessage,PDFDelegateMessage); status=(ghost_info->init_with_args)(interpreter,argc-1,argv+1); if (status == 0) status=(ghost_info->run_string)(interpreter,"systemdict /start get exec\n", 0,&code); (ghost_info->exit)(interpreter); (ghost_info->delete_instance)(interpreter); for (i=0; i < (ssize_t) argc; i++) argv[i]=DestroyString(argv[i]); argv=(char **) RelinquishMagickMemory(argv); if (status != 0) { SetArgsStart(command,args_start); if (status == -101) /* quit */ (void) FormatLocaleString(message,MaxTextExtent, "[ghostscript library %.2f]%s: %s",(double)revision.revision / 100, args_start,errors); else { (void) ThrowMagickException(exception,GetMagickModule(), DelegateError,"PDFDelegateFailed", "`[ghostscript library %.2f]%s': %s", (double)revision.revision / 100,args_start,errors); if (errors != (char *) NULL) errors=DestroyString(errors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Ghostscript returns status %d, exit code %d",status,code); return(MagickFalse); } } if (errors != (char *) NULL) errors=DestroyString(errors); return(MagickTrue); #else status=ExternalDelegateCommand(MagickFalse,verbose,command,(char *) NULL, exception); return(status == 0 ? MagickTrue : MagickFalse); #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P D F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPDF() returns MagickTrue if the image format type, identified by the % magick string, is PDF. % % The format of the IsPDF method is: % % MagickBooleanType IsPDF(const unsigned char *magick,const size_t offset) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o offset: Specifies the offset of the magick string. % */ static MagickBooleanType IsPDF(const unsigned char *magick,const size_t offset) { if (offset < 5) return(MagickFalse); if (LocaleNCompare((const char *) magick,"%PDF-",5) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P D F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPDFImage() reads a Portable Document Format image file and % returns it. It allocates the memory necessary for the new Image structure % and returns a pointer to the new image. % % The format of the ReadPDFImage method is: % % Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsPDFRendered(const char *path) { MagickBooleanType status; struct stat attributes; if ((path == (const char *) NULL) || (*path == '\0')) return(MagickFalse); status=GetPathAttributes(path,&attributes); if ((status != MagickFalse) && S_ISREG(attributes.st_mode) && (attributes.st_size > 0)) return(MagickTrue); return(MagickFalse); } static Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CMYKProcessColor "CMYKProcessColor" #define CropBox "CropBox" #define DefaultCMYK "DefaultCMYK" #define DeviceCMYK "DeviceCMYK" #define MediaBox "MediaBox" #define RenderPostscriptText "Rendering Postscript... " #define PDFRotate "Rotate" #define SpotColor "Separation" #define TrimBox "TrimBox" #define PDFVersion "PDF-" char command[MaxTextExtent], *density, filename[MaxTextExtent], geometry[MaxTextExtent], *options, input_filename[MaxTextExtent], message[MaxTextExtent], postscript_filename[MaxTextExtent]; const char *option; const DelegateInfo *delegate_info; double angle; GeometryInfo geometry_info; Image *image, *next, *pdf_image; ImageInfo *read_info; int c, file; MagickBooleanType cmyk, cropbox, fitPage, status, stop_on_error, trimbox; MagickStatusType flags; PointInfo delta; RectangleInfo bounding_box, page; register char *p; register ssize_t i; SegmentInfo bounds, hires_bounds; size_t scene, spotcolor; ssize_t count; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); /* Open image file. */ image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } (void) ResetMagickMemory(&page,0,sizeof(page)); (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); page.width=(size_t) ceil((double) (page.width*image->x_resolution/delta.x)- 0.5); page.height=(size_t) ceil((double) (page.height*image->y_resolution/delta.y)- 0.5); /* Determine page geometry from the PDF media box. */ cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; cropbox=MagickFalse; option=GetImageOption(image_info,"pdf:use-cropbox"); if (option != (const char *) NULL) cropbox=IsMagickTrue(option); stop_on_error=MagickFalse; option=GetImageOption(image_info,"pdf:stop-on-error"); if (option != (const char *) NULL) stop_on_error=IsMagickTrue(option); trimbox=MagickFalse; option=GetImageOption(image_info,"pdf:use-trimbox"); if (option != (const char *) NULL) trimbox=IsMagickTrue(option); count=0; spotcolor=0; (void) ResetMagickMemory(&bounding_box,0,sizeof(bounding_box)); (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); (void) ResetMagickMemory(&hires_bounds,0,sizeof(hires_bounds)); (void) ResetMagickMemory(command,0,sizeof(command)); angle=0.0; p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note PDF elements. */ if (c == '\n') c=' '; *p++=(char) c; if ((c != (int) '/') && (c != (int) '%') && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *(--p)='\0'; p=command; if (LocaleNCompare(PDFRotate,command,strlen(PDFRotate)) == 0) (void) sscanf(command,"Rotate %lf",&angle); /* Is this a CMYK document? */ if (LocaleNCompare(DefaultCMYK,command,strlen(DefaultCMYK)) == 0) cmyk=MagickTrue; if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0) cmyk=MagickTrue; if (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0) { char name[MaxTextExtent], property[MaxTextExtent], *value; register ssize_t i; /* Note spot names. */ (void) FormatLocaleString(property,MaxTextExtent,"pdf:SpotColor-%.20g", (double) spotcolor++); i=0; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { if ((isspace(c) != 0) || (c == '/') || ((i+1) == MaxTextExtent)) break; name[i++]=(char) c; } name[i]='\0'; value=AcquireString(name); (void) SubstituteString(&value,"#20"," "); (void) SetImageProperty(image,property,value); value=DestroyString(value); continue; } if (LocaleNCompare(PDFVersion,command,strlen(PDFVersion)) == 0) (void) SetImageProperty(image,"pdf:Version",command); if (image_info->page != (char *) NULL) continue; count=0; if (cropbox != MagickFalse) { if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0) { /* Note region defined by crop box. */ count=(ssize_t) sscanf(command,"CropBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"CropBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } } else if (trimbox != MagickFalse) { if (LocaleNCompare(TrimBox,command,strlen(TrimBox)) == 0) { /* Note region defined by trim box. */ count=(ssize_t) sscanf(command,"TrimBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"TrimBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } } else if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0) { /* Note region defined by media box. */ count=(ssize_t) sscanf(command,"MediaBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"MediaBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (count != 4) continue; if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) || (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1))) continue; hires_bounds=bounds; } if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) && (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon)) { /* Set PDF render geometry. */ (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+.15g%+.15g", hires_bounds.x2-bounds.x1,hires_bounds.y2-hires_bounds.y1, hires_bounds.x1,hires_bounds.y1); (void) SetImageProperty(image,"pdf:HiResBoundingBox",geometry); page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)* image->x_resolution/delta.x)-0.5); page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)* image->y_resolution/delta.y)-0.5); } fitPage=MagickFalse; option=GetImageOption(image_info,"pdf:fit-page"); if (option != (char *) NULL) { char *geometry; MagickStatusType flags; geometry=GetPageGeometry(option); flags=ParseMetaGeometry(geometry,&page.x,&page.y,&page.width, &page.height); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidGeometry","`%s'",option); image=DestroyImage(image); return((Image *) NULL); } page.width=(size_t) ceil((double) (page.width*image->x_resolution/delta.x) -0.5); page.height=(size_t) ceil((double) (page.height*image->y_resolution/ delta.y) -0.5); geometry=DestroyString(geometry); fitPage=MagickTrue; } (void) CloseBlob(image); if ((fabs(angle) == 90.0) || (fabs(angle) == 270.0)) { size_t swap; swap=page.width; page.width=page.height; page.height=swap; } if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse) cmyk=MagickFalse; /* Create Ghostscript control file. */ file=AcquireUniqueFileResource(postscript_filename); if (file == -1) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImage(image); return((Image *) NULL); } count=write(file," ",1); file=close(file)-1; /* Render Postscript with the Ghostscript delegate. */ if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) RelinquishUniqueFileResource(postscript_filename); image=DestroyImage(image); return((Image *) NULL); } density=AcquireString(""); options=AcquireString(""); (void) FormatLocaleString(density,MaxTextExtent,"%gx%g",image->x_resolution, image->y_resolution); if ((image_info->page != (char *) NULL) || (fitPage != MagickFalse)) (void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); if (fitPage != MagickFalse) (void) ConcatenateMagickString(options,"-dPSFitPage ",MaxTextExtent); if (cmyk != MagickFalse) (void) ConcatenateMagickString(options,"-dUseCIEColor ",MaxTextExtent); if (cropbox != MagickFalse) (void) ConcatenateMagickString(options,"-dUseCropBox ",MaxTextExtent); if (trimbox != MagickFalse) (void) ConcatenateMagickString(options,"-dUseTrimBox ",MaxTextExtent); if (stop_on_error != MagickFalse) (void) ConcatenateMagickString(options,"-dPDFSTOPONERROR ",MaxTextExtent); option=GetImageOption(image_info,"authenticate"); if (option != (char *) NULL) { char passphrase[MaxTextExtent]; (void) FormatLocaleString(passphrase,MaxTextExtent, "'-sPDFPassword=%s' ",option); (void) ConcatenateMagickString(options,passphrase,MaxTextExtent); } read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { char pages[MaxTextExtent]; (void) FormatLocaleString(pages,MaxTextExtent,"-dFirstPage=%.20g " "-dLastPage=%.20g",(double) read_info->scene+1,(double) (read_info->scene+read_info->number_scenes)); (void) ConcatenateMagickString(options,pages,MaxTextExtent); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } (void) CopyMagickString(filename,read_info->filename,MaxTextExtent); (void) AcquireUniqueFilename(filename); (void) RelinquishUniqueFileResource(filename); (void) ConcatenateMagickString(filename,"%d",MaxTextExtent); (void) FormatLocaleString(command,MaxTextExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options,filename, postscript_filename,input_filename); options=DestroyString(options); density=DestroyString(density); *message='\0'; status=InvokePDFDelegate(read_info->verbose,command,message,exception); (void) RelinquishUniqueFileResource(postscript_filename); (void) RelinquishUniqueFileResource(input_filename); pdf_image=(Image *) NULL; if (status == MagickFalse) for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPDFRendered(read_info->filename) == MagickFalse) break; (void) RelinquishUniqueFileResource(read_info->filename); } else for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPDFRendered(read_info->filename) == MagickFalse) break; read_info->blob=NULL; read_info->length=0; next=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); if (next == (Image *) NULL) break; AppendImageToList(&pdf_image,next); } read_info=DestroyImageInfo(read_info); if (pdf_image == (Image *) NULL) { if (*message != '\0') (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, "PDFDelegateFailed","`%s'",message); image=DestroyImage(image); return((Image *) NULL); } if (LocaleCompare(pdf_image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(pdf_image,exception); if (cmyk_image != (Image *) NULL) { pdf_image=DestroyImageList(pdf_image); pdf_image=cmyk_image; } } if (image_info->number_scenes != 0) { Image *clone_image; register ssize_t i; /* Add place holder images to meet the subimage specification requirement. */ for (i=0; i < (ssize_t) image_info->scene; i++) { clone_image=CloneImage(pdf_image,1,1,MagickTrue,exception); if (clone_image != (Image *) NULL) PrependImageToList(&pdf_image,clone_image); } } do { (void) CopyMagickString(pdf_image->filename,filename,MaxTextExtent); (void) CopyMagickString(pdf_image->magick,image->magick,MaxTextExtent); pdf_image->page=page; (void) CloneImageProfiles(pdf_image,image); (void) CloneImageProperties(pdf_image,image); next=SyncNextImageInList(pdf_image); if (next != (Image *) NULL) pdf_image=next; } while (next != (Image *) NULL); image=DestroyImage(image); scene=0; for (next=GetFirstImageInList(pdf_image); next != (Image *) NULL; ) { next->scene=scene++; next=GetNextImageInList(next); } return(GetFirstImageInList(pdf_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P D F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPDFImage() adds properties for the PDF image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPDFImage method is: % % size_t RegisterPDFImage(void) % */ ModuleExport size_t RegisterPDFImage(void) { MagickInfo *entry; entry=SetMagickInfo("AI"); entry->decoder=(DecodeImageHandler *) ReadPDFImage; entry->encoder=(EncodeImageHandler *) WritePDFImage; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Illustrator CS2"); entry->mime_type=ConstantString("application/pdf"); entry->module=ConstantString("PDF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPDF"); entry->decoder=(DecodeImageHandler *) ReadPDFImage; entry->encoder=(EncodeImageHandler *) WritePDFImage; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated Portable Document Format"); entry->mime_type=ConstantString("application/pdf"); entry->module=ConstantString("PDF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PDF"); entry->decoder=(DecodeImageHandler *) ReadPDFImage; entry->encoder=(EncodeImageHandler *) WritePDFImage; entry->magick=(IsImageFormatHandler *) IsPDF; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Portable Document Format"); entry->mime_type=ConstantString("application/pdf"); entry->module=ConstantString("PDF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PDFA"); entry->decoder=(DecodeImageHandler *) ReadPDFImage; entry->encoder=(EncodeImageHandler *) WritePDFImage; entry->magick=(IsImageFormatHandler *) IsPDF; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Portable Document Archive Format"); entry->mime_type=ConstantString("application/pdf"); entry->module=ConstantString("PDF"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P D F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPDFImage() removes format registrations made by the % PDF module from the list of supported formats. % % The format of the UnregisterPDFImage method is: % % UnregisterPDFImage(void) % */ ModuleExport void UnregisterPDFImage(void) { (void) UnregisterMagickInfo("AI"); (void) UnregisterMagickInfo("EPDF"); (void) UnregisterMagickInfo("PDF"); (void) UnregisterMagickInfo("PDFA"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P D F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePDFImage() writes an image in the Portable Document image % format. % % The format of the WritePDFImage method is: % % MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static char *EscapeParenthesis(const char *source) { char *destination; register char *q; register const char *p; size_t length; assert(source != (const char *) NULL); length=0; for (p=source; *p != '\0'; p++) { if ((*p == '\\') || (*p == '(') || (*p == ')')) { if (~length < 1) ThrowFatalException(ResourceLimitFatalError,"UnableToEscapeString"); length++; } length++; } destination=(char *) NULL; if (~length >= (MaxTextExtent-1)) destination=(char *) AcquireQuantumMemory(length+MaxTextExtent, sizeof(*destination)); if (destination == (char *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToEscapeString"); *destination='\0'; q=destination; for (p=source; *p != '\0'; p++) { if ((*p == '\\') || (*p == '(') || (*p == ')')) *q++='\\'; *q++=(*p); } *q='\0'; return(destination); } static size_t UTF8ToUTF16(const unsigned char *utf8,wchar_t *utf16) { register const unsigned char *p; if (utf16 != (wchar_t *) NULL) { register wchar_t *q; wchar_t c; /* Convert UTF-8 to UTF-16. */ q=utf16; for (p=utf8; *p != '\0'; p++) { if ((*p & 0x80) == 0) *q=(*p); else if ((*p & 0xE0) == 0xC0) { c=(*p); *q=(c & 0x1F) << 6; p++; if ((*p & 0xC0) != 0x80) return(0); *q|=(*p & 0x3F); } else if ((*p & 0xF0) == 0xE0) { c=(*p); *q=c << 12; p++; if ((*p & 0xC0) != 0x80) return(0); c=(*p); *q|=(c & 0x3F) << 6; p++; if ((*p & 0xC0) != 0x80) return(0); *q|=(*p & 0x3F); } else return(0); q++; } *q++=(wchar_t) '\0'; return((size_t) (q-utf16)); } /* Compute UTF-16 string length. */ for (p=utf8; *p != '\0'; p++) { if ((*p & 0x80) == 0) ; else if ((*p & 0xE0) == 0xC0) { p++; if ((*p & 0xC0) != 0x80) return(0); } else if ((*p & 0xF0) == 0xE0) { p++; if ((*p & 0xC0) != 0x80) return(0); p++; if ((*p & 0xC0) != 0x80) return(0); } else return(0); } return((size_t) (p-utf8)); } static wchar_t *ConvertUTF8ToUTF16(const unsigned char *source,size_t *length) { wchar_t *utf16; *length=UTF8ToUTF16(source,(wchar_t *) NULL); if (*length == 0) { register ssize_t i; /* Not UTF-8, just copy. */ *length=strlen((const char *) source); utf16=(wchar_t *) AcquireQuantumMemory(*length+1,sizeof(*utf16)); if (utf16 == (wchar_t *) NULL) return((wchar_t *) NULL); for (i=0; i <= (ssize_t) *length; i++) utf16[i]=source[i]; return(utf16); } utf16=(wchar_t *) AcquireQuantumMemory(*length+1,sizeof(*utf16)); if (utf16 == (wchar_t *) NULL) return((wchar_t *) NULL); *length=UTF8ToUTF16(source,utf16); return(utf16); } static MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info, Image *image,Image *inject_image) { Image *group4_image; ImageInfo *write_info; MagickBooleanType status; size_t length; unsigned char *group4; status=MagickTrue; write_info=CloneImageInfo(image_info); (void) CopyMagickString(write_info->filename,"GROUP4:",MaxTextExtent); (void) CopyMagickString(write_info->magick,"GROUP4",MaxTextExtent); group4_image=CloneImage(inject_image,0,0,MagickTrue,&image->exception); if (group4_image == (Image *) NULL) return(MagickFalse); group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length, &image->exception); group4_image=DestroyImage(group4_image); if (group4 == (unsigned char *) NULL) return(MagickFalse); write_info=DestroyImageInfo(write_info); if (WriteBlob(image,length,group4) != (ssize_t) length) status=MagickFalse; group4=(unsigned char *) RelinquishMagickMemory(group4); return(status); } static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image) { #define CFormat "/Filter [ /%s ]\n" #define ObjectsPerImage 14 DisableMSCWarning(4310) static const char XMPProfile[]= { "<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n" "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n" " <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n" " <xap:ModifyDate>%s</xap:ModifyDate>\n" " <xap:CreateDate>%s</xap:CreateDate>\n" " <xap:MetadataDate>%s</xap:MetadataDate>\n" " <xap:CreatorTool>%s</xap:CreatorTool>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n" " <dc:format>application/pdf</dc:format>\n" " <dc:title>\n" " <rdf:Alt>\n" " <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n" " </rdf:Alt>\n" " </dc:title>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n" " <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n" " <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n" " <pdf:Producer>%s</pdf:Producer>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n" " <pdfaid:part>3</pdfaid:part>\n" " <pdfaid:conformance>B</pdfaid:conformance>\n" " </rdf:Description>\n" " </rdf:RDF>\n" "</x:xmpmeta>\n" "<?xpacket end=\"w\"?>\n" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MaxTextExtent], buffer[MaxTextExtent], date[MaxTextExtent], *escape, **labels, page_geometry[MaxTextExtent], *url; CompressionType compression; const char *device, *option, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; Image *next, *tile_image; MagickBooleanType status; MagickOffsetType offset, scene, *xref; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const IndexPacket *indexes; register const PixelPacket *p; register unsigned char *q; register ssize_t i, x; size_t channels, info_id, length, object, pages_id, root_id, text_size, version; ssize_t count, page_count, y; struct tm local_time; time_t seconds; unsigned char *pixels; wchar_t *utf16; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Allocate X ref memory. */ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(xref,0,2048UL*sizeof(*xref)); /* Write Info object. */ object=0; version=3; if (image_info->compression == JPEG2000Compression) version=(size_t) MagickMax(version,5); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) if (next->matte != MagickFalse) version=(size_t) MagickMax(version,4); if (LocaleCompare(image_info->magick,"PDFA") == 0) version=(size_t) MagickMax(version,6); profile=GetImageProfile(image,"icc"); if (profile != (StringInfo *) NULL) version=(size_t) MagickMax(version,7); (void) FormatLocaleString(buffer,MaxTextExtent,"%%PDF-1.%.20g \n",(double) version); (void) WriteBlobString(image,buffer); if (LocaleCompare(image_info->magick,"PDFA") == 0) { (void) WriteBlobByte(image,'%'); (void) WriteBlobByte(image,0xe2); (void) WriteBlobByte(image,0xe3); (void) WriteBlobByte(image,0xcf); (void) WriteBlobByte(image,0xd3); (void) WriteBlobByte(image,'\n'); } /* Write Catalog object. */ xref[object++]=TellBlob(image); root_id=object; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (LocaleCompare(image_info->magick,"PDFA") != 0) (void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n",(double) object+1); else { (void) FormatLocaleString(buffer,MaxTextExtent,"/Metadata %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n", (double) object+2); } (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Type /Catalog"); option=GetImageOption(image_info,"pdf:page-direction"); if ((option != (const char *) NULL) && (LocaleCompare(option,"right-to-left") != MagickFalse)) (void) WriteBlobString(image,"/ViewerPreferences<</PageDirection/R2L>>\n"); (void) WriteBlobString(image,"\n"); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); GetPathComponent(image->filename,BasePath,basename); if (LocaleCompare(image_info->magick,"PDFA") == 0) { char create_date[MaxTextExtent], modify_date[MaxTextExtent], timestamp[MaxTextExtent], xmp_profile[MaxTextExtent], *url; /* Write XMP object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Subtype /XML\n"); *modify_date='\0'; value=GetImageProperty(image,"date:modify"); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MaxTextExtent); *create_date='\0'; value=GetImageProperty(image,"date:create"); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MaxTextExtent); (void) FormatMagickTime(time((time_t *) NULL),MaxTextExtent,timestamp); url=GetMagickHomeURL(); escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MaxTextExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); url=DestroyString(url); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g\n",(double) i); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Type /Metadata\n"); (void) WriteBlobString(image,">>\nstream\n"); (void) WriteBlobString(image,xmp_profile); (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); } /* Write Pages object. */ xref[object++]=TellBlob(image); pages_id=object; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Pages\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Kids [ %.20g 0 R ",(double) object+1); (void) WriteBlobString(image,buffer); count=(ssize_t) (pages_id+ObjectsPerImage+1); page_count=1; if (image_info->adjoin != MagickFalse) { Image *kid_image; /* Predict page object id's. */ kid_image=image; for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage) { page_count++; profile=GetImageProfile(kid_image,"icc"); if (profile != (StringInfo *) NULL) count+=2; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 R ",(double) count); (void) WriteBlobString(image,buffer); kid_image=GetNextImageInList(kid_image); } xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL, sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) WriteBlobString(image,"]\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Count %.20g\n",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); scene=0; do { MagickBooleanType has_icc_profile; profile=GetImageProfile(image,"icc"); has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((SetImageMonochrome(image,&image->exception) == MagickFalse) || (image->matte != MagickFalse)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)", image->filename); break; } #endif case LZWCompression: { if (LocaleCompare(image_info->magick,"PDFA") == 0) compression=RLECompression; /* LZW compression is forbidden */ break; } case NoCompression: { if (LocaleCompare(image_info->magick,"PDFA") == 0) compression=RLECompression; /* ASCII 85 compression is forbidden */ break; } default: break; } if (compression == JPEG2000Compression) (void) TransformImageColorspace(image,sRGBColorspace); /* Scale relative to dots-per-inch. */ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->x_resolution; resolution.y=image->y_resolution; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MaxTextExtent,"%.20gx%.20g",(double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PDF") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent); (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info, &image->exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); (void) text_size; /* Write Page object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Page\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Parent %.20g 0 R\n", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Resources <<\n"); labels=(char **) NULL; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent, "/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MaxTextExtent, "/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ProcSet %.20g 0 R >>\n", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "/MediaBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "/CropBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Contents %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Thumb %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 10 : 8)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Contents object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); (void) WriteBlobString(image,"q\n"); if (labels != (char **) NULL) for (i=0; labels[i] != (char *) NULL; i++) { (void) WriteBlobString(image,"BT\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/F%.20g %g Tf\n", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g Td\n", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"(%s) Tj\n",labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"ET\n"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MaxTextExtent,"%g 0 0 %g %.20g %.20g cm\n", scale.x,scale.y,(double) geometry.x,(double) geometry.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Im%.20g Do\n",(double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"Q\n"); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Procset object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MaxTextExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MaxTextExtent); else (void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MaxTextExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image," ]\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Font object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (labels != (char **) NULL) { (void) WriteBlobString(image,"/Type /Font\n"); (void) WriteBlobString(image,"/Subtype /Type1\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /F%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/BaseFont /Helvetica\n"); (void) WriteBlobString(image,"/Encoding /MacRomanEncoding\n"); labels=(char **) RelinquishMagickMemory(labels); } (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write XObject object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Im%.20g\n",(double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->matte != MagickFalse) { (void) FormatLocaleString(buffer,MaxTextExtent,"/SMask %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels))) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,image); break; } (void) Huffman2DEncodeImage(image_info,image,image); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p))); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelIndex(indexes+x)); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelIndex(indexes+x))); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) Ascii85Encode(image,(unsigned char) GetPixelIndex(indexes+x)); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Colorspace object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); device="DeviceRGB"; channels=0; if (image->colorspace == CMYKColorspace) { device="DeviceCMYK"; channels=4; } else if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse))) { device="DeviceGray"; channels=1; } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) { device="DeviceRGB"; channels=3; } profile=GetImageProfile(image,"icc"); if ((profile == (StringInfo *) NULL) || (channels == 0)) { if (channels != 0) (void) FormatLocaleString(buffer,MaxTextExtent,"/%s\n",device); else (void) FormatLocaleString(buffer,MaxTextExtent, "[ /Indexed /%s %.20g %.20g 0 R ]\n",device,(double) image->colors- 1,(double) object+3); (void) WriteBlobString(image,buffer); } else { const unsigned char *p; /* Write ICC profile. */ (void) FormatLocaleString(buffer,MaxTextExtent, "[/ICCBased %.20g 0 R]\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"<<\n/N %.20g\n" "/Filter /ASCII85Decode\n/Length %.20g 0 R\n/Alternate /%s\n>>\n" "stream\n",(double) channels,(double) object+1,device); (void) WriteBlobString(image,buffer); offset=TellBlob(image); Ascii85Initialize(image); p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) Ascii85Encode(image,(unsigned char) *p++); Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"endstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"endobj\n"); /* Write Thumb object. */ SetGeometry(image,&geometry); (void) ParseMetaGeometry("106x106+0+0>",&geometry.x,&geometry.y, &geometry.width,&geometry.height); tile_image=ThumbnailImage(image,geometry.width,geometry.height, &image->exception); if (tile_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,image->exception.reason); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows; if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(tile_image,&image->exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,tile_image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,tile_image->exception.reason); break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p))); p++; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p++; } } Ascii85Flush(image); break; } } } else if ((tile_image->storage_class == DirectClass) || (tile_image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,tile_image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,tile_image->exception.reason); break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runoffset encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelIndex(indexes+x)); p++; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelIndex(indexes+x))); p++; } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) Ascii85Encode(image,(unsigned char) GetPixelIndex(indexes+x)); } Ascii85Flush(image); break; } } } tile_image=DestroyImage(tile_image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == FaxCompression) || (compression == Group4Compression)) (void) WriteBlobString(image,">>\n"); else { /* Write Colormap object. */ if (compression == NoCompression) (void) WriteBlobString(image,"/Filter [ /ASCII85Decode ]\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); if (compression == NoCompression) Ascii85Initialize(image); for (i=0; i < (ssize_t) image->colors; i++) { if (compression == NoCompression) { Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].red)); Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].green)); Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].blue)); continue; } (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[i].red)); (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[i].green)); (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[i].blue)); } if (compression == NoCompression) Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); } (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write softmask object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (image->matte == MagickFalse) (void) WriteBlobString(image,">>\n"); else { (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Ma%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "ASCII85Decode"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "FlateDecode"); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/ColorSpace /DeviceGray\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { image=DestroyImage(image); ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p))); p++; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar((Quantum) (QuantumRange- GetPixelOpacity(p)))); p++; } } Ascii85Flush(image); break; } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); } (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); /* Write Metadata object. */ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent,"/Title (\xfe\xff"); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) length; i++) (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]); (void) FormatLocaleString(buffer,MaxTextExtent,")\n"); (void) WriteBlobString(image,buffer); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } seconds=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&seconds,&local_time); #else (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time)); #endif (void) FormatLocaleString(date,MaxTextExtent,"D:%04d%02d%02d%02d%02d%02d", local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday, local_time.tm_hour,local_time.tm_min,local_time.tm_sec); (void) FormatLocaleString(buffer,MaxTextExtent,"/CreationDate (%s)\n",date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ModDate (%s)\n",date); (void) WriteBlobString(image,buffer); url=GetMagickHomeURL(); escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MaxTextExtent,"/Producer (%s)\n",escape); escape=DestroyString(escape); url=DestroyString(url); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Xref object. */ offset=TellBlob(image)-xref[0]+ (LocaleCompare(image_info->magick,"PDFA") == 0 ? 6 : 0)+10; (void) WriteBlobString(image,"xref\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"0 %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"0000000000 65535 f \n"); for (i=0; i < (ssize_t) object; i++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%010lu 00000 n \n", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"trailer\n"); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Size %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Info %.20g 0 R\n",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Root %.20g 0 R\n",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image); (void) FormatLocaleString(buffer,MaxTextExtent,"/ID [<%s> <%s>]\n", GetImageProperty(image,"signature"),GetImageProperty(image,"signature")); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"startxref\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%EOF\n"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2616_0
crossvul-cpp_data_bad_2623_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % JJJ PPPP 222 % % J P P 2 2 % % J PPPP 22 % % J J P 2 % % JJ P 22222 % % % % % % Read/Write JPEG-2000 Image Format % % % % Cristy % % Nathan Brown % % June 2001 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/semaphore.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/module.h" #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) #include <openjpeg.h> #endif /* Forward declarations. */ #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) static MagickBooleanType WriteJP2Image(const ImageInfo *,Image *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J 2 K % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJ2K() returns MagickTrue if the image format type, identified by the % magick string, is J2K. % % The format of the IsJ2K method is: % % MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\xff\x4f\xff\x51",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J P 2 % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJP2() returns MagickTrue if the image format type, identified by the % magick string, is JP2. % % The format of the IsJP2 method is: % % MagickBooleanType IsJP2(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsJP2(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\x0d\x0a\x87\x0a",4) == 0) return(MagickTrue); if (length < 12) return(MagickFalse); if (memcmp(magick,"\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a",12) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJP2Image() reads a JPEG 2000 Image file (JP2) or JPEG 2000 % codestream (JPC) image file and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image or set of images. % % JP2 support is originally written by Nathan Brown, nathanbrown@letu.edu. % % The format of the ReadJP2Image method is: % % Image *ReadJP2Image(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) static void JP2ErrorHandler(const char *message,void *client_data) { ExceptionInfo *exception; exception=(ExceptionInfo *) client_data; (void) ThrowMagickException(exception,GetMagickModule(),CoderError, message,"`%s'","OpenJP2"); } static OPJ_SIZE_T JP2ReadHandler(void *buffer,OPJ_SIZE_T length,void *context) { Image *image; ssize_t count; image=(Image *) context; count=ReadBlob(image,(ssize_t) length,(unsigned char *) buffer); if (count == 0) return((OPJ_SIZE_T) -1); return((OPJ_SIZE_T) count); } static OPJ_BOOL JP2SeekHandler(OPJ_OFF_T offset,void *context) { Image *image; image=(Image *) context; return(SeekBlob(image,offset,SEEK_SET) < 0 ? OPJ_FALSE : OPJ_TRUE); } static OPJ_OFF_T JP2SkipHandler(OPJ_OFF_T offset,void *context) { Image *image; image=(Image *) context; return(SeekBlob(image,offset,SEEK_CUR) < 0 ? -1 : offset); } static void JP2WarningHandler(const char *message,void *client_data) { ExceptionInfo *exception; exception=(ExceptionInfo *) client_data; (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'","OpenJP2"); } static OPJ_SIZE_T JP2WriteHandler(void *buffer,OPJ_SIZE_T length,void *context) { Image *image; ssize_t count; image=(Image *) context; count=WriteBlob(image,(ssize_t) length,(unsigned char *) buffer); return((OPJ_SIZE_T) count); } static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) { const char *option; Image *image; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; opj_codestream_index_t *codestream_index = (opj_codestream_index_t *) NULL; opj_dparameters_t parameters; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned char sans[4]; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize JP2 codec. */ if (ReadBlob(image,4,sans) != 4) { image=DestroyImageList(image); return((Image *) NULL); } (void) SeekBlob(image,SEEK_SET,0); if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_decompress(OPJ_CODEC_JPT); else if (IsJ2K(sans,4) != MagickFalse) jp2_codec=opj_create_decompress(OPJ_CODEC_J2K); else jp2_codec=opj_create_decompress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception); opj_set_default_decoder_parameters(&parameters); option=GetImageOption(image_info,"jp2:reduce-factor"); if (option != (const char *) NULL) parameters.cp_reduce=StringToInteger(option); option=GetImageOption(image_info,"jp2:quality-layers"); if (option == (const char *) NULL) option=GetImageOption(image_info,"jp2:layer-number"); if (option != (const char *) NULL) parameters.cp_layer=StringToInteger(option); if (opj_setup_decoder(jp2_codec,&parameters) == 0) { opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToManageJP2Stream"); } jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image)); if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } jp2_status=1; if ((image->columns != 0) && (image->rows != 0)) { /* Extract an area from the image. */ jp2_status=opj_set_decode_area(jp2_codec,jp2_image, (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y, (OPJ_INT32) image->extract_info.x+(ssize_t) image->columns, (OPJ_INT32) image->extract_info.y+(ssize_t) image->rows); if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } } if ((image_info->number_scenes != 0) && (image_info->scene != 0)) jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image, (unsigned int) image_info->scene-1); else if (image->ping == MagickFalse) { jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image); if (jp2_status != 0) jp2_status=opj_end_decompress(jp2_codec,jp2_stream); } if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } opj_stream_destroy(jp2_stream); for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) || (jp2_image->comps[0].dx != jp2_image->comps[i].dx) || (jp2_image->comps[0].dy != jp2_image->comps[i].dy) || (jp2_image->comps[0].prec != jp2_image->comps[i].prec) || (jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd) || ((image->ping == MagickFalse) && (jp2_image->comps[i].data == NULL))) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported") } } /* Convert JP2 image. */ image->columns=(size_t) jp2_image->comps[0].w; image->rows=(size_t) jp2_image->comps[0].h; image->depth=jp2_image->comps[0].prec; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } image->compression=JPEG2000Compression; if (jp2_image->color_space == 2) { SetImageColorspace(image,GRAYColorspace); if (jp2_image->numcomps > 1) image->matte=MagickTrue; } else if (jp2_image->color_space == 3) SetImageColorspace(image,Rec601YCbCrColorspace); if (jp2_image->numcomps > 3) image->matte=MagickTrue; if (jp2_image->icc_profile_buf != (unsigned char *) NULL) { StringInfo *profile; profile=BlobToStringInfo(jp2_image->icc_profile_buf, jp2_image->icc_profile_len); if (profile != (StringInfo *) NULL) SetImageProfile(image,"icc",profile); } if (image->ping != MagickFalse) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); return(GetFirstImageInList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { double pixel, scale; scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1); pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+ (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0)); switch (i) { case 0: { q->red=ClampToQuantum(pixel); q->green=q->red; q->blue=q->red; q->opacity=OpaqueOpacity; break; } case 1: { if (jp2_image->numcomps == 2) { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } q->green=ClampToQuantum(pixel); break; } case 2: { q->blue=ClampToQuantum(pixel); break; } case 3: { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } /* Free resources. */ opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterJP2Image() adds attributes for the JP2 image format to the list of % supported formats. The attributes include the image format tag, a method % method to read and/or write the format, whether the format supports the % saving of more than one frame to the same file or blob, whether the format % supports native in-memory I/O, and a brief description of the format. % % The format of the RegisterJP2Image method is: % % size_t RegisterJP2Image(void) % */ ModuleExport size_t RegisterJP2Image(void) { char version[MaxTextExtent]; MagickInfo *entry; *version='\0'; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) (void) FormatLocaleString(version,MaxTextExtent,"%s",opj_version()); #endif entry=SetMagickInfo("JP2"); entry->description=ConstantString("JPEG-2000 File Format Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJP2; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("J2C"); entry->description=ConstantString("JPEG-2000 Code Stream Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJ2K; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("J2K"); entry->description=ConstantString("JPEG-2000 Code Stream Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJ2K; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPM"); entry->description=ConstantString("JPEG-2000 Code Stream Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJP2; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPT"); entry->description=ConstantString("JPEG-2000 File Format Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJP2; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPC"); entry->description=ConstantString("JPEG-2000 Code Stream Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJP2; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterJP2Image() removes format registrations made by the JP2 module % from the list of supported formats. % % The format of the UnregisterJP2Image method is: % % UnregisterJP2Image(void) % */ ModuleExport void UnregisterJP2Image(void) { (void) UnregisterMagickInfo("JPC"); (void) UnregisterMagickInfo("JPT"); (void) UnregisterMagickInfo("JPM"); (void) UnregisterMagickInfo("JP2"); (void) UnregisterMagickInfo("J2K"); } #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJP2Image() writes an image in the JPEG 2000 image format. % % JP2 support originally written by Nathan Brown, nathanbrown@letu.edu % % The format of the WriteJP2Image method is: % % MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static void CinemaProfileCompliance(const opj_image_t *jp2_image, opj_cparameters_t *parameters) { /* Digital Cinema 4K profile compliant codestream. */ parameters->tile_size_on=OPJ_FALSE; parameters->cp_tdx=1; parameters->cp_tdy=1; parameters->tp_flag='C'; parameters->tp_on=1; parameters->cp_tx0=0; parameters->cp_ty0=0; parameters->image_offset_x0=0; parameters->image_offset_y0=0; parameters->cblockw_init=32; parameters->cblockh_init=32; parameters->csty|=0x01; parameters->prog_order=OPJ_CPRL; parameters->roi_compno=(-1); parameters->subsampling_dx=1; parameters->subsampling_dy=1; parameters->irreversible=1; if ((jp2_image->comps[0].w == 2048) || (jp2_image->comps[0].h == 1080)) { /* Digital Cinema 2K. */ parameters->cp_cinema=OPJ_CINEMA2K_24; parameters->cp_rsiz=OPJ_CINEMA2K; parameters->max_comp_size=1041666; if (parameters->numresolution > 6) parameters->numresolution=6; } if ((jp2_image->comps[0].w == 4096) || (jp2_image->comps[0].h == 2160)) { /* Digital Cinema 4K. */ parameters->cp_cinema=OPJ_CINEMA4K_24; parameters->cp_rsiz=OPJ_CINEMA4K; parameters->max_comp_size=1041666; if (parameters->numresolution < 1) parameters->numresolution=1; if (parameters->numresolution > 7) parameters->numresolution=7; parameters->numpocs=2; parameters->POC[0].tile=1; parameters->POC[0].resno0=0; parameters->POC[0].compno0=0; parameters->POC[0].layno1=1; parameters->POC[0].resno1=parameters->numresolution-1; parameters->POC[0].compno1=3; parameters->POC[0].prg1=OPJ_CPRL; parameters->POC[1].tile=1; parameters->POC[1].resno0=parameters->numresolution-1; parameters->POC[1].compno0=0; parameters->POC[1].layno1=1; parameters->POC[1].resno1=parameters->numresolution; parameters->POC[1].compno1=3; parameters->POC[1].prg1=OPJ_CPRL; } parameters->tcp_numlayers=1; parameters->tcp_rates[0]=((float) (jp2_image->numcomps*jp2_image->comps[0].w* jp2_image->comps[0].h*jp2_image->comps[0].prec))/(parameters->max_comp_size* 8*jp2_image->comps[0].dx*jp2_image->comps[0].dy); parameters->cp_disto_alloc=1; } static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image) { const char *option, *property; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; OPJ_COLOR_SPACE jp2_colorspace; opj_cparameters_t parameters; opj_image_cmptparm_t jp2_info[5]; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned int channels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Initialize JPEG 2000 encoder parameters. */ opj_set_default_encoder_parameters(&parameters); for (i=1; i < 6; i++) if (((size_t) (1 << (i+2)) > image->columns) && ((size_t) (1 << (i+2)) > image->rows)) break; parameters.numresolution=i; option=GetImageOption(image_info,"jp2:number-resolutions"); if (option != (const char *) NULL) parameters.numresolution=StringToInteger(option); parameters.tcp_numlayers=1; parameters.tcp_rates[0]=0; /* lossless */ parameters.cp_disto_alloc=1; if ((image_info->quality != 0) && (image_info->quality != 100)) { parameters.tcp_distoratio[0]=(double) image_info->quality; parameters.cp_fixed_quality=OPJ_TRUE; } if (image_info->extract != (char *) NULL) { RectangleInfo geometry; int flags; /* Set tile size. */ flags=ParseAbsoluteGeometry(image_info->extract,&geometry); parameters.cp_tdx=(int) geometry.width; parameters.cp_tdy=(int) geometry.width; if ((flags & HeightValue) != 0) parameters.cp_tdy=(int) geometry.height; if ((flags & XValue) != 0) parameters.cp_tx0=geometry.x; if ((flags & YValue) != 0) parameters.cp_ty0=geometry.y; parameters.tile_size_on=OPJ_TRUE; } option=GetImageOption(image_info,"jp2:quality"); if (option != (const char *) NULL) { register const char *p; /* Set quality PSNR. */ p=option; for (i=0; sscanf(p,"%f",&parameters.tcp_distoratio[i]) == 1; i++) { if (i >= 100) break; while ((*p != '\0') && (*p != ',')) p++; if (*p == '\0') break; p++; } parameters.tcp_numlayers=i+1; parameters.cp_fixed_quality=OPJ_TRUE; } option=GetImageOption(image_info,"jp2:progression-order"); if (option != (const char *) NULL) { if (LocaleCompare(option,"LRCP") == 0) parameters.prog_order=OPJ_LRCP; if (LocaleCompare(option,"RLCP") == 0) parameters.prog_order=OPJ_RLCP; if (LocaleCompare(option,"RPCL") == 0) parameters.prog_order=OPJ_RPCL; if (LocaleCompare(option,"PCRL") == 0) parameters.prog_order=OPJ_PCRL; if (LocaleCompare(option,"CPRL") == 0) parameters.prog_order=OPJ_CPRL; } option=GetImageOption(image_info,"jp2:rate"); if (option != (const char *) NULL) { register const char *p; /* Set compression rate. */ p=option; for (i=0; sscanf(p,"%f",&parameters.tcp_rates[i]) == 1; i++) { if (i > 100) break; while ((*p != '\0') && (*p != ',')) p++; if (*p == '\0') break; p++; } parameters.tcp_numlayers=i+1; parameters.cp_disto_alloc=OPJ_TRUE; } if (image_info->sampling_factor != (const char *) NULL) (void) sscanf(image_info->sampling_factor,"%d,%d", &parameters.subsampling_dx,&parameters.subsampling_dy); property=GetImageProperty(image,"comment"); if (property != (const char *) NULL) parameters.cp_comment=property; channels=3; jp2_colorspace=OPJ_CLRSPC_SRGB; if (image->colorspace == YUVColorspace) { jp2_colorspace=OPJ_CLRSPC_SYCC; parameters.subsampling_dx=2; } else { if (IsGrayColorspace(image->colorspace) != MagickFalse) { channels=1; jp2_colorspace=OPJ_CLRSPC_GRAY; } else (void) TransformImageColorspace(image,sRGBColorspace); if (image->matte != MagickFalse) channels++; } parameters.tcp_mct=channels == 3 ? 1 : 0; ResetMagickMemory(jp2_info,0,sizeof(jp2_info)); for (i=0; i < (ssize_t) channels; i++) { jp2_info[i].prec=(unsigned int) image->depth; jp2_info[i].bpp=(unsigned int) image->depth; if ((image->depth == 1) && ((LocaleCompare(image_info->magick,"JPT") == 0) || (LocaleCompare(image_info->magick,"JP2") == 0))) { jp2_info[i].prec++; /* OpenJPEG returns exception for depth @ 1 */ jp2_info[i].bpp++; } jp2_info[i].sgnd=0; jp2_info[i].dx=parameters.subsampling_dx; jp2_info[i].dy=parameters.subsampling_dy; jp2_info[i].w=(unsigned int) image->columns; jp2_info[i].h=(unsigned int) image->rows; } jp2_image=opj_image_create(channels,jp2_info,jp2_colorspace); if (jp2_image == (opj_image_t *) NULL) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); jp2_image->x0=parameters.image_offset_x0; jp2_image->y0=parameters.image_offset_y0; jp2_image->x1=(unsigned int) (2*parameters.image_offset_x0+(image->columns-1)* parameters.subsampling_dx+1); jp2_image->y1=(unsigned int) (2*parameters.image_offset_y0+(image->rows-1)* parameters.subsampling_dx+1); if ((image->depth == 12) && ((image->columns == 2048) || (image->rows == 1080) || (image->columns == 4096) || (image->rows == 2160))) CinemaProfileCompliance(jp2_image,&parameters); if (channels == 4) jp2_image->comps[3].alpha=1; else if ((channels == 2) && (jp2_colorspace == OPJ_CLRSPC_GRAY)) jp2_image->comps[1].alpha=1; /* Convert to JP2 pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *p; ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) channels; i++) { double scale; register int *q; scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange; q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx); switch (i) { case 0: { if (jp2_colorspace == OPJ_CLRSPC_GRAY) { *q=(int) (scale*GetPixelLuma(image,p)); break; } *q=(int) (scale*p->red); break; } case 1: { if (jp2_colorspace == OPJ_CLRSPC_GRAY) { *q=(int) (scale*(QuantumRange-p->opacity)); break; } *q=(int) (scale*p->green); break; } case 2: { *q=(int) (scale*p->blue); break; } case 3: { *q=(int) (scale*(QuantumRange-p->opacity)); break; } } } p++; } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_compress(OPJ_CODEC_JPT); else if (LocaleCompare(image_info->magick,"J2K") == 0) jp2_codec=opj_create_compress(OPJ_CODEC_J2K); else jp2_codec=opj_create_compress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,&image->exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,&image->exception); opj_setup_encoder(jp2_codec,&parameters,jp2_image); jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); if (jp2_stream == (opj_stream_t *) NULL) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream); if (jp2_status == 0) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); if ((opj_encode(jp2_codec,jp2_stream) == 0) || (opj_end_compress(jp2_codec,jp2_stream) == 0)) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); } /* Free resources. */ opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); (void) CloseBlob(image); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2623_1
crossvul-cpp_data_good_2616_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP DDDD FFFFF % % P P D D F % % PPPP D D FFF % % P D D F % % P DDDD F % % % % % % Read/Write Portable Document Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/compress.h" #include "magick/constitute.h" #include "magick/delegate.h" #include "magick/delegate-private.h" #include "magick/draw.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/magick-type.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/nt-base-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/signature.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/token.h" #include "magick/transform.h" #include "magick/utility.h" #include "magick/module.h" /* Define declarations. */ #if defined(MAGICKCORE_TIFF_DELEGATE) #define CCITTParam "-1" #else #define CCITTParam "0" #endif /* Forward declarations. */ static MagickBooleanType WritePDFImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v o k e P D F D e l e g a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InvokePDFDelegate() executes the PDF interpreter with the specified command. % % The format of the InvokePDFDelegate method is: % % MagickBooleanType InvokePDFDelegate(const MagickBooleanType verbose, % const char *command,ExceptionInfo *exception) % % A description of each parameter follows: % % o verbose: A value other than zero displays the command prior to % executing it. % % o command: the address of a character string containing the command to % execute. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT) static int MagickDLLCall PDFDelegateMessage(void *handle,const char *message, int length) { char **messages; ssize_t offset; offset=0; messages=(char **) handle; if (*messages == (char *) NULL) *messages=(char *) AcquireQuantumMemory(length+1,sizeof(char *)); else { offset=strlen(*messages); *messages=(char *) ResizeQuantumMemory(*messages,offset+length+1, sizeof(char *)); } (void) memcpy(*messages+offset,message,length); (*messages)[length+offset] ='\0'; return(length); } #endif static MagickBooleanType InvokePDFDelegate(const MagickBooleanType verbose, const char *command,char *message,ExceptionInfo *exception) { int status; #if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT) #define SetArgsStart(command,args_start) \ if (args_start == (const char *) NULL) \ { \ if (*command != '"') \ args_start=strchr(command,' '); \ else \ { \ args_start=strchr(command+1,'"'); \ if (args_start != (const char *) NULL) \ args_start++; \ } \ } #define ExecuteGhostscriptCommand(command,status) \ { \ status=ExternalDelegateCommand(MagickFalse,verbose,command,message, \ exception); \ if (status == 0) \ return(MagickTrue); \ if (status < 0) \ return(MagickFalse); \ (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, \ "FailedToExecuteCommand","`%s' (%d)",command,status); \ return(MagickFalse); \ } char **argv, *errors; const char *args_start=NULL; const GhostInfo *ghost_info; gs_main_instance *interpreter; gsapi_revision_t revision; int argc, code; register ssize_t i; #if defined(MAGICKCORE_WINDOWS_SUPPORT) ghost_info=NTGhostscriptDLLVectors(); #else GhostInfo ghost_info_struct; ghost_info=(&ghost_info_struct); (void) ResetMagickMemory(&ghost_info_struct,0,sizeof(ghost_info_struct)); ghost_info_struct.delete_instance=(void (*)(gs_main_instance *)) gsapi_delete_instance; ghost_info_struct.exit=(int (*)(gs_main_instance *)) gsapi_exit; ghost_info_struct.new_instance=(int (*)(gs_main_instance **,void *)) gsapi_new_instance; ghost_info_struct.init_with_args=(int (*)(gs_main_instance *,int,char **)) gsapi_init_with_args; ghost_info_struct.run_string=(int (*)(gs_main_instance *,const char *,int, int *)) gsapi_run_string; ghost_info_struct.set_stdio=(int (*)(gs_main_instance *,int(*)(void *,char *, int),int(*)(void *,const char *,int),int(*)(void *, const char *, int))) gsapi_set_stdio; ghost_info_struct.revision=(int (*)(gsapi_revision_t *,int)) gsapi_revision; #endif if (ghost_info == (GhostInfo *) NULL) ExecuteGhostscriptCommand(command,status); if ((ghost_info->revision)(&revision,sizeof(revision)) != 0) revision.revision=0; if (verbose != MagickFalse) { (void) fprintf(stdout,"[ghostscript library %.2f]",(double) revision.revision/100.0); SetArgsStart(command,args_start); (void) fputs(args_start,stdout); } errors=(char *) NULL; status=(ghost_info->new_instance)(&interpreter,(void *) &errors); if (status < 0) ExecuteGhostscriptCommand(command,status); code=0; argv=StringToArgv(command,&argc); if (argv == (char **) NULL) { (ghost_info->delete_instance)(interpreter); return(MagickFalse); } (void) (ghost_info->set_stdio)(interpreter,(int(MagickDLLCall *)(void *, char *,int)) NULL,PDFDelegateMessage,PDFDelegateMessage); status=(ghost_info->init_with_args)(interpreter,argc-1,argv+1); if (status == 0) status=(ghost_info->run_string)(interpreter,"systemdict /start get exec\n", 0,&code); (ghost_info->exit)(interpreter); (ghost_info->delete_instance)(interpreter); for (i=0; i < (ssize_t) argc; i++) argv[i]=DestroyString(argv[i]); argv=(char **) RelinquishMagickMemory(argv); if (status != 0) { SetArgsStart(command,args_start); if (status == -101) /* quit */ (void) FormatLocaleString(message,MaxTextExtent, "[ghostscript library %.2f]%s: %s",(double)revision.revision / 100, args_start,errors); else { (void) ThrowMagickException(exception,GetMagickModule(), DelegateError,"PDFDelegateFailed", "`[ghostscript library %.2f]%s': %s", (double)revision.revision / 100,args_start,errors); if (errors != (char *) NULL) errors=DestroyString(errors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Ghostscript returns status %d, exit code %d",status,code); return(MagickFalse); } } if (errors != (char *) NULL) errors=DestroyString(errors); return(MagickTrue); #else status=ExternalDelegateCommand(MagickFalse,verbose,command,(char *) NULL, exception); return(status == 0 ? MagickTrue : MagickFalse); #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P D F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPDF() returns MagickTrue if the image format type, identified by the % magick string, is PDF. % % The format of the IsPDF method is: % % MagickBooleanType IsPDF(const unsigned char *magick,const size_t offset) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o offset: Specifies the offset of the magick string. % */ static MagickBooleanType IsPDF(const unsigned char *magick,const size_t offset) { if (offset < 5) return(MagickFalse); if (LocaleNCompare((const char *) magick,"%PDF-",5) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P D F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPDFImage() reads a Portable Document Format image file and % returns it. It allocates the memory necessary for the new Image structure % and returns a pointer to the new image. % % The format of the ReadPDFImage method is: % % Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsPDFRendered(const char *path) { MagickBooleanType status; struct stat attributes; if ((path == (const char *) NULL) || (*path == '\0')) return(MagickFalse); status=GetPathAttributes(path,&attributes); if ((status != MagickFalse) && S_ISREG(attributes.st_mode) && (attributes.st_size > 0)) return(MagickTrue); return(MagickFalse); } static Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CMYKProcessColor "CMYKProcessColor" #define CropBox "CropBox" #define DefaultCMYK "DefaultCMYK" #define DeviceCMYK "DeviceCMYK" #define MediaBox "MediaBox" #define RenderPostscriptText "Rendering Postscript... " #define PDFRotate "Rotate" #define SpotColor "Separation" #define TrimBox "TrimBox" #define PDFVersion "PDF-" char command[MaxTextExtent], *density, filename[MaxTextExtent], geometry[MaxTextExtent], *options, input_filename[MaxTextExtent], message[MaxTextExtent], postscript_filename[MaxTextExtent]; const char *option; const DelegateInfo *delegate_info; double angle; GeometryInfo geometry_info; Image *image, *next, *pdf_image; ImageInfo *read_info; int c, file; MagickBooleanType cmyk, cropbox, fitPage, status, stop_on_error, trimbox; MagickStatusType flags; PointInfo delta; RectangleInfo bounding_box, page; register char *p; register ssize_t i; SegmentInfo bounds, hires_bounds; size_t scene, spotcolor; ssize_t count; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); /* Open image file. */ image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } (void) ResetMagickMemory(&page,0,sizeof(page)); (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); page.width=(size_t) ceil((double) (page.width*image->x_resolution/delta.x)- 0.5); page.height=(size_t) ceil((double) (page.height*image->y_resolution/delta.y)- 0.5); /* Determine page geometry from the PDF media box. */ cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; cropbox=MagickFalse; option=GetImageOption(image_info,"pdf:use-cropbox"); if (option != (const char *) NULL) cropbox=IsMagickTrue(option); stop_on_error=MagickFalse; option=GetImageOption(image_info,"pdf:stop-on-error"); if (option != (const char *) NULL) stop_on_error=IsMagickTrue(option); trimbox=MagickFalse; option=GetImageOption(image_info,"pdf:use-trimbox"); if (option != (const char *) NULL) trimbox=IsMagickTrue(option); count=0; spotcolor=0; (void) ResetMagickMemory(&bounding_box,0,sizeof(bounding_box)); (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); (void) ResetMagickMemory(&hires_bounds,0,sizeof(hires_bounds)); (void) ResetMagickMemory(command,0,sizeof(command)); angle=0.0; p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note PDF elements. */ if (c == '\n') c=' '; *p++=(char) c; if ((c != (int) '/') && (c != (int) '%') && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *(--p)='\0'; p=command; if (LocaleNCompare(PDFRotate,command,strlen(PDFRotate)) == 0) (void) sscanf(command,"Rotate %lf",&angle); /* Is this a CMYK document? */ if (LocaleNCompare(DefaultCMYK,command,strlen(DefaultCMYK)) == 0) cmyk=MagickTrue; if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0) cmyk=MagickTrue; if (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0) { char name[MaxTextExtent], property[MaxTextExtent], *value; register ssize_t i; /* Note spot names. */ (void) FormatLocaleString(property,MaxTextExtent,"pdf:SpotColor-%.20g", (double) spotcolor++); i=0; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { if ((isspace(c) != 0) || (c == '/') || ((i+1) == MaxTextExtent)) break; name[i++]=(char) c; } name[i]='\0'; value=AcquireString(name); (void) SubstituteString(&value,"#20"," "); (void) SetImageProperty(image,property,value); value=DestroyString(value); continue; } if (LocaleNCompare(PDFVersion,command,strlen(PDFVersion)) == 0) (void) SetImageProperty(image,"pdf:Version",command); if (image_info->page != (char *) NULL) continue; count=0; if (cropbox != MagickFalse) { if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0) { /* Note region defined by crop box. */ count=(ssize_t) sscanf(command,"CropBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"CropBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } } else if (trimbox != MagickFalse) { if (LocaleNCompare(TrimBox,command,strlen(TrimBox)) == 0) { /* Note region defined by trim box. */ count=(ssize_t) sscanf(command,"TrimBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"TrimBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } } else if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0) { /* Note region defined by media box. */ count=(ssize_t) sscanf(command,"MediaBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"MediaBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (count != 4) continue; if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) || (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1))) continue; hires_bounds=bounds; } if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) && (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon)) { /* Set PDF render geometry. */ (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+.15g%+.15g", hires_bounds.x2-bounds.x1,hires_bounds.y2-hires_bounds.y1, hires_bounds.x1,hires_bounds.y1); (void) SetImageProperty(image,"pdf:HiResBoundingBox",geometry); page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)* image->x_resolution/delta.x)-0.5); page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)* image->y_resolution/delta.y)-0.5); } fitPage=MagickFalse; option=GetImageOption(image_info,"pdf:fit-page"); if (option != (char *) NULL) { char *geometry; MagickStatusType flags; geometry=GetPageGeometry(option); flags=ParseMetaGeometry(geometry,&page.x,&page.y,&page.width, &page.height); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidGeometry","`%s'",option); image=DestroyImage(image); return((Image *) NULL); } page.width=(size_t) ceil((double) (page.width*image->x_resolution/delta.x) -0.5); page.height=(size_t) ceil((double) (page.height*image->y_resolution/ delta.y) -0.5); geometry=DestroyString(geometry); fitPage=MagickTrue; } (void) CloseBlob(image); if ((fabs(angle) == 90.0) || (fabs(angle) == 270.0)) { size_t swap; swap=page.width; page.width=page.height; page.height=swap; } if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse) cmyk=MagickFalse; /* Create Ghostscript control file. */ file=AcquireUniqueFileResource(postscript_filename); if (file == -1) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImage(image); return((Image *) NULL); } count=write(file," ",1); file=close(file)-1; /* Render Postscript with the Ghostscript delegate. */ if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) RelinquishUniqueFileResource(postscript_filename); image=DestroyImage(image); return((Image *) NULL); } density=AcquireString(""); options=AcquireString(""); (void) FormatLocaleString(density,MaxTextExtent,"%gx%g",image->x_resolution, image->y_resolution); if ((image_info->page != (char *) NULL) || (fitPage != MagickFalse)) (void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); if (fitPage != MagickFalse) (void) ConcatenateMagickString(options,"-dPSFitPage ",MaxTextExtent); if (cmyk != MagickFalse) (void) ConcatenateMagickString(options,"-dUseCIEColor ",MaxTextExtent); if (cropbox != MagickFalse) (void) ConcatenateMagickString(options,"-dUseCropBox ",MaxTextExtent); if (trimbox != MagickFalse) (void) ConcatenateMagickString(options,"-dUseTrimBox ",MaxTextExtent); if (stop_on_error != MagickFalse) (void) ConcatenateMagickString(options,"-dPDFSTOPONERROR ",MaxTextExtent); option=GetImageOption(image_info,"authenticate"); if (option != (char *) NULL) { char passphrase[MaxTextExtent]; (void) FormatLocaleString(passphrase,MaxTextExtent, "'-sPDFPassword=%s' ",option); (void) ConcatenateMagickString(options,passphrase,MaxTextExtent); } read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { char pages[MaxTextExtent]; (void) FormatLocaleString(pages,MaxTextExtent,"-dFirstPage=%.20g " "-dLastPage=%.20g",(double) read_info->scene+1,(double) (read_info->scene+read_info->number_scenes)); (void) ConcatenateMagickString(options,pages,MaxTextExtent); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } (void) CopyMagickString(filename,read_info->filename,MaxTextExtent); (void) AcquireUniqueFilename(filename); (void) RelinquishUniqueFileResource(filename); (void) ConcatenateMagickString(filename,"%d",MaxTextExtent); (void) FormatLocaleString(command,MaxTextExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options,filename, postscript_filename,input_filename); options=DestroyString(options); density=DestroyString(density); *message='\0'; status=InvokePDFDelegate(read_info->verbose,command,message,exception); (void) RelinquishUniqueFileResource(postscript_filename); (void) RelinquishUniqueFileResource(input_filename); pdf_image=(Image *) NULL; if (status == MagickFalse) for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPDFRendered(read_info->filename) == MagickFalse) break; (void) RelinquishUniqueFileResource(read_info->filename); } else for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPDFRendered(read_info->filename) == MagickFalse) break; read_info->blob=NULL; read_info->length=0; next=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); if (next == (Image *) NULL) break; AppendImageToList(&pdf_image,next); } read_info=DestroyImageInfo(read_info); if (pdf_image == (Image *) NULL) { if (*message != '\0') (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, "PDFDelegateFailed","`%s'",message); image=DestroyImage(image); return((Image *) NULL); } if (LocaleCompare(pdf_image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(pdf_image,exception); if (cmyk_image != (Image *) NULL) { pdf_image=DestroyImageList(pdf_image); pdf_image=cmyk_image; } } if (image_info->number_scenes != 0) { Image *clone_image; register ssize_t i; /* Add place holder images to meet the subimage specification requirement. */ for (i=0; i < (ssize_t) image_info->scene; i++) { clone_image=CloneImage(pdf_image,1,1,MagickTrue,exception); if (clone_image != (Image *) NULL) PrependImageToList(&pdf_image,clone_image); } } do { (void) CopyMagickString(pdf_image->filename,filename,MaxTextExtent); (void) CopyMagickString(pdf_image->magick,image->magick,MaxTextExtent); pdf_image->page=page; (void) CloneImageProfiles(pdf_image,image); (void) CloneImageProperties(pdf_image,image); next=SyncNextImageInList(pdf_image); if (next != (Image *) NULL) pdf_image=next; } while (next != (Image *) NULL); image=DestroyImage(image); scene=0; for (next=GetFirstImageInList(pdf_image); next != (Image *) NULL; ) { next->scene=scene++; next=GetNextImageInList(next); } return(GetFirstImageInList(pdf_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P D F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPDFImage() adds properties for the PDF image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPDFImage method is: % % size_t RegisterPDFImage(void) % */ ModuleExport size_t RegisterPDFImage(void) { MagickInfo *entry; entry=SetMagickInfo("AI"); entry->decoder=(DecodeImageHandler *) ReadPDFImage; entry->encoder=(EncodeImageHandler *) WritePDFImage; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Illustrator CS2"); entry->mime_type=ConstantString("application/pdf"); entry->module=ConstantString("PDF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPDF"); entry->decoder=(DecodeImageHandler *) ReadPDFImage; entry->encoder=(EncodeImageHandler *) WritePDFImage; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated Portable Document Format"); entry->mime_type=ConstantString("application/pdf"); entry->module=ConstantString("PDF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PDF"); entry->decoder=(DecodeImageHandler *) ReadPDFImage; entry->encoder=(EncodeImageHandler *) WritePDFImage; entry->magick=(IsImageFormatHandler *) IsPDF; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Portable Document Format"); entry->mime_type=ConstantString("application/pdf"); entry->module=ConstantString("PDF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PDFA"); entry->decoder=(DecodeImageHandler *) ReadPDFImage; entry->encoder=(EncodeImageHandler *) WritePDFImage; entry->magick=(IsImageFormatHandler *) IsPDF; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Portable Document Archive Format"); entry->mime_type=ConstantString("application/pdf"); entry->module=ConstantString("PDF"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P D F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPDFImage() removes format registrations made by the % PDF module from the list of supported formats. % % The format of the UnregisterPDFImage method is: % % UnregisterPDFImage(void) % */ ModuleExport void UnregisterPDFImage(void) { (void) UnregisterMagickInfo("AI"); (void) UnregisterMagickInfo("EPDF"); (void) UnregisterMagickInfo("PDF"); (void) UnregisterMagickInfo("PDFA"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P D F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePDFImage() writes an image in the Portable Document image % format. % % The format of the WritePDFImage method is: % % MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static char *EscapeParenthesis(const char *source) { char *destination; register char *q; register const char *p; size_t length; assert(source != (const char *) NULL); length=0; for (p=source; *p != '\0'; p++) { if ((*p == '\\') || (*p == '(') || (*p == ')')) { if (~length < 1) ThrowFatalException(ResourceLimitFatalError,"UnableToEscapeString"); length++; } length++; } destination=(char *) NULL; if (~length >= (MaxTextExtent-1)) destination=(char *) AcquireQuantumMemory(length+MaxTextExtent, sizeof(*destination)); if (destination == (char *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToEscapeString"); *destination='\0'; q=destination; for (p=source; *p != '\0'; p++) { if ((*p == '\\') || (*p == '(') || (*p == ')')) *q++='\\'; *q++=(*p); } *q='\0'; return(destination); } static size_t UTF8ToUTF16(const unsigned char *utf8,wchar_t *utf16) { register const unsigned char *p; if (utf16 != (wchar_t *) NULL) { register wchar_t *q; wchar_t c; /* Convert UTF-8 to UTF-16. */ q=utf16; for (p=utf8; *p != '\0'; p++) { if ((*p & 0x80) == 0) *q=(*p); else if ((*p & 0xE0) == 0xC0) { c=(*p); *q=(c & 0x1F) << 6; p++; if ((*p & 0xC0) != 0x80) return(0); *q|=(*p & 0x3F); } else if ((*p & 0xF0) == 0xE0) { c=(*p); *q=c << 12; p++; if ((*p & 0xC0) != 0x80) return(0); c=(*p); *q|=(c & 0x3F) << 6; p++; if ((*p & 0xC0) != 0x80) return(0); *q|=(*p & 0x3F); } else return(0); q++; } *q++=(wchar_t) '\0'; return((size_t) (q-utf16)); } /* Compute UTF-16 string length. */ for (p=utf8; *p != '\0'; p++) { if ((*p & 0x80) == 0) ; else if ((*p & 0xE0) == 0xC0) { p++; if ((*p & 0xC0) != 0x80) return(0); } else if ((*p & 0xF0) == 0xE0) { p++; if ((*p & 0xC0) != 0x80) return(0); p++; if ((*p & 0xC0) != 0x80) return(0); } else return(0); } return((size_t) (p-utf8)); } static wchar_t *ConvertUTF8ToUTF16(const unsigned char *source,size_t *length) { wchar_t *utf16; *length=UTF8ToUTF16(source,(wchar_t *) NULL); if (*length == 0) { register ssize_t i; /* Not UTF-8, just copy. */ *length=strlen((const char *) source); utf16=(wchar_t *) AcquireQuantumMemory(*length+1,sizeof(*utf16)); if (utf16 == (wchar_t *) NULL) return((wchar_t *) NULL); for (i=0; i <= (ssize_t) *length; i++) utf16[i]=source[i]; return(utf16); } utf16=(wchar_t *) AcquireQuantumMemory(*length+1,sizeof(*utf16)); if (utf16 == (wchar_t *) NULL) return((wchar_t *) NULL); *length=UTF8ToUTF16(source,utf16); return(utf16); } static MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info, Image *image,Image *inject_image) { Image *group4_image; ImageInfo *write_info; MagickBooleanType status; size_t length; unsigned char *group4; status=MagickTrue; write_info=CloneImageInfo(image_info); (void) CopyMagickString(write_info->filename,"GROUP4:",MaxTextExtent); (void) CopyMagickString(write_info->magick,"GROUP4",MaxTextExtent); group4_image=CloneImage(inject_image,0,0,MagickTrue,&image->exception); if (group4_image == (Image *) NULL) return(MagickFalse); group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length, &image->exception); group4_image=DestroyImage(group4_image); if (group4 == (unsigned char *) NULL) return(MagickFalse); write_info=DestroyImageInfo(write_info); if (WriteBlob(image,length,group4) != (ssize_t) length) status=MagickFalse; group4=(unsigned char *) RelinquishMagickMemory(group4); return(status); } static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image) { #define CFormat "/Filter [ /%s ]\n" #define ObjectsPerImage 14 DisableMSCWarning(4310) static const char XMPProfile[]= { "<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n" "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n" " <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n" " <xap:ModifyDate>%s</xap:ModifyDate>\n" " <xap:CreateDate>%s</xap:CreateDate>\n" " <xap:MetadataDate>%s</xap:MetadataDate>\n" " <xap:CreatorTool>%s</xap:CreatorTool>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n" " <dc:format>application/pdf</dc:format>\n" " <dc:title>\n" " <rdf:Alt>\n" " <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n" " </rdf:Alt>\n" " </dc:title>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n" " <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n" " <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n" " <pdf:Producer>%s</pdf:Producer>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n" " <pdfaid:part>3</pdfaid:part>\n" " <pdfaid:conformance>B</pdfaid:conformance>\n" " </rdf:Description>\n" " </rdf:RDF>\n" "</x:xmpmeta>\n" "<?xpacket end=\"w\"?>\n" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MaxTextExtent], buffer[MaxTextExtent], date[MaxTextExtent], *escape, **labels, page_geometry[MaxTextExtent], *url; CompressionType compression; const char *device, *option, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; Image *next, *tile_image; MagickBooleanType status; MagickOffsetType offset, scene, *xref; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const IndexPacket *indexes; register const PixelPacket *p; register unsigned char *q; register ssize_t i, x; size_t channels, info_id, length, object, pages_id, root_id, text_size, version; ssize_t count, page_count, y; struct tm local_time; time_t seconds; unsigned char *pixels; wchar_t *utf16; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Allocate X ref memory. */ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(xref,0,2048UL*sizeof(*xref)); /* Write Info object. */ object=0; version=3; if (image_info->compression == JPEG2000Compression) version=(size_t) MagickMax(version,5); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) if (next->matte != MagickFalse) version=(size_t) MagickMax(version,4); if (LocaleCompare(image_info->magick,"PDFA") == 0) version=(size_t) MagickMax(version,6); profile=GetImageProfile(image,"icc"); if (profile != (StringInfo *) NULL) version=(size_t) MagickMax(version,7); (void) FormatLocaleString(buffer,MaxTextExtent,"%%PDF-1.%.20g \n",(double) version); (void) WriteBlobString(image,buffer); if (LocaleCompare(image_info->magick,"PDFA") == 0) { (void) WriteBlobByte(image,'%'); (void) WriteBlobByte(image,0xe2); (void) WriteBlobByte(image,0xe3); (void) WriteBlobByte(image,0xcf); (void) WriteBlobByte(image,0xd3); (void) WriteBlobByte(image,'\n'); } /* Write Catalog object. */ xref[object++]=TellBlob(image); root_id=object; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (LocaleCompare(image_info->magick,"PDFA") != 0) (void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n",(double) object+1); else { (void) FormatLocaleString(buffer,MaxTextExtent,"/Metadata %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n", (double) object+2); } (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Type /Catalog"); option=GetImageOption(image_info,"pdf:page-direction"); if ((option != (const char *) NULL) && (LocaleCompare(option,"right-to-left") != MagickFalse)) (void) WriteBlobString(image,"/ViewerPreferences<</PageDirection/R2L>>\n"); (void) WriteBlobString(image,"\n"); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); GetPathComponent(image->filename,BasePath,basename); if (LocaleCompare(image_info->magick,"PDFA") == 0) { char create_date[MaxTextExtent], modify_date[MaxTextExtent], timestamp[MaxTextExtent], xmp_profile[MaxTextExtent], *url; /* Write XMP object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Subtype /XML\n"); *modify_date='\0'; value=GetImageProperty(image,"date:modify"); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MaxTextExtent); *create_date='\0'; value=GetImageProperty(image,"date:create"); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MaxTextExtent); (void) FormatMagickTime(time((time_t *) NULL),MaxTextExtent,timestamp); url=GetMagickHomeURL(); escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MaxTextExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); url=DestroyString(url); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g\n",(double) i); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Type /Metadata\n"); (void) WriteBlobString(image,">>\nstream\n"); (void) WriteBlobString(image,xmp_profile); (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); } /* Write Pages object. */ xref[object++]=TellBlob(image); pages_id=object; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Pages\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Kids [ %.20g 0 R ",(double) object+1); (void) WriteBlobString(image,buffer); count=(ssize_t) (pages_id+ObjectsPerImage+1); page_count=1; if (image_info->adjoin != MagickFalse) { Image *kid_image; /* Predict page object id's. */ kid_image=image; for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage) { page_count++; profile=GetImageProfile(kid_image,"icc"); if (profile != (StringInfo *) NULL) count+=2; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 R ",(double) count); (void) WriteBlobString(image,buffer); kid_image=GetNextImageInList(kid_image); } xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL, sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) WriteBlobString(image,"]\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Count %.20g\n",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); scene=0; do { MagickBooleanType has_icc_profile; profile=GetImageProfile(image,"icc"); has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((SetImageMonochrome(image,&image->exception) == MagickFalse) || (image->matte != MagickFalse)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)", image->filename); break; } #endif case LZWCompression: { if (LocaleCompare(image_info->magick,"PDFA") == 0) compression=RLECompression; /* LZW compression is forbidden */ break; } case NoCompression: { if (LocaleCompare(image_info->magick,"PDFA") == 0) compression=RLECompression; /* ASCII 85 compression is forbidden */ break; } default: break; } if (compression == JPEG2000Compression) (void) TransformImageColorspace(image,sRGBColorspace); /* Scale relative to dots-per-inch. */ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->x_resolution; resolution.y=image->y_resolution; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MaxTextExtent,"%.20gx%.20g",(double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PDF") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent); (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info, &image->exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); (void) text_size; /* Write Page object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Page\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Parent %.20g 0 R\n", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Resources <<\n"); labels=(char **) NULL; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent, "/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MaxTextExtent, "/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ProcSet %.20g 0 R >>\n", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "/MediaBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "/CropBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Contents %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Thumb %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 10 : 8)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Contents object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); (void) WriteBlobString(image,"q\n"); if (labels != (char **) NULL) for (i=0; labels[i] != (char *) NULL; i++) { (void) WriteBlobString(image,"BT\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/F%.20g %g Tf\n", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g Td\n", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"(%s) Tj\n",labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"ET\n"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MaxTextExtent,"%g 0 0 %g %.20g %.20g cm\n", scale.x,scale.y,(double) geometry.x,(double) geometry.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Im%.20g Do\n",(double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"Q\n"); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Procset object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MaxTextExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MaxTextExtent); else (void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MaxTextExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image," ]\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Font object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (labels != (char **) NULL) { (void) WriteBlobString(image,"/Type /Font\n"); (void) WriteBlobString(image,"/Subtype /Type1\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /F%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/BaseFont /Helvetica\n"); (void) WriteBlobString(image,"/Encoding /MacRomanEncoding\n"); labels=(char **) RelinquishMagickMemory(labels); } (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write XObject object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Im%.20g\n",(double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->matte != MagickFalse) { (void) FormatLocaleString(buffer,MaxTextExtent,"/SMask %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels))) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,image); break; } (void) Huffman2DEncodeImage(image_info,image,image); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p))); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelIndex(indexes+x)); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelIndex(indexes+x))); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) Ascii85Encode(image,(unsigned char) GetPixelIndex(indexes+x)); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Colorspace object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); device="DeviceRGB"; channels=0; if (image->colorspace == CMYKColorspace) { device="DeviceCMYK"; channels=4; } else if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse))) { device="DeviceGray"; channels=1; } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) { device="DeviceRGB"; channels=3; } profile=GetImageProfile(image,"icc"); if ((profile == (StringInfo *) NULL) || (channels == 0)) { if (channels != 0) (void) FormatLocaleString(buffer,MaxTextExtent,"/%s\n",device); else (void) FormatLocaleString(buffer,MaxTextExtent, "[ /Indexed /%s %.20g %.20g 0 R ]\n",device,(double) image->colors- 1,(double) object+3); (void) WriteBlobString(image,buffer); } else { const unsigned char *p; /* Write ICC profile. */ (void) FormatLocaleString(buffer,MaxTextExtent, "[/ICCBased %.20g 0 R]\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"<<\n/N %.20g\n" "/Filter /ASCII85Decode\n/Length %.20g 0 R\n/Alternate /%s\n>>\n" "stream\n",(double) channels,(double) object+1,device); (void) WriteBlobString(image,buffer); offset=TellBlob(image); Ascii85Initialize(image); p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) Ascii85Encode(image,(unsigned char) *p++); Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"endstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"endobj\n"); /* Write Thumb object. */ SetGeometry(image,&geometry); (void) ParseMetaGeometry("106x106+0+0>",&geometry.x,&geometry.y, &geometry.width,&geometry.height); tile_image=ThumbnailImage(image,geometry.width,geometry.height, &image->exception); if (tile_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,image->exception.reason); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows; if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(tile_image,&image->exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,tile_image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,tile_image->exception.reason); break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p))); p++; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p++; } } Ascii85Flush(image); break; } } } else if ((tile_image->storage_class == DirectClass) || (tile_image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,tile_image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,tile_image->exception.reason); break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runoffset encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelIndex(indexes+x)); p++; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelIndex(indexes+x))); p++; } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) Ascii85Encode(image,(unsigned char) GetPixelIndex(indexes+x)); } Ascii85Flush(image); break; } } } tile_image=DestroyImage(tile_image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == FaxCompression) || (compression == Group4Compression)) (void) WriteBlobString(image,">>\n"); else { /* Write Colormap object. */ if (compression == NoCompression) (void) WriteBlobString(image,"/Filter [ /ASCII85Decode ]\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); if (compression == NoCompression) Ascii85Initialize(image); for (i=0; i < (ssize_t) image->colors; i++) { if (compression == NoCompression) { Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].red)); Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].green)); Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].blue)); continue; } (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[i].red)); (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[i].green)); (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[i].blue)); } if (compression == NoCompression) Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); } (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write softmask object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (image->matte == MagickFalse) (void) WriteBlobString(image,">>\n"); else { (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Ma%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "ASCII85Decode"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "FlateDecode"); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/ColorSpace /DeviceGray\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { image=DestroyImage(image); ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p))); p++; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar((Quantum) (QuantumRange- GetPixelOpacity(p)))); p++; } } Ascii85Flush(image); break; } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); } (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); /* Write Metadata object. */ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent,"/Title (\xfe\xff"); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) length; i++) (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]); (void) FormatLocaleString(buffer,MaxTextExtent,")\n"); (void) WriteBlobString(image,buffer); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } seconds=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&seconds,&local_time); #else (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time)); #endif (void) FormatLocaleString(date,MaxTextExtent,"D:%04d%02d%02d%02d%02d%02d", local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday, local_time.tm_hour,local_time.tm_min,local_time.tm_sec); (void) FormatLocaleString(buffer,MaxTextExtent,"/CreationDate (%s)\n",date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ModDate (%s)\n",date); (void) WriteBlobString(image,buffer); url=GetMagickHomeURL(); escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MaxTextExtent,"/Producer (%s)\n",escape); escape=DestroyString(escape); url=DestroyString(url); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Xref object. */ offset=TellBlob(image)-xref[0]+ (LocaleCompare(image_info->magick,"PDFA") == 0 ? 6 : 0)+10; (void) WriteBlobString(image,"xref\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"0 %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"0000000000 65535 f \n"); for (i=0; i < (ssize_t) object; i++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%010lu 00000 n \n", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"trailer\n"); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Size %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Info %.20g 0 R\n",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Root %.20g 0 R\n",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image); (void) FormatLocaleString(buffer,MaxTextExtent,"/ID [<%s> <%s>]\n", GetImageProperty(image,"signature"),GetImageProperty(image,"signature")); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"startxref\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%EOF\n"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-772/c/good_2616_0
crossvul-cpp_data_good_1356_0
/* SPDX-License-Identifier: LGPL-2.1+ */ #include <errno.h> #include <fcntl.h> #include <string.h> #include <sys/ioctl.h> #include <unistd.h> #include <linux/input.h> #include "sd-messages.h" #include "alloc-util.h" #include "fd-util.h" #include "logind-button.h" #include "missing_input.h" #include "string-util.h" #include "util.h" #define CONST_MAX4(a, b, c, d) CONST_MAX(CONST_MAX(a, b), CONST_MAX(c, d)) #define ULONG_BITS (sizeof(unsigned long)*8) static bool bitset_get(const unsigned long *bits, unsigned i) { return (bits[i / ULONG_BITS] >> (i % ULONG_BITS)) & 1UL; } static void bitset_put(unsigned long *bits, unsigned i) { bits[i / ULONG_BITS] |= (unsigned long) 1 << (i % ULONG_BITS); } Button* button_new(Manager *m, const char *name) { Button *b; assert(m); assert(name); b = new0(Button, 1); if (!b) return NULL; b->name = strdup(name); if (!b->name) return mfree(b); if (hashmap_put(m->buttons, b->name, b) < 0) { free(b->name); return mfree(b); } b->manager = m; b->fd = -1; return b; } void button_free(Button *b) { assert(b); hashmap_remove(b->manager->buttons, b->name); sd_event_source_unref(b->io_event_source); sd_event_source_unref(b->check_event_source); if (b->fd >= 0) /* If the device has been unplugged close() returns * ENODEV, let's ignore this, hence we don't use * safe_close() */ (void) close(b->fd); free(b->name); free(b->seat); free(b); } int button_set_seat(Button *b, const char *sn) { char *s; assert(b); assert(sn); s = strdup(sn); if (!s) return -ENOMEM; free(b->seat); b->seat = s; return 0; } static void button_lid_switch_handle_action(Manager *manager, bool is_edge) { HandleAction handle_action; assert(manager); /* If we are docked or on external power, handle the lid switch * differently */ if (manager_is_docked_or_external_displays(manager)) handle_action = manager->handle_lid_switch_docked; else if (manager->handle_lid_switch_ep != _HANDLE_ACTION_INVALID && manager_is_on_external_power()) handle_action = manager->handle_lid_switch_ep; else handle_action = manager->handle_lid_switch; manager_handle_action(manager, INHIBIT_HANDLE_LID_SWITCH, handle_action, manager->lid_switch_ignore_inhibited, is_edge); } static int button_recheck(sd_event_source *e, void *userdata) { Button *b = userdata; assert(b); assert(b->lid_closed); button_lid_switch_handle_action(b->manager, false); return 1; } static int button_install_check_event_source(Button *b) { int r; assert(b); /* Install a post handler, so that we keep rechecking as long as the lid is closed. */ if (b->check_event_source) return 0; r = sd_event_add_post(b->manager->event, &b->check_event_source, button_recheck, b); if (r < 0) return r; return sd_event_source_set_priority(b->check_event_source, SD_EVENT_PRIORITY_IDLE+1); } static int button_dispatch(sd_event_source *s, int fd, uint32_t revents, void *userdata) { Button *b = userdata; struct input_event ev; ssize_t l; assert(s); assert(fd == b->fd); assert(b); l = read(b->fd, &ev, sizeof(ev)); if (l < 0) return errno != EAGAIN ? -errno : 0; if ((size_t) l < sizeof(ev)) return -EIO; if (ev.type == EV_KEY && ev.value > 0) { switch (ev.code) { case KEY_POWER: case KEY_POWER2: log_struct(LOG_INFO, LOG_MESSAGE("Power key pressed."), "MESSAGE_ID=" SD_MESSAGE_POWER_KEY_STR); manager_handle_action(b->manager, INHIBIT_HANDLE_POWER_KEY, b->manager->handle_power_key, b->manager->power_key_ignore_inhibited, true); break; /* The kernel is a bit confused here: KEY_SLEEP = suspend-to-ram, which everybody else calls "suspend" KEY_SUSPEND = suspend-to-disk, which everybody else calls "hibernate" */ case KEY_SLEEP: log_struct(LOG_INFO, LOG_MESSAGE("Suspend key pressed."), "MESSAGE_ID=" SD_MESSAGE_SUSPEND_KEY_STR); manager_handle_action(b->manager, INHIBIT_HANDLE_SUSPEND_KEY, b->manager->handle_suspend_key, b->manager->suspend_key_ignore_inhibited, true); break; case KEY_SUSPEND: log_struct(LOG_INFO, LOG_MESSAGE("Hibernate key pressed."), "MESSAGE_ID=" SD_MESSAGE_HIBERNATE_KEY_STR); manager_handle_action(b->manager, INHIBIT_HANDLE_HIBERNATE_KEY, b->manager->handle_hibernate_key, b->manager->hibernate_key_ignore_inhibited, true); break; } } else if (ev.type == EV_SW && ev.value > 0) { if (ev.code == SW_LID) { log_struct(LOG_INFO, LOG_MESSAGE("Lid closed."), "MESSAGE_ID=" SD_MESSAGE_LID_CLOSED_STR); b->lid_closed = true; button_lid_switch_handle_action(b->manager, true); button_install_check_event_source(b); } else if (ev.code == SW_DOCK) { log_struct(LOG_INFO, LOG_MESSAGE("System docked."), "MESSAGE_ID=" SD_MESSAGE_SYSTEM_DOCKED_STR); b->docked = true; } } else if (ev.type == EV_SW && ev.value == 0) { if (ev.code == SW_LID) { log_struct(LOG_INFO, LOG_MESSAGE("Lid opened."), "MESSAGE_ID=" SD_MESSAGE_LID_OPENED_STR); b->lid_closed = false; b->check_event_source = sd_event_source_unref(b->check_event_source); } else if (ev.code == SW_DOCK) { log_struct(LOG_INFO, LOG_MESSAGE("System undocked."), "MESSAGE_ID=" SD_MESSAGE_SYSTEM_UNDOCKED_STR); b->docked = false; } } return 0; } static int button_suitable(Button *b) { unsigned long types[CONST_MAX(EV_KEY, EV_SW)/ULONG_BITS+1]; assert(b); assert(b->fd); if (ioctl(b->fd, EVIOCGBIT(EV_SYN, sizeof(types)), types) < 0) return -errno; if (bitset_get(types, EV_KEY)) { unsigned long keys[CONST_MAX4(KEY_POWER, KEY_POWER2, KEY_SLEEP, KEY_SUSPEND)/ULONG_BITS+1]; if (ioctl(b->fd, EVIOCGBIT(EV_KEY, sizeof(keys)), keys) < 0) return -errno; if (bitset_get(keys, KEY_POWER) || bitset_get(keys, KEY_POWER2) || bitset_get(keys, KEY_SLEEP) || bitset_get(keys, KEY_SUSPEND)) return true; } if (bitset_get(types, EV_SW)) { unsigned long switches[CONST_MAX(SW_LID, SW_DOCK)/ULONG_BITS+1]; if (ioctl(b->fd, EVIOCGBIT(EV_SW, sizeof(switches)), switches) < 0) return -errno; if (bitset_get(switches, SW_LID) || bitset_get(switches, SW_DOCK)) return true; } return false; } static int button_set_mask(Button *b) { unsigned long types[CONST_MAX(EV_KEY, EV_SW)/ULONG_BITS+1] = {}, keys[CONST_MAX4(KEY_POWER, KEY_POWER2, KEY_SLEEP, KEY_SUSPEND)/ULONG_BITS+1] = {}, switches[CONST_MAX(SW_LID, SW_DOCK)/ULONG_BITS+1] = {}; struct input_mask mask; assert(b); assert(b->fd >= 0); bitset_put(types, EV_KEY); bitset_put(types, EV_SW); mask = (struct input_mask) { .type = EV_SYN, .codes_size = sizeof(types), .codes_ptr = PTR_TO_UINT64(types), }; if (ioctl(b->fd, EVIOCSMASK, &mask) < 0) /* Log only at debug level if the kernel doesn't do EVIOCSMASK yet */ return log_full_errno(IN_SET(errno, ENOTTY, EOPNOTSUPP, EINVAL) ? LOG_DEBUG : LOG_WARNING, errno, "Failed to set EV_SYN event mask on /dev/input/%s: %m", b->name); bitset_put(keys, KEY_POWER); bitset_put(keys, KEY_POWER2); bitset_put(keys, KEY_SLEEP); bitset_put(keys, KEY_SUSPEND); mask = (struct input_mask) { .type = EV_KEY, .codes_size = sizeof(keys), .codes_ptr = PTR_TO_UINT64(keys), }; if (ioctl(b->fd, EVIOCSMASK, &mask) < 0) return log_warning_errno(errno, "Failed to set EV_KEY event mask on /dev/input/%s: %m", b->name); bitset_put(switches, SW_LID); bitset_put(switches, SW_DOCK); mask = (struct input_mask) { .type = EV_SW, .codes_size = sizeof(switches), .codes_ptr = PTR_TO_UINT64(switches), }; if (ioctl(b->fd, EVIOCSMASK, &mask) < 0) return log_warning_errno(errno, "Failed to set EV_SW event mask on /dev/input/%s: %m", b->name); return 0; } int button_open(Button *b) { char *p, name[256]; int r; assert(b); b->fd = safe_close(b->fd); p = strjoina("/dev/input/", b->name); b->fd = open(p, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK); if (b->fd < 0) return log_warning_errno(errno, "Failed to open %s: %m", p); r = button_suitable(b); if (r < 0) return log_warning_errno(r, "Failed to determine whether input device is relevant to us: %m"); if (r == 0) return log_debug_errno(SYNTHETIC_ERRNO(EADDRNOTAVAIL), "Device %s does not expose keys or switches relevant to us, ignoring.", p); if (ioctl(b->fd, EVIOCGNAME(sizeof(name)), name) < 0) { r = log_error_errno(errno, "Failed to get input name: %m"); goto fail; } (void) button_set_mask(b); b->io_event_source = sd_event_source_unref(b->io_event_source); r = sd_event_add_io(b->manager->event, &b->io_event_source, b->fd, EPOLLIN, button_dispatch, b); if (r < 0) { log_error_errno(r, "Failed to add button event: %m"); goto fail; } log_info("Watching system buttons on /dev/input/%s (%s)", b->name, name); return 0; fail: b->fd = safe_close(b->fd); return r; } int button_check_switches(Button *b) { unsigned long switches[CONST_MAX(SW_LID, SW_DOCK)/ULONG_BITS+1] = {}; assert(b); if (b->fd < 0) return -EINVAL; if (ioctl(b->fd, EVIOCGSW(sizeof(switches)), switches) < 0) return -errno; b->lid_closed = bitset_get(switches, SW_LID); b->docked = bitset_get(switches, SW_DOCK); if (b->lid_closed) button_install_check_event_source(b); return 0; }
./CrossVul/dataset_final_sorted/CWE-772/c/good_1356_0
crossvul-cpp_data_bad_2608_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M SSSSS L % % MM MM SS L % % M M M SSS L % % M M SS L % % M M SSSSS LLLLL % % % % % % Execute Magick Scripting Language Scripts. % % % % Software Design % % Cristy % % Leonard Rosenthol % % William Radcliffe % % December 2001 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/annotate.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/composite.h" #include "MagickCore/constitute.h" #include "MagickCore/decorate.h" #include "MagickCore/display.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/effect.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum-private.h" #include "MagickCore/registry.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/shear.h" #include "MagickCore/signature.h" #include "MagickCore/statistic.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/transform.h" #include "MagickCore/threshold.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_XML_DELEGATE) # if defined(MAGICKCORE_WINDOWS_SUPPORT) # if !defined(__MINGW32__) && !defined(__MINGW64__) # include <win32config.h> # endif # endif # include <libxml/parser.h> # include <libxml/xmlmemory.h> # include <libxml/parserInternals.h> # include <libxml/xmlerror.h> #endif /* Define Declatations. */ #define ThrowMSLException(severity,tag,reason) \ (void) ThrowMagickException(msl_info->exception,GetMagickModule(),severity, \ tag,"`%s'",reason); /* Typedef declaractions. */ typedef struct _MSLGroupInfo { size_t numImages; /* how many images are in this group */ } MSLGroupInfo; typedef struct _MSLInfo { ExceptionInfo *exception; ssize_t n, number_groups; ImageInfo **image_info; DrawInfo **draw_info; Image **attributes, **image; char *content; MSLGroupInfo *group_info; #if defined(MAGICKCORE_XML_DELEGATE) xmlParserCtxtPtr parser; xmlDocPtr document; #endif } MSLInfo; /* Forward declarations. */ #if defined(MAGICKCORE_XML_DELEGATE) static MagickBooleanType WriteMSLImage(const ImageInfo *,Image *,ExceptionInfo *); static MagickBooleanType SetMSLAttributes(MSLInfo *,const char *,const char *); #endif #if defined(MAGICKCORE_XML_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d M S L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMSLImage() reads a Magick Scripting Language file and returns it. % It allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadMSLImage method is: % % Image *ReadMSLImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static inline Image *GetImageCache(const ImageInfo *image_info,const char *path, ExceptionInfo *exception) { char key[MagickPathExtent]; ExceptionInfo *sans_exception; Image *image; ImageInfo *read_info; (void) FormatLocaleString(key,MagickPathExtent,"cache:%s",path); sans_exception=AcquireExceptionInfo(); image=(Image *) GetImageRegistry(ImageRegistryType,key,sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if (image != (Image *) NULL) return(image); read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->filename,path,MagickPathExtent); image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) (void) SetImageRegistry(ImageRegistryType,key,image,exception); return(image); } static int IsPathDirectory(const char *path) { MagickBooleanType status; struct stat attributes; if ((path == (const char *) NULL) || (*path == '\0')) return(MagickFalse); status=GetPathAttributes(path,&attributes); if (status == MagickFalse) return(-1); if (S_ISDIR(attributes.st_mode) == 0) return(0); return(1); } static int MSLIsStandalone(void *context) { MSLInfo *msl_info; /* Is this document tagged standalone? */ (void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.MSLIsStandalone()"); msl_info=(MSLInfo *) context; return(msl_info->document->standalone == 1); } static int MSLHasInternalSubset(void *context) { MSLInfo *msl_info; /* Does this document has an internal subset? */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.MSLHasInternalSubset()"); msl_info=(MSLInfo *) context; return(msl_info->document->intSubset != NULL); } static int MSLHasExternalSubset(void *context) { MSLInfo *msl_info; /* Does this document has an external subset? */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.MSLHasExternalSubset()"); msl_info=(MSLInfo *) context; return(msl_info->document->extSubset != NULL); } static void MSLInternalSubset(void *context,const xmlChar *name, const xmlChar *external_id,const xmlChar *system_id) { MSLInfo *msl_info; /* Does this document has an internal subset? */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.internalSubset(%s %s %s)",name, (external_id != (const xmlChar *) NULL ? (const char *) external_id : " "), (system_id != (const xmlChar *) NULL ? (const char *) system_id : " ")); msl_info=(MSLInfo *) context; (void) xmlCreateIntSubset(msl_info->document,name,external_id,system_id); } static xmlParserInputPtr MSLResolveEntity(void *context, const xmlChar *public_id,const xmlChar *system_id) { MSLInfo *msl_info; xmlParserInputPtr stream; /* Special entity resolver, better left to the parser, it has more context than the application layer. The default behaviour is to not resolve the entities, in that case the ENTITY_REF nodes are built in the structure (and the parameter values). */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.resolveEntity(%s, %s)", (public_id != (const xmlChar *) NULL ? (const char *) public_id : "none"), (system_id != (const xmlChar *) NULL ? (const char *) system_id : "none")); msl_info=(MSLInfo *) context; stream=xmlLoadExternalEntity((const char *) system_id,(const char *) public_id,msl_info->parser); return(stream); } static xmlEntityPtr MSLGetEntity(void *context,const xmlChar *name) { MSLInfo *msl_info; /* Get an entity by name. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.MSLGetEntity(%s)",(const char *) name); msl_info=(MSLInfo *) context; return(xmlGetDocEntity(msl_info->document,name)); } static xmlEntityPtr MSLGetParameterEntity(void *context,const xmlChar *name) { MSLInfo *msl_info; /* Get a parameter entity by name. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.getParameterEntity(%s)",(const char *) name); msl_info=(MSLInfo *) context; return(xmlGetParameterEntity(msl_info->document,name)); } static void MSLEntityDeclaration(void *context,const xmlChar *name,int type, const xmlChar *public_id,const xmlChar *system_id,xmlChar *content) { MSLInfo *msl_info; /* An entity definition has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.entityDecl(%s, %d, %s, %s, %s)",name,type, public_id != (const xmlChar *) NULL ? (const char *) public_id : "none", system_id != (const xmlChar *) NULL ? (const char *) system_id : "none", content); msl_info=(MSLInfo *) context; if (msl_info->parser->inSubset == 1) (void) xmlAddDocEntity(msl_info->document,name,type,public_id,system_id, content); else if (msl_info->parser->inSubset == 2) (void) xmlAddDtdEntity(msl_info->document,name,type,public_id,system_id, content); } static void MSLAttributeDeclaration(void *context,const xmlChar *element, const xmlChar *name,int type,int value,const xmlChar *default_value, xmlEnumerationPtr tree) { MSLInfo *msl_info; xmlChar *fullname, *prefix; xmlParserCtxtPtr parser; /* An attribute definition has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.attributeDecl(%s, %s, %d, %d, %s, ...)\n",element,name,type,value, default_value); msl_info=(MSLInfo *) context; fullname=(xmlChar *) NULL; prefix=(xmlChar *) NULL; parser=msl_info->parser; fullname=(xmlChar *) xmlSplitQName(parser,name,&prefix); if (parser->inSubset == 1) (void) xmlAddAttributeDecl(&parser->vctxt,msl_info->document->intSubset, element,fullname,prefix,(xmlAttributeType) type, (xmlAttributeDefault) value,default_value,tree); else if (parser->inSubset == 2) (void) xmlAddAttributeDecl(&parser->vctxt,msl_info->document->extSubset, element,fullname,prefix,(xmlAttributeType) type, (xmlAttributeDefault) value,default_value,tree); if (prefix != (xmlChar *) NULL) xmlFree(prefix); if (fullname != (xmlChar *) NULL) xmlFree(fullname); } static void MSLElementDeclaration(void *context,const xmlChar *name,int type, xmlElementContentPtr content) { MSLInfo *msl_info; xmlParserCtxtPtr parser; /* An element definition has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.elementDecl(%s, %d, ...)",name,type); msl_info=(MSLInfo *) context; parser=msl_info->parser; if (parser->inSubset == 1) (void) xmlAddElementDecl(&parser->vctxt,msl_info->document->intSubset, name,(xmlElementTypeVal) type,content); else if (parser->inSubset == 2) (void) xmlAddElementDecl(&parser->vctxt,msl_info->document->extSubset, name,(xmlElementTypeVal) type,content); } static void MSLNotationDeclaration(void *context,const xmlChar *name, const xmlChar *public_id,const xmlChar *system_id) { MSLInfo *msl_info; xmlParserCtxtPtr parser; /* What to do when a notation declaration has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.notationDecl(%s, %s, %s)",name, public_id != (const xmlChar *) NULL ? (const char *) public_id : "none", system_id != (const xmlChar *) NULL ? (const char *) system_id : "none"); msl_info=(MSLInfo *) context; parser=msl_info->parser; if (parser->inSubset == 1) (void) xmlAddNotationDecl(&parser->vctxt,msl_info->document->intSubset, name,public_id,system_id); else if (parser->inSubset == 2) (void) xmlAddNotationDecl(&parser->vctxt,msl_info->document->intSubset, name,public_id,system_id); } static void MSLUnparsedEntityDeclaration(void *context,const xmlChar *name, const xmlChar *public_id,const xmlChar *system_id,const xmlChar *notation) { MSLInfo *msl_info; /* What to do when an unparsed entity declaration is parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.unparsedEntityDecl(%s, %s, %s, %s)",name, public_id != (const xmlChar *) NULL ? (const char *) public_id : "none", system_id != (const xmlChar *) NULL ? (const char *) system_id : "none", notation); msl_info=(MSLInfo *) context; (void) xmlAddDocEntity(msl_info->document,name, XML_EXTERNAL_GENERAL_UNPARSED_ENTITY,public_id,system_id,notation); } static void MSLSetDocumentLocator(void *context,xmlSAXLocatorPtr location) { MSLInfo *msl_info; /* Receive the document locator at startup, actually xmlDefaultSAXLocator. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.setDocumentLocator()\n"); (void) location; msl_info=(MSLInfo *) context; (void) msl_info; } static void MSLStartDocument(void *context) { MSLInfo *msl_info; xmlParserCtxtPtr parser; /* Called when the document start being processed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.startDocument()"); msl_info=(MSLInfo *) context; parser=msl_info->parser; msl_info->document=xmlNewDoc(parser->version); if (msl_info->document == (xmlDocPtr) NULL) return; if (parser->encoding == NULL) msl_info->document->encoding=NULL; else msl_info->document->encoding=xmlStrdup(parser->encoding); msl_info->document->standalone=parser->standalone; } static void MSLEndDocument(void *context) { MSLInfo *msl_info; /* Called when the document end has been detected. */ (void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.endDocument()"); msl_info=(MSLInfo *) context; if (msl_info->content != (char *) NULL) msl_info->content=DestroyString(msl_info->content); } static void MSLPushImage(MSLInfo *msl_info,Image *image) { ssize_t n; (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(msl_info != (MSLInfo *) NULL); msl_info->n++; n=msl_info->n; msl_info->image_info=(ImageInfo **) ResizeQuantumMemory(msl_info->image_info, (n+1),sizeof(*msl_info->image_info)); msl_info->draw_info=(DrawInfo **) ResizeQuantumMemory(msl_info->draw_info, (n+1),sizeof(*msl_info->draw_info)); msl_info->attributes=(Image **) ResizeQuantumMemory(msl_info->attributes, (n+1),sizeof(*msl_info->attributes)); msl_info->image=(Image **) ResizeQuantumMemory(msl_info->image,(n+1), sizeof(*msl_info->image)); if ((msl_info->image_info == (ImageInfo **) NULL) || (msl_info->draw_info == (DrawInfo **) NULL) || (msl_info->attributes == (Image **) NULL) || (msl_info->image == (Image **) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed") msl_info->image_info[n]=CloneImageInfo(msl_info->image_info[n-1]); msl_info->draw_info[n]=CloneDrawInfo(msl_info->image_info[n-1], msl_info->draw_info[n-1]); if (image == (Image *) NULL) msl_info->attributes[n]=AcquireImage(msl_info->image_info[n], msl_info->exception); else msl_info->attributes[n]=CloneImage(image,0,0,MagickTrue, msl_info->exception); msl_info->image[n]=(Image *) image; if ((msl_info->image_info[n] == (ImageInfo *) NULL) || (msl_info->attributes[n] == (Image *) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed") if (msl_info->number_groups != 0) msl_info->group_info[msl_info->number_groups-1].numImages++; } static void MSLPopImage(MSLInfo *msl_info) { if (msl_info->number_groups != 0) return; if (msl_info->image[msl_info->n] != (Image *) NULL) msl_info->image[msl_info->n]=DestroyImage(msl_info->image[msl_info->n]); msl_info->attributes[msl_info->n]=DestroyImage( msl_info->attributes[msl_info->n]); msl_info->image_info[msl_info->n]=DestroyImageInfo( msl_info->image_info[msl_info->n]); msl_info->n--; } static void MSLStartElement(void *context,const xmlChar *tag, const xmlChar **attributes) { AffineMatrix affine, current; ChannelType channel; ChannelType channel_mask; char *attribute, key[MagickPathExtent], *value; const char *keyword; double angle; DrawInfo *draw_info; ExceptionInfo *exception; GeometryInfo geometry_info; Image *image; int flags; ssize_t option, j, n, x, y; MSLInfo *msl_info; RectangleInfo geometry; register ssize_t i; size_t height, width; /* Called when an opening tag has been processed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.startElement(%s",tag); exception=AcquireExceptionInfo(); msl_info=(MSLInfo *) context; n=msl_info->n; keyword=(const char *) NULL; value=(char *) NULL; SetGeometryInfo(&geometry_info); (void) ResetMagickMemory(&geometry,0,sizeof(geometry)); channel=DefaultChannels; switch (*tag) { case 'A': case 'a': { if (LocaleCompare((const char *) tag,"add-noise") == 0) { Image *noise_image; NoiseType noise; /* Add noise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } noise=UniformNoise; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'N': case 'n': { if (LocaleCompare(keyword,"noise") == 0) { option=ParseCommandOption(MagickNoiseOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); noise=(NoiseType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } channel_mask=SetImageChannelMask(msl_info->image[n],channel); noise_image=AddNoiseImage(msl_info->image[n],noise,1.0, msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); if (noise_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=noise_image; break; } if (LocaleCompare((const char *) tag,"annotate") == 0) { char text[MagickPathExtent]; /* Annotate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); angle=0.0; current=draw_info->affine; GetAffineMatrix(&affine); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"affine") == 0) { char *p; p=value; draw_info->affine.sx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.rx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ry=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.sy=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.tx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ty=StringToDouble(p,&p); break; } if (LocaleCompare(keyword,"align") == 0) { option=ParseCommandOption(MagickAlignOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedAlignType", value); draw_info->align=(AlignType) option; break; } if (LocaleCompare(keyword,"antialias") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); draw_info->stroke_antialias=(MagickBooleanType) option; draw_info->text_antialias=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"encoding") == 0) { CloneString(&draw_info->encoding,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->fill,exception); break; } if (LocaleCompare(keyword,"family") == 0) { CloneString(&draw_info->family,value); break; } if (LocaleCompare(keyword,"font") == 0) { CloneString(&draw_info->font,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGravityGeometry(msl_info->image[n],value, &geometry,exception); break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); draw_info->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"pointsize") == 0) { draw_info->pointsize=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { angle=StringToDouble(value,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.sx=geometry_info.rho; affine.sy=geometry_info.sigma; break; } if (LocaleCompare(keyword,"skewX") == 0) { angle=StringToDouble(value,(char **) NULL); affine.ry=tan(DegreesToRadians(fmod((double) angle, 360.0))); break; } if (LocaleCompare(keyword,"skewY") == 0) { angle=StringToDouble(value,(char **) NULL); affine.rx=tan(DegreesToRadians(fmod((double) angle, 360.0))); break; } if (LocaleCompare(keyword,"stretch") == 0) { option=ParseCommandOption(MagickStretchOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStretchType", value); draw_info->stretch=(StretchType) option; break; } if (LocaleCompare(keyword, "stroke") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->stroke,exception); break; } if (LocaleCompare(keyword,"strokewidth") == 0) { draw_info->stroke_width=StringToLong(value); break; } if (LocaleCompare(keyword,"style") == 0) { option=ParseCommandOption(MagickStyleOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStyleType", value); draw_info->style=(StyleType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"text") == 0) { CloneString(&draw_info->text,value); break; } if (LocaleCompare(keyword,"translate") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.tx=geometry_info.rho; affine.ty=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'U': case 'u': { if (LocaleCompare(keyword, "undercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->undercolor,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"weight") == 0) { draw_info->weight=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(text,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); CloneString(&draw_info->geometry,text); draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx; draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx; draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy; draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy; draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+ affine.tx; draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+ affine.ty; (void) AnnotateImage(msl_info->image[n],draw_info, msl_info->exception); draw_info=DestroyDrawInfo(draw_info); break; } if (LocaleCompare((const char *) tag,"append") == 0) { Image *append_image; MagickBooleanType stack; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } stack=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'S': case 's': { if (LocaleCompare(keyword,"stack") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); stack=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } append_image=AppendImages(msl_info->image[n],stack, msl_info->exception); if (append_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=append_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); break; } case 'B': case 'b': { if (LocaleCompare((const char *) tag,"blur") == 0) { Image *blur_image; /* Blur image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { geometry_info.sigma=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } channel_mask=SetImageChannelMask(msl_info->image[n],channel); blur_image=BlurImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); if (blur_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=blur_image; break; } if (LocaleCompare((const char *) tag,"border") == 0) { Image *border_image; /* Border image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"compose") == 0) { option=ParseCommandOption(MagickComposeOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedComposeType", value); msl_info->image[n]->compose=(CompositeOperator) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &msl_info->image[n]->border_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } border_image=BorderImage(msl_info->image[n],&geometry, msl_info->image[n]->compose,msl_info->exception); if (border_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=border_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'C': case 'c': { if (LocaleCompare((const char *) tag,"colorize") == 0) { char blend[MagickPathExtent]; Image *colorize_image; PixelInfo target; /* Add noise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } GetPixelInfo(msl_info->image[n],&target); (void) CopyMagickString(blend,"100",MagickPathExtent); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blend") == 0) { (void) CopyMagickString(blend,value,MagickPathExtent); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &target,msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } colorize_image=ColorizeImage(msl_info->image[n],blend,&target, msl_info->exception); if (colorize_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=colorize_image; break; } if (LocaleCompare((const char *) tag, "charcoal") == 0) { double radius = 0.0, sigma = 1.0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } /* NOTE: charcoal can have no attributes, since we use all the defaults! */ if (attributes != (const xmlChar **) NULL) { for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { radius=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { sigma = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } } /* charcoal image. */ { Image *newImage; newImage=CharcoalImage(msl_info->image[n],radius,sigma, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } if (LocaleCompare((const char *) tag,"chop") == 0) { Image *chop_image; /* Chop image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } chop_image=ChopImage(msl_info->image[n],&geometry, msl_info->exception); if (chop_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=chop_image; break; } if (LocaleCompare((const char *) tag,"color-floodfill") == 0) { PaintMethod paint_method; PixelInfo target; /* Color floodfill image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); SetGeometry(msl_info->image[n],&geometry); paint_method=FloodfillMethod; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"bordercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &target,exception); paint_method=FillToBorderMethod; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->fill,exception); break; } if (LocaleCompare(keyword,"fuzz") == 0) { msl_info->image[n]->fuzz=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FloodfillPaintImage(msl_info->image[n],draw_info,&target, geometry.x,geometry.y,paint_method == FloodfillMethod ? MagickFalse : MagickTrue,msl_info->exception); draw_info=DestroyDrawInfo(draw_info); break; } if (LocaleCompare((const char *) tag,"comment") == 0) break; if (LocaleCompare((const char *) tag,"composite") == 0) { char composite_geometry[MagickPathExtent]; CompositeOperator compose; Image *composite_image, *rotate_image; /* Composite image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } composite_image=NewImageList(); compose=OverCompositeOp; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"compose") == 0) { option=ParseCommandOption(MagickComposeOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedComposeType", value); compose=(CompositeOperator) option; break; } break; } case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id", exception); if ((attribute != (const char *) NULL) && (LocaleCompare(attribute,value) == 0)) { composite_image=CloneImage(msl_info->image[j],0,0, MagickFalse,exception); break; } } break; } default: break; } } if (composite_image == (Image *) NULL) break; rotate_image=NewImageList(); SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blend") == 0) { (void) SetImageArtifact(composite_image, "compose:args",value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } if (LocaleCompare(keyword, "color") == 0) { (void) QueryColorCompliance(value,AllCompliance, &composite_image->background_color,exception); break; } if (LocaleCompare(keyword,"compose") == 0) break; ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); msl_info->image[n]->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) break; ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'M': case 'm': { if (LocaleCompare(keyword,"mask") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id", exception); if ((attribute != (const char *) NULL) && (LocaleCompare(value,value) == 0)) { SetImageType(composite_image,TrueColorAlphaType, exception); (void) CompositeImage(composite_image, msl_info->image[j],CopyAlphaCompositeOp,MagickTrue, 0,0,exception); break; } } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { ssize_t opacity, y; register ssize_t x; register Quantum *q; CacheView *composite_view; opacity=StringToLong(value); if (compose != DissolveCompositeOp) { (void) SetImageAlpha(composite_image,(Quantum) opacity,exception); break; } (void) SetImageArtifact(msl_info->image[n], "compose:args",value); if (composite_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlpha(composite_image,OpaqueAlpha, exception); composite_view=AcquireAuthenticCacheView(composite_image,exception); for (y=0; y < (ssize_t) composite_image->rows ; y++) { q=GetCacheViewAuthenticPixels(composite_view,0,y, (ssize_t) composite_image->columns,1,exception); for (x=0; x < (ssize_t) composite_image->columns; x++) { if (GetPixelAlpha(composite_image,q) == OpaqueAlpha) SetPixelAlpha(composite_image, ClampToQuantum(opacity),q); q+=GetPixelChannels(composite_image); } if (SyncCacheViewAuthenticPixels(composite_view,exception) == MagickFalse) break; } composite_view=DestroyCacheView(composite_view); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { rotate_image=RotateImage(composite_image, StringToDouble(value,(char **) NULL),exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"tile") == 0) { MagickBooleanType tile; option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); tile=(MagickBooleanType) option; (void) tile; if (rotate_image != (Image *) NULL) (void) SetImageArtifact(rotate_image, "compose:outside-overlay","false"); else (void) SetImageArtifact(composite_image, "compose:outside-overlay","false"); image=msl_info->image[n]; height=composite_image->rows; width=composite_image->columns; for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) height) for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) width) { if (rotate_image != (Image *) NULL) (void) CompositeImage(image,rotate_image,compose, MagickTrue,x,y,exception); else (void) CompositeImage(image,composite_image, compose,MagickTrue,x,y,exception); } if (rotate_image != (Image *) NULL) rotate_image=DestroyImage(rotate_image); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } image=msl_info->image[n]; (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns, (double) composite_image->rows,(double) geometry.x,(double) geometry.y); flags=ParseGravityGeometry(image,composite_geometry,&geometry, exception); channel_mask=SetImageChannelMask(image,channel); if (rotate_image == (Image *) NULL) CompositeImage(image,composite_image,compose,MagickTrue,geometry.x, geometry.y,exception); else { /* Rotate image. */ geometry.x-=(ssize_t) (rotate_image->columns- composite_image->columns)/2; geometry.y-=(ssize_t) (rotate_image->rows- composite_image->rows)/2; CompositeImage(image,rotate_image,compose,MagickTrue,geometry.x, geometry.y,exception); rotate_image=DestroyImage(rotate_image); } (void) SetImageChannelMask(image,channel_mask); composite_image=DestroyImage(composite_image); break; } if (LocaleCompare((const char *) tag,"contrast") == 0) { MagickBooleanType sharpen; /* Contrast image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } sharpen=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'S': case 's': { if (LocaleCompare(keyword,"sharpen") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); sharpen=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) ContrastImage(msl_info->image[n],sharpen, msl_info->exception); break; } if (LocaleCompare((const char *) tag,"crop") == 0) { Image *crop_image; /* Crop image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGravityGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } crop_image=CropImage(msl_info->image[n],&geometry, msl_info->exception); if (crop_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=crop_image; break; } if (LocaleCompare((const char *) tag,"cycle-colormap") == 0) { ssize_t display; /* Cycle-colormap image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } display=0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"display") == 0) { display=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) CycleColormapImage(msl_info->image[n],display,exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'D': case 'd': { if (LocaleCompare((const char *) tag,"despeckle") == 0) { Image *despeckle_image; /* Despeckle image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } despeckle_image=DespeckleImage(msl_info->image[n], msl_info->exception); if (despeckle_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=despeckle_image; break; } if (LocaleCompare((const char *) tag,"display") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) DisplayImages(msl_info->image_info[n],msl_info->image[n], msl_info->exception); break; } if (LocaleCompare((const char *) tag,"draw") == 0) { char text[MagickPathExtent]; /* Annotate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); angle=0.0; current=draw_info->affine; GetAffineMatrix(&affine); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"affine") == 0) { char *p; p=value; draw_info->affine.sx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.rx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ry=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.sy=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.tx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ty=StringToDouble(p,&p); break; } if (LocaleCompare(keyword,"align") == 0) { option=ParseCommandOption(MagickAlignOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedAlignType", value); draw_info->align=(AlignType) option; break; } if (LocaleCompare(keyword,"antialias") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); draw_info->stroke_antialias=(MagickBooleanType) option; draw_info->text_antialias=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"encoding") == 0) { CloneString(&draw_info->encoding,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->fill,exception); break; } if (LocaleCompare(keyword,"family") == 0) { CloneString(&draw_info->family,value); break; } if (LocaleCompare(keyword,"font") == 0) { CloneString(&draw_info->font,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); draw_info->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"points") == 0) { if (LocaleCompare(draw_info->primitive,"path") == 0) { (void) ConcatenateString(&draw_info->primitive," '"); ConcatenateString(&draw_info->primitive,value); (void) ConcatenateString(&draw_info->primitive,"'"); } else { (void) ConcatenateString(&draw_info->primitive," "); ConcatenateString(&draw_info->primitive,value); } break; } if (LocaleCompare(keyword,"pointsize") == 0) { draw_info->pointsize=StringToDouble(value, (char **) NULL); break; } if (LocaleCompare(keyword,"primitive") == 0) { CloneString(&draw_info->primitive,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { angle=StringToDouble(value,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.sx=geometry_info.rho; affine.sy=geometry_info.sigma; break; } if (LocaleCompare(keyword,"skewX") == 0) { angle=StringToDouble(value,(char **) NULL); affine.ry=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"skewY") == 0) { angle=StringToDouble(value,(char **) NULL); affine.rx=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"stretch") == 0) { option=ParseCommandOption(MagickStretchOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStretchType", value); draw_info->stretch=(StretchType) option; break; } if (LocaleCompare(keyword, "stroke") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->stroke,exception); break; } if (LocaleCompare(keyword,"strokewidth") == 0) { draw_info->stroke_width=StringToLong(value); break; } if (LocaleCompare(keyword,"style") == 0) { option=ParseCommandOption(MagickStyleOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStyleType", value); draw_info->style=(StyleType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"text") == 0) { (void) ConcatenateString(&draw_info->primitive," '"); (void) ConcatenateString(&draw_info->primitive,value); (void) ConcatenateString(&draw_info->primitive,"'"); break; } if (LocaleCompare(keyword,"translate") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.tx=geometry_info.rho; affine.ty=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'U': case 'u': { if (LocaleCompare(keyword, "undercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->undercolor,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"weight") == 0) { draw_info->weight=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(text,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); CloneString(&draw_info->geometry,text); draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx; draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx; draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy; draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy; draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+ affine.tx; draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+ affine.ty; (void) DrawImage(msl_info->image[n],draw_info,exception); draw_info=DestroyDrawInfo(draw_info); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'E': case 'e': { if (LocaleCompare((const char *) tag,"edge") == 0) { Image *edge_image; /* Edge image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } edge_image=EdgeImage(msl_info->image[n],geometry_info.rho, msl_info->exception); if (edge_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=edge_image; break; } if (LocaleCompare((const char *) tag,"emboss") == 0) { Image *emboss_image; /* Emboss image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { geometry_info.sigma=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } emboss_image=EmbossImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,msl_info->exception); if (emboss_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=emboss_image; break; } if (LocaleCompare((const char *) tag,"enhance") == 0) { Image *enhance_image; /* Enhance image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } enhance_image=EnhanceImage(msl_info->image[n], msl_info->exception); if (enhance_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=enhance_image; break; } if (LocaleCompare((const char *) tag,"equalize") == 0) { /* Equalize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) EqualizeImage(msl_info->image[n], msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'F': case 'f': { if (LocaleCompare((const char *) tag, "flatten") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } /* no attributes here */ /* process the image */ { Image *newImage; newImage=MergeImageLayers(msl_info->image[n],FlattenLayer, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } if (LocaleCompare((const char *) tag,"flip") == 0) { Image *flip_image; /* Flip image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } flip_image=FlipImage(msl_info->image[n], msl_info->exception); if (flip_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=flip_image; break; } if (LocaleCompare((const char *) tag,"flop") == 0) { Image *flop_image; /* Flop image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } flop_image=FlopImage(msl_info->image[n], msl_info->exception); if (flop_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=flop_image; break; } if (LocaleCompare((const char *) tag,"frame") == 0) { FrameInfo frame_info; Image *frame_image; /* Frame image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } (void) ResetMagickMemory(&frame_info,0,sizeof(frame_info)); SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"compose") == 0) { option=ParseCommandOption(MagickComposeOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedComposeType", value); msl_info->image[n]->compose=(CompositeOperator) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &msl_info->image[n]->matte_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; frame_info.width=geometry.width; frame_info.height=geometry.height; frame_info.outer_bevel=geometry.x; frame_info.inner_bevel=geometry.y; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { frame_info.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"inner") == 0) { frame_info.inner_bevel=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"outer") == 0) { frame_info.outer_bevel=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { frame_info.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } frame_info.x=(ssize_t) frame_info.width; frame_info.y=(ssize_t) frame_info.height; frame_info.width=msl_info->image[n]->columns+2*frame_info.x; frame_info.height=msl_info->image[n]->rows+2*frame_info.y; frame_image=FrameImage(msl_info->image[n],&frame_info, msl_info->image[n]->compose,msl_info->exception); if (frame_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=frame_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'G': case 'g': { if (LocaleCompare((const char *) tag,"gamma") == 0) { char gamma[MagickPathExtent]; PixelInfo pixel; /* Gamma image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } channel=UndefinedChannel; pixel.red=0.0; pixel.green=0.0; pixel.blue=0.0; *gamma='\0'; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blue") == 0) { pixel.blue=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { (void) CopyMagickString(gamma,value,MagickPathExtent); break; } if (LocaleCompare(keyword,"green") == 0) { pixel.green=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"red") == 0) { pixel.red=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } if (*gamma == '\0') (void) FormatLocaleString(gamma,MagickPathExtent,"%g,%g,%g", (double) pixel.red,(double) pixel.green,(double) pixel.blue); (void) GammaImage(msl_info->image[n],strtod(gamma,(char **) NULL), msl_info->exception); break; } else if (LocaleCompare((const char *) tag,"get") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,(const char *) attributes[i]); (void) CopyMagickString(key,value,MagickPathExtent); switch (*keyword) { case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { (void) FormatLocaleString(value,MagickPathExtent,"%.20g", (double) msl_info->image[n]->rows); (void) SetImageProperty(msl_info->attributes[n],key,value, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { (void) FormatLocaleString(value,MagickPathExtent,"%.20g", (double) msl_info->image[n]->columns); (void) SetImageProperty(msl_info->attributes[n],key,value, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } break; } else if (LocaleCompare((const char *) tag, "group") == 0) { msl_info->number_groups++; msl_info->group_info=(MSLGroupInfo *) ResizeQuantumMemory( msl_info->group_info,msl_info->number_groups+1UL, sizeof(*msl_info->group_info)); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'I': case 'i': { if (LocaleCompare((const char *) tag,"image") == 0) { MSLPushImage(msl_info,(Image *) NULL); if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"color") == 0) { Image *next_image; (void) CopyMagickString(msl_info->image_info[n]->filename, "xc:",MagickPathExtent); (void) ConcatenateMagickString(msl_info->image_info[n]-> filename,value,MagickPathExtent); next_image=ReadImage(msl_info->image_info[n],exception); CatchException(exception); if (next_image == (Image *) NULL) continue; if (msl_info->image[n] == (Image *) NULL) msl_info->image[n]=next_image; else { register Image *p; /* Link image into image list. */ p=msl_info->image[n]; while (p->next != (Image *) NULL) p=GetNextImageInList(p); next_image->previous=p; p->next=next_image; } break; } (void) SetMSLAttributes(msl_info,keyword,value); break; } default: { (void) SetMSLAttributes(msl_info,keyword,value); break; } } } break; } if (LocaleCompare((const char *) tag,"implode") == 0) { Image *implode_image; /* Implode image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"amount") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } implode_image=ImplodeImage(msl_info->image[n],geometry_info.rho, msl_info->image[n]->interpolate,msl_info->exception); if (implode_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=implode_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'L': case 'l': { if (LocaleCompare((const char *) tag,"label") == 0) break; if (LocaleCompare((const char *) tag, "level") == 0) { double levelBlack = 0, levelGamma = 1, levelWhite = QuantumRange; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,(const char *) attributes[i]); (void) CopyMagickString(key,value,MagickPathExtent); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"black") == 0) { levelBlack = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { levelGamma = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"white") == 0) { levelWhite = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image */ LevelImage(msl_info->image[n],levelBlack,levelWhite,levelGamma, msl_info->exception); break; } } case 'M': case 'm': { if (LocaleCompare((const char *) tag,"magnify") == 0) { Image *magnify_image; /* Magnify image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } magnify_image=MagnifyImage(msl_info->image[n], msl_info->exception); if (magnify_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=magnify_image; break; } if (LocaleCompare((const char *) tag,"map") == 0) { Image *affinity_image; MagickBooleanType dither; QuantizeInfo *quantize_info; /* Map image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } affinity_image=NewImageList(); dither=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"dither") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); dither=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id", exception); if ((attribute != (const char *) NULL) && (LocaleCompare(attribute,value) == 0)) { affinity_image=CloneImage(msl_info->image[j],0,0, MagickFalse,exception); break; } } break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } quantize_info=AcquireQuantizeInfo(msl_info->image_info[n]); quantize_info->dither_method=dither != MagickFalse ? RiemersmaDitherMethod : NoDitherMethod; (void) RemapImages(quantize_info,msl_info->image[n], affinity_image,exception); quantize_info=DestroyQuantizeInfo(quantize_info); affinity_image=DestroyImage(affinity_image); break; } if (LocaleCompare((const char *) tag,"matte-floodfill") == 0) { double opacity; PixelInfo target; PaintMethod paint_method; /* Matte floodfill image. */ opacity=0.0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); paint_method=FloodfillMethod; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"bordercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &target,exception); paint_method=FillToBorderMethod; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fuzz") == 0) { msl_info->image[n]->fuzz=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { opacity=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); draw_info->fill.alpha=ClampToQuantum(opacity); channel_mask=SetImageChannelMask(msl_info->image[n],AlphaChannel); (void) FloodfillPaintImage(msl_info->image[n],draw_info,&target, geometry.x,geometry.y,paint_method == FloodfillMethod ? MagickFalse : MagickTrue,msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); draw_info=DestroyDrawInfo(draw_info); break; } if (LocaleCompare((const char *) tag,"median-filter") == 0) { Image *median_image; /* Median-filter image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } median_image=StatisticImage(msl_info->image[n],MedianStatistic, (size_t) geometry_info.rho,(size_t) geometry_info.sigma, msl_info->exception); if (median_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=median_image; break; } if (LocaleCompare((const char *) tag,"minify") == 0) { Image *minify_image; /* Minify image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } minify_image=MinifyImage(msl_info->image[n], msl_info->exception); if (minify_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=minify_image; break; } if (LocaleCompare((const char *) tag,"msl") == 0 ) break; if (LocaleCompare((const char *) tag,"modulate") == 0) { char modulate[MagickPathExtent]; /* Modulate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } geometry_info.rho=100.0; geometry_info.sigma=100.0; geometry_info.xi=100.0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blackness") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } if (LocaleCompare(keyword,"brightness") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"factor") == 0) { flags=ParseGeometry(value,&geometry_info); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"hue") == 0) { geometry_info.xi=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'L': case 'l': { if (LocaleCompare(keyword,"lightness") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"saturation") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"whiteness") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(modulate,MagickPathExtent,"%g,%g,%g", geometry_info.rho,geometry_info.sigma,geometry_info.xi); (void) ModulateImage(msl_info->image[n],modulate, msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'N': case 'n': { if (LocaleCompare((const char *) tag,"negate") == 0) { MagickBooleanType gray; /* Negate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } gray=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gray") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); gray=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } channel_mask=SetImageChannelMask(msl_info->image[n],channel); (void) NegateImage(msl_info->image[n],gray, msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); break; } if (LocaleCompare((const char *) tag,"normalize") == 0) { /* Normalize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) NormalizeImage(msl_info->image[n], msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'O': case 'o': { if (LocaleCompare((const char *) tag,"oil-paint") == 0) { Image *paint_image; /* Oil-paint image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } paint_image=OilPaintImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,msl_info->exception); if (paint_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=paint_image; break; } if (LocaleCompare((const char *) tag,"opaque") == 0) { PixelInfo fill_color, target; /* Opaque image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } (void) QueryColorCompliance("none",AllCompliance,&target, exception); (void) QueryColorCompliance("none",AllCompliance,&fill_color, exception); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &fill_color,exception); break; } if (LocaleCompare(keyword,"fuzz") == 0) { msl_info->image[n]->fuzz=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } channel_mask=SetImageChannelMask(msl_info->image[n],channel); (void) OpaquePaintImage(msl_info->image[n],&target,&fill_color, MagickFalse,msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'P': case 'p': { if (LocaleCompare((const char *) tag,"print") == 0) { if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'O': case 'o': { if (LocaleCompare(keyword,"output") == 0) { (void) FormatLocaleFile(stdout,"%s",value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } break; } if (LocaleCompare((const char *) tag, "profile") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { const char *name; const StringInfo *profile; Image *profile_image; ImageInfo *profile_info; keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); if (*keyword == '!') { /* Remove a profile from the image. */ (void) ProfileImage(msl_info->image[n],keyword, (const unsigned char *) NULL,0,exception); continue; } /* Associate a profile with the image. */ profile_info=CloneImageInfo(msl_info->image_info[n]); profile=GetImageProfile(msl_info->image[n],"iptc"); if (profile != (StringInfo *) NULL) profile_info->profile=(void *) CloneStringInfo(profile); profile_image=GetImageCache(profile_info,keyword,exception); profile_info=DestroyImageInfo(profile_info); if (profile_image == (Image *) NULL) { char name[MagickPathExtent], filename[MagickPathExtent]; register char *p; StringInfo *profile; (void) CopyMagickString(filename,keyword,MagickPathExtent); (void) CopyMagickString(name,keyword,MagickPathExtent); for (p=filename; *p != '\0'; p++) if ((*p == ':') && (IsPathDirectory(keyword) < 0) && (IsPathAccessible(keyword) == MagickFalse)) { register char *q; /* Look for profile name (e.g. name:profile). */ (void) CopyMagickString(name,filename,(size_t) (p-filename+1)); for (q=filename; *q != '\0'; q++) *q=(*++p); break; } profile=FileToStringInfo(filename,~0UL,exception); if (profile != (StringInfo *) NULL) { (void) ProfileImage(msl_info->image[n],name, GetStringInfoDatum(profile),(size_t) GetStringInfoLength(profile),exception); profile=DestroyStringInfo(profile); } continue; } ResetImageProfileIterator(profile_image); name=GetNextImageProfile(profile_image); while (name != (const char *) NULL) { profile=GetImageProfile(profile_image,name); if (profile != (StringInfo *) NULL) (void) ProfileImage(msl_info->image[n],name, GetStringInfoDatum(profile),(size_t) GetStringInfoLength(profile),exception); name=GetNextImageProfile(profile_image); } profile_image=DestroyImage(profile_image); } break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'Q': case 'q': { if (LocaleCompare((const char *) tag,"quantize") == 0) { QuantizeInfo quantize_info; /* Quantize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } GetQuantizeInfo(&quantize_info); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"colors") == 0) { quantize_info.number_colors=StringToLong(value); break; } if (LocaleCompare(keyword,"colorspace") == 0) { option=ParseCommandOption(MagickColorspaceOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError, "UnrecognizedColorspaceType",value); quantize_info.colorspace=(ColorspaceType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"dither") == 0) { option=ParseCommandOption(MagickDitherOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); quantize_info.dither_method=(DitherMethod) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'M': case 'm': { if (LocaleCompare(keyword,"measure") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); quantize_info.measure_error=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"treedepth") == 0) { quantize_info.tree_depth=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) QuantizeImage(&quantize_info,msl_info->image[n],exception); break; } if (LocaleCompare((const char *) tag,"query-font-metrics") == 0) { char text[MagickPathExtent]; MagickBooleanType status; TypeMetric metrics; /* Query font metrics. */ draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); angle=0.0; current=draw_info->affine; GetAffineMatrix(&affine); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"affine") == 0) { char *p; p=value; draw_info->affine.sx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.rx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ry=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.sy=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.tx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ty=StringToDouble(p,&p); break; } if (LocaleCompare(keyword,"align") == 0) { option=ParseCommandOption(MagickAlignOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedAlignType", value); draw_info->align=(AlignType) option; break; } if (LocaleCompare(keyword,"antialias") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); draw_info->stroke_antialias=(MagickBooleanType) option; draw_info->text_antialias=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"encoding") == 0) { CloneString(&draw_info->encoding,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->fill,exception); break; } if (LocaleCompare(keyword,"family") == 0) { CloneString(&draw_info->family,value); break; } if (LocaleCompare(keyword,"font") == 0) { CloneString(&draw_info->font,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); draw_info->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"pointsize") == 0) { draw_info->pointsize=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { angle=StringToDouble(value,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.sx=geometry_info.rho; affine.sy=geometry_info.sigma; break; } if (LocaleCompare(keyword,"skewX") == 0) { angle=StringToDouble(value,(char **) NULL); affine.ry=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"skewY") == 0) { angle=StringToDouble(value,(char **) NULL); affine.rx=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"stretch") == 0) { option=ParseCommandOption(MagickStretchOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStretchType", value); draw_info->stretch=(StretchType) option; break; } if (LocaleCompare(keyword, "stroke") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->stroke,exception); break; } if (LocaleCompare(keyword,"strokewidth") == 0) { draw_info->stroke_width=StringToLong(value); break; } if (LocaleCompare(keyword,"style") == 0) { option=ParseCommandOption(MagickStyleOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStyleType", value); draw_info->style=(StyleType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"text") == 0) { CloneString(&draw_info->text,value); break; } if (LocaleCompare(keyword,"translate") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.tx=geometry_info.rho; affine.ty=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'U': case 'u': { if (LocaleCompare(keyword, "undercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->undercolor,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"weight") == 0) { draw_info->weight=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(text,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); CloneString(&draw_info->geometry,text); draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx; draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx; draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy; draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy; draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+ affine.tx; draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+ affine.ty; status=GetTypeMetrics(msl_info->attributes[n],draw_info,&metrics, msl_info->exception); if (status != MagickFalse) { Image *image; image=msl_info->attributes[n]; FormatImageProperty(image,"msl:font-metrics.pixels_per_em.x", "%g",metrics.pixels_per_em.x); FormatImageProperty(image,"msl:font-metrics.pixels_per_em.y", "%g",metrics.pixels_per_em.y); FormatImageProperty(image,"msl:font-metrics.ascent","%g", metrics.ascent); FormatImageProperty(image,"msl:font-metrics.descent","%g", metrics.descent); FormatImageProperty(image,"msl:font-metrics.width","%g", metrics.width); FormatImageProperty(image,"msl:font-metrics.height","%g", metrics.height); FormatImageProperty(image,"msl:font-metrics.max_advance","%g", metrics.max_advance); FormatImageProperty(image,"msl:font-metrics.bounds.x1","%g", metrics.bounds.x1); FormatImageProperty(image,"msl:font-metrics.bounds.y1","%g", metrics.bounds.y1); FormatImageProperty(image,"msl:font-metrics.bounds.x2","%g", metrics.bounds.x2); FormatImageProperty(image,"msl:font-metrics.bounds.y2","%g", metrics.bounds.y2); FormatImageProperty(image,"msl:font-metrics.origin.x","%g", metrics.origin.x); FormatImageProperty(image,"msl:font-metrics.origin.y","%g", metrics.origin.y); } draw_info=DestroyDrawInfo(draw_info); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'R': case 'r': { if (LocaleCompare((const char *) tag,"raise") == 0) { MagickBooleanType raise; /* Raise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } raise=MagickFalse; SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"raise") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); raise=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) RaiseImage(msl_info->image[n],&geometry,raise, msl_info->exception); break; } if (LocaleCompare((const char *) tag,"read") == 0) { if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"filename") == 0) { Image *image; if (value == (char *) NULL) break; (void) CopyMagickString(msl_info->image_info[n]->filename, value,MagickPathExtent); image=ReadImage(msl_info->image_info[n],exception); CatchException(exception); if (image == (Image *) NULL) continue; AppendImageToList(&msl_info->image[n],image); break; } (void) SetMSLAttributes(msl_info,keyword,value); break; } default: { (void) SetMSLAttributes(msl_info,keyword,value); break; } } } break; } if (LocaleCompare((const char *) tag,"reduce-noise") == 0) { Image *paint_image; /* Reduce-noise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } paint_image=StatisticImage(msl_info->image[n],NonpeakStatistic, (size_t) geometry_info.rho,(size_t) geometry_info.sigma, msl_info->exception); if (paint_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=paint_image; break; } else if (LocaleCompare((const char *) tag,"repage") == 0) { /* init the values */ width=msl_info->image[n]->page.width; height=msl_info->image[n]->page.height; x=msl_info->image[n]->page.x; y=msl_info->image[n]->page.y; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { int flags; RectangleInfo geometry; flags=ParseAbsoluteGeometry(value,&geometry); if ((flags & WidthValue) != 0) { if ((flags & HeightValue) == 0) geometry.height=geometry.width; width=geometry.width; height=geometry.height; } if ((flags & AspectValue) != 0) { if ((flags & XValue) != 0) x+=geometry.x; if ((flags & YValue) != 0) y+=geometry.y; } else { if ((flags & XValue) != 0) { x=geometry.x; if ((width == 0) && (geometry.x > 0)) width=msl_info->image[n]->columns+geometry.x; } if ((flags & YValue) != 0) { y=geometry.y; if ((height == 0) && (geometry.y > 0)) height=msl_info->image[n]->rows+geometry.y; } } break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { height = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { width = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { x = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { y = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } msl_info->image[n]->page.width=width; msl_info->image[n]->page.height=height; msl_info->image[n]->page.x=x; msl_info->image[n]->page.y=y; break; } else if (LocaleCompare((const char *) tag,"resample") == 0) { double x_resolution, y_resolution; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; x_resolution=DefaultResolution; y_resolution=DefaultResolution; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { ssize_t flags; flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma*=geometry_info.rho; x_resolution=geometry_info.rho; y_resolution=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x-resolution") == 0) { x_resolution=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y-resolution") == 0) { y_resolution=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* Resample image. */ { double factor; Image *resample_image; factor=1.0; if (msl_info->image[n]->units == PixelsPerCentimeterResolution) factor=2.54; width=(size_t) (x_resolution*msl_info->image[n]->columns/ (factor*(msl_info->image[n]->resolution.x == 0.0 ? DefaultResolution : msl_info->image[n]->resolution.x))+0.5); height=(size_t) (y_resolution*msl_info->image[n]->rows/ (factor*(msl_info->image[n]->resolution.y == 0.0 ? DefaultResolution : msl_info->image[n]->resolution.y))+0.5); resample_image=ResizeImage(msl_info->image[n],width,height, msl_info->image[n]->filter,msl_info->exception); if (resample_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=resample_image; } break; } if (LocaleCompare((const char *) tag,"resize") == 0) { FilterType filter; Image *resize_image; /* Resize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } filter=UndefinedFilter; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"filter") == 0) { option=ParseCommandOption(MagickFilterOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); filter=(FilterType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseRegionGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToUnsignedLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } resize_image=ResizeImage(msl_info->image[n],geometry.width, geometry.height,filter,msl_info->exception); if (resize_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=resize_image; break; } if (LocaleCompare((const char *) tag,"roll") == 0) { Image *roll_image; /* Roll image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } roll_image=RollImage(msl_info->image[n],geometry.x,geometry.y, msl_info->exception); if (roll_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=roll_image; break; } else if (LocaleCompare((const char *) tag,"roll") == 0) { /* init the values */ width=msl_info->image[n]->columns; height=msl_info->image[n]->rows; x = y = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { (void) ParseMetaGeometry(value,&x,&y,&width,&height); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { x = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { y = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { Image *newImage; newImage=RollImage(msl_info->image[n], x, y, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; } break; } if (LocaleCompare((const char *) tag,"rotate") == 0) { Image *rotate_image; /* Rotate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"degrees") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } rotate_image=RotateImage(msl_info->image[n],geometry_info.rho, msl_info->exception); if (rotate_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=rotate_image; break; } else if (LocaleCompare((const char *) tag,"rotate") == 0) { /* init the values */ double degrees = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"degrees") == 0) { degrees = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { Image *newImage; newImage=RotateImage(msl_info->image[n], degrees, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; } break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'S': case 's': { if (LocaleCompare((const char *) tag,"sample") == 0) { Image *sample_image; /* Sample image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseRegionGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToUnsignedLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } sample_image=SampleImage(msl_info->image[n],geometry.width, geometry.height,msl_info->exception); if (sample_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=sample_image; break; } if (LocaleCompare((const char *) tag,"scale") == 0) { Image *scale_image; /* Scale image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseRegionGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToUnsignedLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } scale_image=ScaleImage(msl_info->image[n],geometry.width, geometry.height,msl_info->exception); if (scale_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=scale_image; break; } if (LocaleCompare((const char *) tag,"segment") == 0) { ColorspaceType colorspace; MagickBooleanType verbose; /* Segment image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } geometry_info.rho=1.0; geometry_info.sigma=1.5; colorspace=sRGBColorspace; verbose=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"cluster-threshold") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } if (LocaleCompare(keyword,"colorspace") == 0) { option=ParseCommandOption(MagickColorspaceOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError, "UnrecognizedColorspaceType",value); colorspace=(ColorspaceType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.5; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"smoothing-threshold") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SegmentImage(msl_info->image[n],colorspace,verbose, geometry_info.rho,geometry_info.sigma,exception); break; } else if (LocaleCompare((const char *) tag, "set") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"clip-mask") == 0) { for (j=0; j < msl_info->n; j++) { const char *property; property=GetImageProperty(msl_info->attributes[j],"id", exception); if (LocaleCompare(property,value) == 0) { SetImageMask(msl_info->image[n],ReadPixelMask, msl_info->image[j],exception); break; } } break; } if (LocaleCompare(keyword,"clip-path") == 0) { for (j=0; j < msl_info->n; j++) { const char *property; property=GetImageProperty(msl_info->attributes[j],"id", exception); if (LocaleCompare(property,value) == 0) { SetImageMask(msl_info->image[n],ReadPixelMask, msl_info->image[j],exception); break; } } break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,value); if (colorspace < 0) ThrowMSLException(OptionError,"UnrecognizedColorspace", value); (void) TransformImageColorspace(msl_info->image[n], (ColorspaceType) colorspace,exception); break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, exception); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { flags=ParseGeometry(value,&geometry_info); msl_info->image[n]->resolution.x=geometry_info.rho; msl_info->image[n]->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) msl_info->image[n]->resolution.y= msl_info->image[n]->resolution.x; break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, exception); break; } case 'O': case 'o': { if (LocaleCompare(keyword, "opacity") == 0) { ssize_t opac = OpaqueAlpha, len = (ssize_t) strlen( value ); if (value[len-1] == '%') { char tmp[100]; (void) CopyMagickString(tmp,value,len); opac = StringToLong( tmp ); opac = (int)(QuantumRange * ((float)opac/100)); } else opac = StringToLong( value ); (void) SetImageAlpha( msl_info->image[n], (Quantum) opac, exception); break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, msl_info->exception); break; } case 'P': case 'p': { if (LocaleCompare(keyword, "page") == 0) { char page[MagickPathExtent]; const char *image_option; MagickStatusType flags; RectangleInfo geometry; (void) ResetMagickMemory(&geometry,0,sizeof(geometry)); image_option=GetImageArtifact(msl_info->image[n],"page"); if (image_option != (const char *) NULL) flags=ParseAbsoluteGeometry(image_option,&geometry); flags=ParseAbsoluteGeometry(value,&geometry); (void) FormatLocaleString(page,MagickPathExtent,"%.20gx%.20g", (double) geometry.width,(double) geometry.height); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) (void) FormatLocaleString(page,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width, (double) geometry.height,(double) geometry.x,(double) geometry.y); (void) SetImageOption(msl_info->image_info[n],keyword,page); msl_info->image_info[n]->page=GetPageGeometry(page); break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, msl_info->exception); break; } default: { (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, msl_info->exception); break; } } } break; } if (LocaleCompare((const char *) tag,"shade") == 0) { Image *shade_image; MagickBooleanType gray; /* Shade image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } gray=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"azimuth") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"elevation") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } if (LocaleCompare(keyword,"gray") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); gray=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } shade_image=ShadeImage(msl_info->image[n],gray,geometry_info.rho, geometry_info.sigma,msl_info->exception); if (shade_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=shade_image; break; } if (LocaleCompare((const char *) tag,"shadow") == 0) { Image *shadow_image; /* Shear image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { geometry_info.rho=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { geometry_info.sigma=StringToLong(value); break; } break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry_info.xi=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry_info.psi=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } shadow_image=ShadowImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,(ssize_t) ceil(geometry_info.xi-0.5), (ssize_t) ceil(geometry_info.psi-0.5),msl_info->exception); if (shadow_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=shadow_image; break; } if (LocaleCompare((const char *) tag,"sharpen") == 0) { double radius = 0.0, sigma = 1.0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } /* NOTE: sharpen can have no attributes, since we use all the defaults! */ if (attributes != (const xmlChar **) NULL) { for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'R': case 'r': { if (LocaleCompare(keyword, "radius") == 0) { radius = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { sigma = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } } /* sharpen image. */ { Image *newImage; newImage=SharpenImage(msl_info->image[n],radius,sigma, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } else if (LocaleCompare((const char *) tag,"shave") == 0) { /* init the values */ width = height = 0; x = y = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { (void) ParseMetaGeometry(value,&x,&y,&width,&height); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { height = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { width = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { Image *newImage; RectangleInfo rectInfo; rectInfo.height = height; rectInfo.width = width; rectInfo.x = x; rectInfo.y = y; newImage=ShaveImage(msl_info->image[n], &rectInfo, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; } break; } if (LocaleCompare((const char *) tag,"shear") == 0) { Image *shear_image; /* Shear image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &msl_info->image[n]->background_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry_info.sigma=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } shear_image=ShearImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,msl_info->exception); if (shear_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=shear_image; break; } if (LocaleCompare((const char *) tag,"signature") == 0) { /* Signature image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SignatureImage(msl_info->image[n],exception); break; } if (LocaleCompare((const char *) tag,"solarize") == 0) { /* Solarize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } geometry_info.rho=QuantumRange/2.0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"threshold") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SolarizeImage(msl_info->image[n],geometry_info.rho, msl_info->exception); break; } if (LocaleCompare((const char *) tag,"spread") == 0) { Image *spread_image; /* Spread image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } spread_image=SpreadImage(msl_info->image[n], msl_info->image[n]->interpolate,geometry_info.rho, msl_info->exception); if (spread_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=spread_image; break; } else if (LocaleCompare((const char *) tag,"stegano") == 0) { Image * watermark = (Image*) NULL; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) { for (j=0; j<msl_info->n;j++) { const char * theAttr = GetImageProperty(msl_info->attributes[j], "id", exception); if (theAttr && LocaleCompare(theAttr, value) == 0) { watermark = msl_info->image[j]; break; } } break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ if ( watermark != (Image*) NULL ) { Image *newImage; newImage=SteganoImage(msl_info->image[n], watermark, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } else ThrowMSLException(OptionError,"MissingWatermarkImage",keyword); } else if (LocaleCompare((const char *) tag,"stereo") == 0) { Image * stereoImage = (Image*) NULL; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) { for (j=0; j<msl_info->n;j++) { const char * theAttr = GetImageProperty(msl_info->attributes[j], "id", exception); if (theAttr && LocaleCompare(theAttr, value) == 0) { stereoImage = msl_info->image[j]; break; } } break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ if ( stereoImage != (Image*) NULL ) { Image *newImage; newImage=StereoImage(msl_info->image[n], stereoImage, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } else ThrowMSLException(OptionError,"Missing stereo image",keyword); } if (LocaleCompare((const char *) tag,"strip") == 0) { /* Strip image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } (void) StripImage(msl_info->image[n],msl_info->exception); break; } if (LocaleCompare((const char *) tag,"swap") == 0) { Image *p, *q, *swap; ssize_t index, swap_index; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } index=(-1); swap_index=(-2); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"indexes") == 0) { flags=ParseGeometry(value,&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) == 0) swap_index=(ssize_t) geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } /* Swap images. */ p=GetImageFromList(msl_info->image[n],index); q=GetImageFromList(msl_info->image[n],swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { ThrowMSLException(OptionError,"NoSuchImage",(const char *) tag); break; } swap=CloneImage(p,0,0,MagickTrue,msl_info->exception); ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue, msl_info->exception)); ReplaceImageInList(&q,swap); msl_info->image[n]=GetFirstImageInList(q); break; } if (LocaleCompare((const char *) tag,"swirl") == 0) { Image *swirl_image; /* Swirl image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"degrees") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } swirl_image=SwirlImage(msl_info->image[n],geometry_info.rho, msl_info->image[n]->interpolate,msl_info->exception); if (swirl_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=swirl_image; break; } if (LocaleCompare((const char *) tag,"sync") == 0) { /* Sync image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SyncImage(msl_info->image[n],exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'T': case 't': { if (LocaleCompare((const char *) tag,"map") == 0) { Image *texture_image; /* Texture image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } texture_image=NewImageList(); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id", exception); if ((attribute != (const char *) NULL) && (LocaleCompare(attribute,value) == 0)) { texture_image=CloneImage(msl_info->image[j],0,0, MagickFalse,exception); break; } } break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) TextureImage(msl_info->image[n],texture_image,exception); texture_image=DestroyImage(texture_image); break; } else if (LocaleCompare((const char *) tag,"threshold") == 0) { /* init the values */ double threshold = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'T': case 't': { if (LocaleCompare(keyword,"threshold") == 0) { threshold = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { BilevelImage(msl_info->image[n],threshold,exception); break; } } else if (LocaleCompare((const char *) tag, "transparent") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"color") == 0) { PixelInfo target; (void) QueryColorCompliance(value,AllCompliance,&target, exception); (void) TransparentPaintImage(msl_info->image[n],&target, TransparentAlpha,MagickFalse,msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } break; } else if (LocaleCompare((const char *) tag, "trim") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } /* no attributes here */ /* process the image */ { Image *newImage; RectangleInfo rectInfo; /* all zeros on a crop == trim edges! */ rectInfo.height = rectInfo.width = 0; rectInfo.x = rectInfo.y = 0; newImage=CropImage(msl_info->image[n],&rectInfo, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'W': case 'w': { if (LocaleCompare((const char *) tag,"write") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"filename") == 0) { (void) CopyMagickString(msl_info->image[n]->filename,value, MagickPathExtent); break; } (void) SetMSLAttributes(msl_info,keyword,value); } default: { (void) SetMSLAttributes(msl_info,keyword,value); break; } } } /* process */ { *msl_info->image_info[n]->magick='\0'; (void) WriteImage(msl_info->image_info[n], msl_info->image[n], msl_info->exception); break; } } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } default: { ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); break; } } if (value != (char *) NULL) value=DestroyString(value); (void) DestroyExceptionInfo(exception); (void) LogMagickEvent(CoderEvent,GetMagickModule()," )"); } static void MSLEndElement(void *context,const xmlChar *tag) { ssize_t n; MSLInfo *msl_info; /* Called when the end of an element has been detected. */ (void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.endElement(%s)", tag); msl_info=(MSLInfo *) context; n=msl_info->n; switch (*tag) { case 'C': case 'c': { if (LocaleCompare((const char *) tag,"comment") == 0 ) { (void) DeleteImageProperty(msl_info->image[n],"comment"); if (msl_info->content == (char *) NULL) break; StripString(msl_info->content); (void) SetImageProperty(msl_info->image[n],"comment", msl_info->content,msl_info->exception); break; } break; } case 'G': case 'g': { if (LocaleCompare((const char *) tag, "group") == 0 ) { if (msl_info->group_info[msl_info->number_groups-1].numImages > 0 ) { ssize_t i = (ssize_t) (msl_info->group_info[msl_info->number_groups-1].numImages); while ( i-- ) { if (msl_info->image[msl_info->n] != (Image *) NULL) msl_info->image[msl_info->n]=DestroyImage( msl_info->image[msl_info->n]); msl_info->attributes[msl_info->n]=DestroyImage( msl_info->attributes[msl_info->n]); msl_info->image_info[msl_info->n]=DestroyImageInfo( msl_info->image_info[msl_info->n]); msl_info->n--; } } msl_info->number_groups--; } break; } case 'I': case 'i': { if (LocaleCompare((const char *) tag, "image") == 0) MSLPopImage(msl_info); break; } case 'L': case 'l': { if (LocaleCompare((const char *) tag,"label") == 0 ) { (void) DeleteImageProperty(msl_info->image[n],"label"); if (msl_info->content == (char *) NULL) break; StripString(msl_info->content); (void) SetImageProperty(msl_info->image[n],"label", msl_info->content,msl_info->exception); break; } break; } case 'M': case 'm': { if (LocaleCompare((const char *) tag, "msl") == 0 ) { /* This our base element. at the moment we don't do anything special but someday we might! */ } break; } default: break; } if (msl_info->content != (char *) NULL) msl_info->content=DestroyString(msl_info->content); } static void MSLCharacters(void *context,const xmlChar *c,int length) { MSLInfo *msl_info; register char *p; register ssize_t i; /* Receiving some characters from the parser. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.characters(%s,%d)",c,length); msl_info=(MSLInfo *) context; if (msl_info->content != (char *) NULL) msl_info->content=(char *) ResizeQuantumMemory(msl_info->content, strlen(msl_info->content)+length+MagickPathExtent, sizeof(*msl_info->content)); else { msl_info->content=(char *) NULL; if (~(size_t) length >= (MagickPathExtent-1)) msl_info->content=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*msl_info->content)); if (msl_info->content != (char *) NULL) *msl_info->content='\0'; } if (msl_info->content == (char *) NULL) return; p=msl_info->content+strlen(msl_info->content); for (i=0; i < length; i++) *p++=c[i]; *p='\0'; } static void MSLReference(void *context,const xmlChar *name) { MSLInfo *msl_info; xmlParserCtxtPtr parser; /* Called when an entity reference is detected. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.reference(%s)",name); msl_info=(MSLInfo *) context; parser=msl_info->parser; if (*name == '#') (void) xmlAddChild(parser->node,xmlNewCharRef(msl_info->document,name)); else (void) xmlAddChild(parser->node,xmlNewReference(msl_info->document,name)); } static void MSLIgnorableWhitespace(void *context,const xmlChar *c,int length) { MSLInfo *msl_info; /* Receiving some ignorable whitespaces from the parser. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.ignorableWhitespace(%.30s, %d)",c,length); msl_info=(MSLInfo *) context; (void) msl_info; } static void MSLProcessingInstructions(void *context,const xmlChar *target, const xmlChar *data) { MSLInfo *msl_info; /* A processing instruction has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.processingInstruction(%s, %s)", target,data); msl_info=(MSLInfo *) context; (void) msl_info; } static void MSLComment(void *context,const xmlChar *value) { MSLInfo *msl_info; /* A comment has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.comment(%s)",value); msl_info=(MSLInfo *) context; (void) msl_info; } static void MSLWarning(void *context,const char *format,...) { char *message, reason[MagickPathExtent]; MSLInfo *msl_info; va_list operands; /** Display and format a warning messages, gives file, line, position and extra parameters. */ va_start(operands,format); (void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.warning: "); (void) LogMagickEvent(CoderEvent,GetMagickModule(),format,operands); msl_info=(MSLInfo *) context; (void) msl_info; #if !defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsprintf(reason,format,operands); #else (void) vsnprintf(reason,MagickPathExtent,format,operands); #endif message=GetExceptionMessage(errno); ThrowMSLException(CoderError,reason,message); message=DestroyString(message); va_end(operands); } static void MSLError(void *context,const char *format,...) { char reason[MagickPathExtent]; MSLInfo *msl_info; va_list operands; /* Display and format a error formats, gives file, line, position and extra parameters. */ va_start(operands,format); (void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.error: "); (void) LogMagickEvent(CoderEvent,GetMagickModule(),format,operands); msl_info=(MSLInfo *) context; (void) msl_info; #if !defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsprintf(reason,format,operands); #else (void) vsnprintf(reason,MagickPathExtent,format,operands); #endif ThrowMSLException(DelegateFatalError,reason,"SAX error"); va_end(operands); } static void MSLCDataBlock(void *context,const xmlChar *value,int length) { MSLInfo *msl_info; xmlNodePtr child; xmlParserCtxtPtr parser; /* Called when a pcdata block has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.pcdata(%s, %d)",value,length); msl_info=(MSLInfo *) context; (void) msl_info; parser=msl_info->parser; child=xmlGetLastChild(parser->node); if ((child != (xmlNodePtr) NULL) && (child->type == XML_CDATA_SECTION_NODE)) { xmlTextConcat(child,value,length); return; } (void) xmlAddChild(parser->node,xmlNewCDataBlock(parser->myDoc,value,length)); } static void MSLExternalSubset(void *context,const xmlChar *name, const xmlChar *external_id,const xmlChar *system_id) { MSLInfo *msl_info; xmlParserCtxt parser_context; xmlParserCtxtPtr parser; xmlParserInputPtr input; /* Does this document has an external subset? */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.externalSubset(%s %s %s)",name, (external_id != (const xmlChar *) NULL ? (const char *) external_id : " "), (system_id != (const xmlChar *) NULL ? (const char *) system_id : " ")); msl_info=(MSLInfo *) context; (void) msl_info; parser=msl_info->parser; if (((external_id == NULL) && (system_id == NULL)) || ((parser->validate == 0) || (parser->wellFormed == 0) || (msl_info->document == 0))) return; input=MSLResolveEntity(context,external_id,system_id); if (input == NULL) return; (void) xmlNewDtd(msl_info->document,name,external_id,system_id); parser_context=(*parser); parser->inputTab=(xmlParserInputPtr *) xmlMalloc(5*sizeof(*parser->inputTab)); if (parser->inputTab == (xmlParserInputPtr *) NULL) { parser->errNo=XML_ERR_NO_MEMORY; parser->input=parser_context.input; parser->inputNr=parser_context.inputNr; parser->inputMax=parser_context.inputMax; parser->inputTab=parser_context.inputTab; return; } parser->inputNr=0; parser->inputMax=5; parser->input=NULL; xmlPushInput(parser,input); (void) xmlSwitchEncoding(parser,xmlDetectCharEncoding(parser->input->cur,4)); if (input->filename == (char *) NULL) input->filename=(char *) xmlStrdup(system_id); input->line=1; input->col=1; input->base=parser->input->cur; input->cur=parser->input->cur; input->free=NULL; xmlParseExternalSubset(parser,external_id,system_id); while (parser->inputNr > 1) (void) xmlPopInput(parser); xmlFreeInputStream(parser->input); xmlFree(parser->inputTab); parser->input=parser_context.input; parser->inputNr=parser_context.inputNr; parser->inputMax=parser_context.inputMax; parser->inputTab=parser_context.inputTab; } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickBooleanType ProcessMSLScript(const ImageInfo *image_info, Image **image,ExceptionInfo *exception) { char message[MagickPathExtent]; Image *msl_image; int status; ssize_t n; MSLInfo msl_info; xmlSAXHandler sax_modules; xmlSAXHandlerPtr sax_handler; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(image != (Image **) NULL); msl_image=AcquireImage(image_info,exception); status=OpenBlob(image_info,msl_image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", msl_image->filename); msl_image=DestroyImageList(msl_image); return(MagickFalse); } msl_image->columns=1; msl_image->rows=1; /* Parse MSL file. */ (void) ResetMagickMemory(&msl_info,0,sizeof(msl_info)); msl_info.exception=exception; msl_info.image_info=(ImageInfo **) AcquireMagickMemory( sizeof(*msl_info.image_info)); msl_info.draw_info=(DrawInfo **) AcquireMagickMemory( sizeof(*msl_info.draw_info)); /* top of the stack is the MSL file itself */ msl_info.image=(Image **) AcquireMagickMemory(sizeof(*msl_info.image)); msl_info.attributes=(Image **) AcquireMagickMemory( sizeof(*msl_info.attributes)); msl_info.group_info=(MSLGroupInfo *) AcquireMagickMemory( sizeof(*msl_info.group_info)); if ((msl_info.image_info == (ImageInfo **) NULL) || (msl_info.image == (Image **) NULL) || (msl_info.attributes == (Image **) NULL) || (msl_info.group_info == (MSLGroupInfo *) NULL)) ThrowFatalException(ResourceLimitFatalError,"UnableToInterpretMSLImage"); *msl_info.image_info=CloneImageInfo(image_info); *msl_info.draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); *msl_info.attributes=AcquireImage(image_info,exception); msl_info.group_info[0].numImages=0; /* the first slot is used to point to the MSL file image */ *msl_info.image=msl_image; if (*image != (Image *) NULL) MSLPushImage(&msl_info,*image); (void) xmlSubstituteEntitiesDefault(1); (void) ResetMagickMemory(&sax_modules,0,sizeof(sax_modules)); sax_modules.internalSubset=MSLInternalSubset; sax_modules.isStandalone=MSLIsStandalone; sax_modules.hasInternalSubset=MSLHasInternalSubset; sax_modules.hasExternalSubset=MSLHasExternalSubset; sax_modules.resolveEntity=MSLResolveEntity; sax_modules.getEntity=MSLGetEntity; sax_modules.entityDecl=MSLEntityDeclaration; sax_modules.notationDecl=MSLNotationDeclaration; sax_modules.attributeDecl=MSLAttributeDeclaration; sax_modules.elementDecl=MSLElementDeclaration; sax_modules.unparsedEntityDecl=MSLUnparsedEntityDeclaration; sax_modules.setDocumentLocator=MSLSetDocumentLocator; sax_modules.startDocument=MSLStartDocument; sax_modules.endDocument=MSLEndDocument; sax_modules.startElement=MSLStartElement; sax_modules.endElement=MSLEndElement; sax_modules.reference=MSLReference; sax_modules.characters=MSLCharacters; sax_modules.ignorableWhitespace=MSLIgnorableWhitespace; sax_modules.processingInstruction=MSLProcessingInstructions; sax_modules.comment=MSLComment; sax_modules.warning=MSLWarning; sax_modules.error=MSLError; sax_modules.fatalError=MSLError; sax_modules.getParameterEntity=MSLGetParameterEntity; sax_modules.cdataBlock=MSLCDataBlock; sax_modules.externalSubset=MSLExternalSubset; sax_handler=(&sax_modules); msl_info.parser=xmlCreatePushParserCtxt(sax_handler,&msl_info,(char *) NULL,0, msl_image->filename); while (ReadBlobString(msl_image,message) != (char *) NULL) { n=(ssize_t) strlen(message); if (n == 0) continue; status=xmlParseChunk(msl_info.parser,message,(int) n,MagickFalse); if (status != 0) break; (void) xmlParseChunk(msl_info.parser," ",1,MagickFalse); if (msl_info.exception->severity >= ErrorException) break; } if (msl_info.exception->severity == UndefinedException) (void) xmlParseChunk(msl_info.parser," ",1,MagickTrue); xmlFreeParserCtxt(msl_info.parser); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX"); msl_info.group_info=(MSLGroupInfo *) RelinquishMagickMemory( msl_info.group_info); if (*image == (Image *) NULL) *image=(*msl_info.image); if (msl_info.exception->severity != UndefinedException) return(MagickFalse); return(MagickTrue); } static Image *ReadMSLImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=(Image *) NULL; (void) ProcessMSLScript(image_info,&image,exception); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M S L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterMSLImage() adds attributes for the MSL image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterMSLImage method is: % % size_t RegisterMSLImage(void) % */ ModuleExport size_t RegisterMSLImage(void) { MagickInfo *entry; #if defined(MAGICKCORE_XML_DELEGATE) xmlInitParser(); #endif entry=AcquireMagickInfo("MSL","MSL","Magick Scripting Language"); #if defined(MAGICKCORE_XML_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMSLImage; entry->encoder=(EncodeImageHandler *) WriteMSLImage; #endif entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } #if defined(MAGICKCORE_XML_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t M S L A t t r i b u t e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetMSLAttributes() ... % % The format of the SetMSLAttributes method is: % % MagickBooleanType SetMSLAttributes(MSLInfo *msl_info, % const char *keyword,const char *value) % % A description of each parameter follows: % % o msl_info: the MSL info. % % o keyword: the keyword. % % o value: the value. % */ static MagickBooleanType SetMSLAttributes(MSLInfo *msl_info,const char *keyword, const char *value) { Image *attributes; DrawInfo *draw_info; ExceptionInfo *exception; GeometryInfo geometry_info; Image *image; ImageInfo *image_info; int flags; ssize_t n; assert(msl_info != (MSLInfo *) NULL); if (keyword == (const char *) NULL) return(MagickTrue); if (value == (const char *) NULL) return(MagickTrue); exception=msl_info->exception; n=msl_info->n; attributes=msl_info->attributes[n]; image_info=msl_info->image_info[n]; draw_info=msl_info->draw_info[n]; image=msl_info->image[n]; switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"adjoin") == 0) { ssize_t adjoin; adjoin=ParseCommandOption(MagickBooleanOptions,MagickFalse,value); if (adjoin < 0) ThrowMSLException(OptionError,"UnrecognizedType",value); image_info->adjoin=(MagickBooleanType) adjoin; break; } if (LocaleCompare(keyword,"alpha") == 0) { ssize_t alpha; alpha=ParseCommandOption(MagickAlphaChannelOptions,MagickFalse,value); if (alpha < 0) ThrowMSLException(OptionError,"UnrecognizedType",value); if (image != (Image *) NULL) (void) SetImageAlphaChannel(image,(AlphaChannelOption) alpha, exception); break; } if (LocaleCompare(keyword,"antialias") == 0) { ssize_t antialias; antialias=ParseCommandOption(MagickBooleanOptions,MagickFalse,value); if (antialias < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType",value); image_info->antialias=(MagickBooleanType) antialias; break; } if (LocaleCompare(keyword,"area-limit") == 0) { MagickSizeType limit; limit=MagickResourceInfinity; if (LocaleCompare(value,"unlimited") != 0) limit=(MagickSizeType) StringToDoubleInterval(value,100.0); (void) SetMagickResourceLimit(AreaResource,limit); break; } if (LocaleCompare(keyword,"attenuate") == 0) { (void) SetImageOption(image_info,keyword,value); break; } if (LocaleCompare(keyword,"authenticate") == 0) { (void) CloneString(&image_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'B': case 'b': { if (LocaleCompare(keyword,"background") == 0) { (void) QueryColorCompliance(value,AllCompliance, &image_info->background_color,exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { if (image == (Image *) NULL) break; flags=ParseGeometry(value,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"bordercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &image_info->border_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { (void) CloneString(&image_info->density,value); (void) CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorCompliance(value,AllCompliance,&draw_info->fill, exception); (void) SetImageOption(image_info,keyword,value); break; } if (LocaleCompare(keyword,"filename") == 0) { (void) CopyMagickString(image_info->filename,value,MagickPathExtent); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gravity") == 0) { ssize_t gravity; gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,value); if (gravity < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType",value); (void) SetImageOption(image_info,keyword,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"id") == 0) { (void) SetImageProperty(attributes,keyword,value,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'M': case 'm': { if (LocaleCompare(keyword,"magick") == 0) { (void) CopyMagickString(image_info->magick,value,MagickPathExtent); break; } if (LocaleCompare(keyword,"mattecolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &image_info->matte_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"pointsize") == 0) { image_info->pointsize=StringToDouble(value,(char **) NULL); draw_info->pointsize=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Q': case 'q': { if (LocaleCompare(keyword,"quality") == 0) { image_info->quality=StringToLong(value); if (image == (Image *) NULL) break; image->quality=StringToLong(value); break; } break; } case 'S': case 's': { if (LocaleCompare(keyword,"size") == 0) { (void) CloneString(&image_info->size,value); break; } if (LocaleCompare(keyword,"stroke") == 0) { (void) QueryColorCompliance(value,AllCompliance,&draw_info->stroke, exception); (void) SetImageOption(image_info,keyword,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } return(MagickTrue); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M S L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterMSLImage() removes format registrations made by the % MSL module from the list of supported formats. % % The format of the UnregisterMSLImage method is: % % UnregisterMSLImage(void) % */ ModuleExport void UnregisterMSLImage(void) { (void) UnregisterMagickInfo("MSL"); #if defined(MAGICKCORE_XML_DELEGATE) xmlCleanupParser(); #endif } #if defined(MAGICKCORE_XML_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M S L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMSLImage() writes an image to a file in MVG image format. % % The format of the WriteMSLImage method is: % % MagickBooleanType WriteMSLImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteMSLImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { Image *msl_image; MagickBooleanType status; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); msl_image=CloneImage(image,0,0,MagickTrue,exception); status=ProcessMSLScript(image_info,&msl_image,exception); if (msl_image != (Image *) NULL) msl_image=DestroyImage(msl_image); return(status); } #endif
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2608_1
crossvul-cpp_data_bad_1161_0
/* * IPv6 over IPv4 tunnel device - Simple Internet Transition (SIT) * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Changes: * Roger Venning <r.venning@telstra.com>: 6to4 support * Nate Thompson <nate@thebog.net>: 6to4 support * Fred Templin <fred.l.templin@boeing.com>: isatap support */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/capability.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/in6.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/icmp.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/init.h> #include <linux/netfilter_ipv4.h> #include <linux/if_ether.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/protocol.h> #include <net/transp_v6.h> #include <net/ip6_fib.h> #include <net/ip6_route.h> #include <net/ndisc.h> #include <net/addrconf.h> #include <net/ip.h> #include <net/udp.h> #include <net/icmp.h> #include <net/ip_tunnels.h> #include <net/inet_ecn.h> #include <net/xfrm.h> #include <net/dsfield.h> #include <net/net_namespace.h> #include <net/netns/generic.h> /* This version of net/ipv6/sit.c is cloned of net/ipv4/ip_gre.c For comments look at net/ipv4/ip_gre.c --ANK */ #define IP6_SIT_HASH_SIZE 16 #define HASH(addr) (((__force u32)addr^((__force u32)addr>>4))&0xF) static bool log_ecn_error = true; module_param(log_ecn_error, bool, 0644); MODULE_PARM_DESC(log_ecn_error, "Log packets received with corrupted ECN"); static int ipip6_tunnel_init(struct net_device *dev); static void ipip6_tunnel_setup(struct net_device *dev); static void ipip6_dev_free(struct net_device *dev); static bool check_6rd(struct ip_tunnel *tunnel, const struct in6_addr *v6dst, __be32 *v4dst); static struct rtnl_link_ops sit_link_ops __read_mostly; static unsigned int sit_net_id __read_mostly; struct sit_net { struct ip_tunnel __rcu *tunnels_r_l[IP6_SIT_HASH_SIZE]; struct ip_tunnel __rcu *tunnels_r[IP6_SIT_HASH_SIZE]; struct ip_tunnel __rcu *tunnels_l[IP6_SIT_HASH_SIZE]; struct ip_tunnel __rcu *tunnels_wc[1]; struct ip_tunnel __rcu **tunnels[4]; struct net_device *fb_tunnel_dev; }; /* * Must be invoked with rcu_read_lock */ static struct ip_tunnel *ipip6_tunnel_lookup(struct net *net, struct net_device *dev, __be32 remote, __be32 local, int sifindex) { unsigned int h0 = HASH(remote); unsigned int h1 = HASH(local); struct ip_tunnel *t; struct sit_net *sitn = net_generic(net, sit_net_id); int ifindex = dev ? dev->ifindex : 0; for_each_ip_tunnel_rcu(t, sitn->tunnels_r_l[h0 ^ h1]) { if (local == t->parms.iph.saddr && remote == t->parms.iph.daddr && (!dev || !t->parms.link || ifindex == t->parms.link || sifindex == t->parms.link) && (t->dev->flags & IFF_UP)) return t; } for_each_ip_tunnel_rcu(t, sitn->tunnels_r[h0]) { if (remote == t->parms.iph.daddr && (!dev || !t->parms.link || ifindex == t->parms.link || sifindex == t->parms.link) && (t->dev->flags & IFF_UP)) return t; } for_each_ip_tunnel_rcu(t, sitn->tunnels_l[h1]) { if (local == t->parms.iph.saddr && (!dev || !t->parms.link || ifindex == t->parms.link || sifindex == t->parms.link) && (t->dev->flags & IFF_UP)) return t; } t = rcu_dereference(sitn->tunnels_wc[0]); if (t && (t->dev->flags & IFF_UP)) return t; return NULL; } static struct ip_tunnel __rcu **__ipip6_bucket(struct sit_net *sitn, struct ip_tunnel_parm *parms) { __be32 remote = parms->iph.daddr; __be32 local = parms->iph.saddr; unsigned int h = 0; int prio = 0; if (remote) { prio |= 2; h ^= HASH(remote); } if (local) { prio |= 1; h ^= HASH(local); } return &sitn->tunnels[prio][h]; } static inline struct ip_tunnel __rcu **ipip6_bucket(struct sit_net *sitn, struct ip_tunnel *t) { return __ipip6_bucket(sitn, &t->parms); } static void ipip6_tunnel_unlink(struct sit_net *sitn, struct ip_tunnel *t) { struct ip_tunnel __rcu **tp; struct ip_tunnel *iter; for (tp = ipip6_bucket(sitn, t); (iter = rtnl_dereference(*tp)) != NULL; tp = &iter->next) { if (t == iter) { rcu_assign_pointer(*tp, t->next); break; } } } static void ipip6_tunnel_link(struct sit_net *sitn, struct ip_tunnel *t) { struct ip_tunnel __rcu **tp = ipip6_bucket(sitn, t); rcu_assign_pointer(t->next, rtnl_dereference(*tp)); rcu_assign_pointer(*tp, t); } static void ipip6_tunnel_clone_6rd(struct net_device *dev, struct sit_net *sitn) { #ifdef CONFIG_IPV6_SIT_6RD struct ip_tunnel *t = netdev_priv(dev); if (dev == sitn->fb_tunnel_dev || !sitn->fb_tunnel_dev) { ipv6_addr_set(&t->ip6rd.prefix, htonl(0x20020000), 0, 0, 0); t->ip6rd.relay_prefix = 0; t->ip6rd.prefixlen = 16; t->ip6rd.relay_prefixlen = 0; } else { struct ip_tunnel *t0 = netdev_priv(sitn->fb_tunnel_dev); memcpy(&t->ip6rd, &t0->ip6rd, sizeof(t->ip6rd)); } #endif } static int ipip6_tunnel_create(struct net_device *dev) { struct ip_tunnel *t = netdev_priv(dev); struct net *net = dev_net(dev); struct sit_net *sitn = net_generic(net, sit_net_id); int err; memcpy(dev->dev_addr, &t->parms.iph.saddr, 4); memcpy(dev->broadcast, &t->parms.iph.daddr, 4); if ((__force u16)t->parms.i_flags & SIT_ISATAP) dev->priv_flags |= IFF_ISATAP; dev->rtnl_link_ops = &sit_link_ops; err = register_netdevice(dev); if (err < 0) goto out; ipip6_tunnel_clone_6rd(dev, sitn); dev_hold(dev); ipip6_tunnel_link(sitn, t); return 0; out: return err; } static struct ip_tunnel *ipip6_tunnel_locate(struct net *net, struct ip_tunnel_parm *parms, int create) { __be32 remote = parms->iph.daddr; __be32 local = parms->iph.saddr; struct ip_tunnel *t, *nt; struct ip_tunnel __rcu **tp; struct net_device *dev; char name[IFNAMSIZ]; struct sit_net *sitn = net_generic(net, sit_net_id); for (tp = __ipip6_bucket(sitn, parms); (t = rtnl_dereference(*tp)) != NULL; tp = &t->next) { if (local == t->parms.iph.saddr && remote == t->parms.iph.daddr && parms->link == t->parms.link) { if (create) return NULL; else return t; } } if (!create) goto failed; if (parms->name[0]) { if (!dev_valid_name(parms->name)) goto failed; strlcpy(name, parms->name, IFNAMSIZ); } else { strcpy(name, "sit%d"); } dev = alloc_netdev(sizeof(*t), name, NET_NAME_UNKNOWN, ipip6_tunnel_setup); if (!dev) return NULL; dev_net_set(dev, net); nt = netdev_priv(dev); nt->parms = *parms; if (ipip6_tunnel_create(dev) < 0) goto failed_free; return nt; failed_free: free_netdev(dev); failed: return NULL; } #define for_each_prl_rcu(start) \ for (prl = rcu_dereference(start); \ prl; \ prl = rcu_dereference(prl->next)) static struct ip_tunnel_prl_entry * __ipip6_tunnel_locate_prl(struct ip_tunnel *t, __be32 addr) { struct ip_tunnel_prl_entry *prl; for_each_prl_rcu(t->prl) if (prl->addr == addr) break; return prl; } static int ipip6_tunnel_get_prl(struct ip_tunnel *t, struct ip_tunnel_prl __user *a) { struct ip_tunnel_prl kprl, *kp; struct ip_tunnel_prl_entry *prl; unsigned int cmax, c = 0, ca, len; int ret = 0; if (copy_from_user(&kprl, a, sizeof(kprl))) return -EFAULT; cmax = kprl.datalen / sizeof(kprl); if (cmax > 1 && kprl.addr != htonl(INADDR_ANY)) cmax = 1; /* For simple GET or for root users, * we try harder to allocate. */ kp = (cmax <= 1 || capable(CAP_NET_ADMIN)) ? kcalloc(cmax, sizeof(*kp), GFP_KERNEL | __GFP_NOWARN) : NULL; rcu_read_lock(); ca = t->prl_count < cmax ? t->prl_count : cmax; if (!kp) { /* We don't try hard to allocate much memory for * non-root users. * For root users, retry allocating enough memory for * the answer. */ kp = kcalloc(ca, sizeof(*kp), GFP_ATOMIC); if (!kp) { ret = -ENOMEM; goto out; } } c = 0; for_each_prl_rcu(t->prl) { if (c >= cmax) break; if (kprl.addr != htonl(INADDR_ANY) && prl->addr != kprl.addr) continue; kp[c].addr = prl->addr; kp[c].flags = prl->flags; c++; if (kprl.addr != htonl(INADDR_ANY)) break; } out: rcu_read_unlock(); len = sizeof(*kp) * c; ret = 0; if ((len && copy_to_user(a + 1, kp, len)) || put_user(len, &a->datalen)) ret = -EFAULT; kfree(kp); return ret; } static int ipip6_tunnel_add_prl(struct ip_tunnel *t, struct ip_tunnel_prl *a, int chg) { struct ip_tunnel_prl_entry *p; int err = 0; if (a->addr == htonl(INADDR_ANY)) return -EINVAL; ASSERT_RTNL(); for (p = rtnl_dereference(t->prl); p; p = rtnl_dereference(p->next)) { if (p->addr == a->addr) { if (chg) { p->flags = a->flags; goto out; } err = -EEXIST; goto out; } } if (chg) { err = -ENXIO; goto out; } p = kzalloc(sizeof(struct ip_tunnel_prl_entry), GFP_KERNEL); if (!p) { err = -ENOBUFS; goto out; } p->next = t->prl; p->addr = a->addr; p->flags = a->flags; t->prl_count++; rcu_assign_pointer(t->prl, p); out: return err; } static void prl_list_destroy_rcu(struct rcu_head *head) { struct ip_tunnel_prl_entry *p, *n; p = container_of(head, struct ip_tunnel_prl_entry, rcu_head); do { n = rcu_dereference_protected(p->next, 1); kfree(p); p = n; } while (p); } static int ipip6_tunnel_del_prl(struct ip_tunnel *t, struct ip_tunnel_prl *a) { struct ip_tunnel_prl_entry *x; struct ip_tunnel_prl_entry __rcu **p; int err = 0; ASSERT_RTNL(); if (a && a->addr != htonl(INADDR_ANY)) { for (p = &t->prl; (x = rtnl_dereference(*p)) != NULL; p = &x->next) { if (x->addr == a->addr) { *p = x->next; kfree_rcu(x, rcu_head); t->prl_count--; goto out; } } err = -ENXIO; } else { x = rtnl_dereference(t->prl); if (x) { t->prl_count = 0; call_rcu(&x->rcu_head, prl_list_destroy_rcu); t->prl = NULL; } } out: return err; } static int isatap_chksrc(struct sk_buff *skb, const struct iphdr *iph, struct ip_tunnel *t) { struct ip_tunnel_prl_entry *p; int ok = 1; rcu_read_lock(); p = __ipip6_tunnel_locate_prl(t, iph->saddr); if (p) { if (p->flags & PRL_DEFAULT) skb->ndisc_nodetype = NDISC_NODETYPE_DEFAULT; else skb->ndisc_nodetype = NDISC_NODETYPE_NODEFAULT; } else { const struct in6_addr *addr6 = &ipv6_hdr(skb)->saddr; if (ipv6_addr_is_isatap(addr6) && (addr6->s6_addr32[3] == iph->saddr) && ipv6_chk_prefix(addr6, t->dev)) skb->ndisc_nodetype = NDISC_NODETYPE_HOST; else ok = 0; } rcu_read_unlock(); return ok; } static void ipip6_tunnel_uninit(struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); struct sit_net *sitn = net_generic(tunnel->net, sit_net_id); if (dev == sitn->fb_tunnel_dev) { RCU_INIT_POINTER(sitn->tunnels_wc[0], NULL); } else { ipip6_tunnel_unlink(sitn, tunnel); ipip6_tunnel_del_prl(tunnel, NULL); } dst_cache_reset(&tunnel->dst_cache); dev_put(dev); } static int ipip6_err(struct sk_buff *skb, u32 info) { const struct iphdr *iph = (const struct iphdr *)skb->data; const int type = icmp_hdr(skb)->type; const int code = icmp_hdr(skb)->code; unsigned int data_len = 0; struct ip_tunnel *t; int sifindex; int err; switch (type) { default: case ICMP_PARAMETERPROB: return 0; case ICMP_DEST_UNREACH: switch (code) { case ICMP_SR_FAILED: /* Impossible event. */ return 0; default: /* All others are translated to HOST_UNREACH. rfc2003 contains "deep thoughts" about NET_UNREACH, I believe they are just ether pollution. --ANK */ break; } break; case ICMP_TIME_EXCEEDED: if (code != ICMP_EXC_TTL) return 0; data_len = icmp_hdr(skb)->un.reserved[1] * 4; /* RFC 4884 4.1 */ break; case ICMP_REDIRECT: break; } err = -ENOENT; sifindex = netif_is_l3_master(skb->dev) ? IPCB(skb)->iif : 0; t = ipip6_tunnel_lookup(dev_net(skb->dev), skb->dev, iph->daddr, iph->saddr, sifindex); if (!t) goto out; if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED) { ipv4_update_pmtu(skb, dev_net(skb->dev), info, t->parms.link, iph->protocol); err = 0; goto out; } if (type == ICMP_REDIRECT) { ipv4_redirect(skb, dev_net(skb->dev), t->parms.link, iph->protocol); err = 0; goto out; } err = 0; if (__in6_dev_get(skb->dev) && !ip6_err_gen_icmpv6_unreach(skb, iph->ihl * 4, type, data_len)) goto out; if (t->parms.iph.daddr == 0) goto out; if (t->parms.iph.ttl == 0 && type == ICMP_TIME_EXCEEDED) goto out; if (time_before(jiffies, t->err_time + IPTUNNEL_ERR_TIMEO)) t->err_count++; else t->err_count = 1; t->err_time = jiffies; out: return err; } static inline bool is_spoofed_6rd(struct ip_tunnel *tunnel, const __be32 v4addr, const struct in6_addr *v6addr) { __be32 v4embed = 0; if (check_6rd(tunnel, v6addr, &v4embed) && v4addr != v4embed) return true; return false; } /* Checks if an address matches an address on the tunnel interface. * Used to detect the NAT of proto 41 packets and let them pass spoofing test. * Long story: * This function is called after we considered the packet as spoofed * in is_spoofed_6rd. * We may have a router that is doing NAT for proto 41 packets * for an internal station. Destination a.a.a.a/PREFIX:bbbb:bbbb * will be translated to n.n.n.n/PREFIX:bbbb:bbbb. And is_spoofed_6rd * function will return true, dropping the packet. * But, we can still check if is spoofed against the IP * addresses associated with the interface. */ static bool only_dnatted(const struct ip_tunnel *tunnel, const struct in6_addr *v6dst) { int prefix_len; #ifdef CONFIG_IPV6_SIT_6RD prefix_len = tunnel->ip6rd.prefixlen + 32 - tunnel->ip6rd.relay_prefixlen; #else prefix_len = 48; #endif return ipv6_chk_custom_prefix(v6dst, prefix_len, tunnel->dev); } /* Returns true if a packet is spoofed */ static bool packet_is_spoofed(struct sk_buff *skb, const struct iphdr *iph, struct ip_tunnel *tunnel) { const struct ipv6hdr *ipv6h; if (tunnel->dev->priv_flags & IFF_ISATAP) { if (!isatap_chksrc(skb, iph, tunnel)) return true; return false; } if (tunnel->dev->flags & IFF_POINTOPOINT) return false; ipv6h = ipv6_hdr(skb); if (unlikely(is_spoofed_6rd(tunnel, iph->saddr, &ipv6h->saddr))) { net_warn_ratelimited("Src spoofed %pI4/%pI6c -> %pI4/%pI6c\n", &iph->saddr, &ipv6h->saddr, &iph->daddr, &ipv6h->daddr); return true; } if (likely(!is_spoofed_6rd(tunnel, iph->daddr, &ipv6h->daddr))) return false; if (only_dnatted(tunnel, &ipv6h->daddr)) return false; net_warn_ratelimited("Dst spoofed %pI4/%pI6c -> %pI4/%pI6c\n", &iph->saddr, &ipv6h->saddr, &iph->daddr, &ipv6h->daddr); return true; } static int ipip6_rcv(struct sk_buff *skb) { const struct iphdr *iph = ip_hdr(skb); struct ip_tunnel *tunnel; int sifindex; int err; sifindex = netif_is_l3_master(skb->dev) ? IPCB(skb)->iif : 0; tunnel = ipip6_tunnel_lookup(dev_net(skb->dev), skb->dev, iph->saddr, iph->daddr, sifindex); if (tunnel) { struct pcpu_sw_netstats *tstats; if (tunnel->parms.iph.protocol != IPPROTO_IPV6 && tunnel->parms.iph.protocol != 0) goto out; skb->mac_header = skb->network_header; skb_reset_network_header(skb); IPCB(skb)->flags = 0; skb->dev = tunnel->dev; if (packet_is_spoofed(skb, iph, tunnel)) { tunnel->dev->stats.rx_errors++; goto out; } if (iptunnel_pull_header(skb, 0, htons(ETH_P_IPV6), !net_eq(tunnel->net, dev_net(tunnel->dev)))) goto out; err = IP_ECN_decapsulate(iph, skb); if (unlikely(err)) { if (log_ecn_error) net_info_ratelimited("non-ECT from %pI4 with TOS=%#x\n", &iph->saddr, iph->tos); if (err > 1) { ++tunnel->dev->stats.rx_frame_errors; ++tunnel->dev->stats.rx_errors; goto out; } } tstats = this_cpu_ptr(tunnel->dev->tstats); u64_stats_update_begin(&tstats->syncp); tstats->rx_packets++; tstats->rx_bytes += skb->len; u64_stats_update_end(&tstats->syncp); netif_rx(skb); return 0; } /* no tunnel matched, let upstream know, ipsec may handle it */ return 1; out: kfree_skb(skb); return 0; } static const struct tnl_ptk_info ipip_tpi = { /* no tunnel info required for ipip. */ .proto = htons(ETH_P_IP), }; #if IS_ENABLED(CONFIG_MPLS) static const struct tnl_ptk_info mplsip_tpi = { /* no tunnel info required for mplsip. */ .proto = htons(ETH_P_MPLS_UC), }; #endif static int sit_tunnel_rcv(struct sk_buff *skb, u8 ipproto) { const struct iphdr *iph; struct ip_tunnel *tunnel; int sifindex; sifindex = netif_is_l3_master(skb->dev) ? IPCB(skb)->iif : 0; iph = ip_hdr(skb); tunnel = ipip6_tunnel_lookup(dev_net(skb->dev), skb->dev, iph->saddr, iph->daddr, sifindex); if (tunnel) { const struct tnl_ptk_info *tpi; if (tunnel->parms.iph.protocol != ipproto && tunnel->parms.iph.protocol != 0) goto drop; if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) goto drop; #if IS_ENABLED(CONFIG_MPLS) if (ipproto == IPPROTO_MPLS) tpi = &mplsip_tpi; else #endif tpi = &ipip_tpi; if (iptunnel_pull_header(skb, 0, tpi->proto, false)) goto drop; return ip_tunnel_rcv(tunnel, skb, tpi, NULL, log_ecn_error); } return 1; drop: kfree_skb(skb); return 0; } static int ipip_rcv(struct sk_buff *skb) { return sit_tunnel_rcv(skb, IPPROTO_IPIP); } #if IS_ENABLED(CONFIG_MPLS) static int mplsip_rcv(struct sk_buff *skb) { return sit_tunnel_rcv(skb, IPPROTO_MPLS); } #endif /* * If the IPv6 address comes from 6rd / 6to4 (RFC 3056) addr space this function * stores the embedded IPv4 address in v4dst and returns true. */ static bool check_6rd(struct ip_tunnel *tunnel, const struct in6_addr *v6dst, __be32 *v4dst) { #ifdef CONFIG_IPV6_SIT_6RD if (ipv6_prefix_equal(v6dst, &tunnel->ip6rd.prefix, tunnel->ip6rd.prefixlen)) { unsigned int pbw0, pbi0; int pbi1; u32 d; pbw0 = tunnel->ip6rd.prefixlen >> 5; pbi0 = tunnel->ip6rd.prefixlen & 0x1f; d = (ntohl(v6dst->s6_addr32[pbw0]) << pbi0) >> tunnel->ip6rd.relay_prefixlen; pbi1 = pbi0 - tunnel->ip6rd.relay_prefixlen; if (pbi1 > 0) d |= ntohl(v6dst->s6_addr32[pbw0 + 1]) >> (32 - pbi1); *v4dst = tunnel->ip6rd.relay_prefix | htonl(d); return true; } #else if (v6dst->s6_addr16[0] == htons(0x2002)) { /* 6to4 v6 addr has 16 bits prefix, 32 v4addr, 16 SLA, ... */ memcpy(v4dst, &v6dst->s6_addr16[1], 4); return true; } #endif return false; } static inline __be32 try_6rd(struct ip_tunnel *tunnel, const struct in6_addr *v6dst) { __be32 dst = 0; check_6rd(tunnel, v6dst, &dst); return dst; } /* * This function assumes it is being called from dev_queue_xmit() * and that skb is filled properly by that function. */ static netdev_tx_t ipip6_tunnel_xmit(struct sk_buff *skb, struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); const struct iphdr *tiph = &tunnel->parms.iph; const struct ipv6hdr *iph6 = ipv6_hdr(skb); u8 tos = tunnel->parms.iph.tos; __be16 df = tiph->frag_off; struct rtable *rt; /* Route to the other host */ struct net_device *tdev; /* Device to other host */ unsigned int max_headroom; /* The extra header space needed */ __be32 dst = tiph->daddr; struct flowi4 fl4; int mtu; const struct in6_addr *addr6; int addr_type; u8 ttl; u8 protocol = IPPROTO_IPV6; int t_hlen = tunnel->hlen + sizeof(struct iphdr); if (tos == 1) tos = ipv6_get_dsfield(iph6); /* ISATAP (RFC4214) - must come before 6to4 */ if (dev->priv_flags & IFF_ISATAP) { struct neighbour *neigh = NULL; bool do_tx_error = false; if (skb_dst(skb)) neigh = dst_neigh_lookup(skb_dst(skb), &iph6->daddr); if (!neigh) { net_dbg_ratelimited("nexthop == NULL\n"); goto tx_error; } addr6 = (const struct in6_addr *)&neigh->primary_key; addr_type = ipv6_addr_type(addr6); if ((addr_type & IPV6_ADDR_UNICAST) && ipv6_addr_is_isatap(addr6)) dst = addr6->s6_addr32[3]; else do_tx_error = true; neigh_release(neigh); if (do_tx_error) goto tx_error; } if (!dst) dst = try_6rd(tunnel, &iph6->daddr); if (!dst) { struct neighbour *neigh = NULL; bool do_tx_error = false; if (skb_dst(skb)) neigh = dst_neigh_lookup(skb_dst(skb), &iph6->daddr); if (!neigh) { net_dbg_ratelimited("nexthop == NULL\n"); goto tx_error; } addr6 = (const struct in6_addr *)&neigh->primary_key; addr_type = ipv6_addr_type(addr6); if (addr_type == IPV6_ADDR_ANY) { addr6 = &ipv6_hdr(skb)->daddr; addr_type = ipv6_addr_type(addr6); } if ((addr_type & IPV6_ADDR_COMPATv4) != 0) dst = addr6->s6_addr32[3]; else do_tx_error = true; neigh_release(neigh); if (do_tx_error) goto tx_error; } flowi4_init_output(&fl4, tunnel->parms.link, tunnel->fwmark, RT_TOS(tos), RT_SCOPE_UNIVERSE, IPPROTO_IPV6, 0, dst, tiph->saddr, 0, 0, sock_net_uid(tunnel->net, NULL)); rt = ip_route_output_flow(tunnel->net, &fl4, NULL); if (IS_ERR(rt)) { dev->stats.tx_carrier_errors++; goto tx_error_icmp; } if (rt->rt_type != RTN_UNICAST) { ip_rt_put(rt); dev->stats.tx_carrier_errors++; goto tx_error_icmp; } tdev = rt->dst.dev; if (tdev == dev) { ip_rt_put(rt); dev->stats.collisions++; goto tx_error; } if (iptunnel_handle_offloads(skb, SKB_GSO_IPXIP4)) { ip_rt_put(rt); goto tx_error; } if (df) { mtu = dst_mtu(&rt->dst) - t_hlen; if (mtu < 68) { dev->stats.collisions++; ip_rt_put(rt); goto tx_error; } if (mtu < IPV6_MIN_MTU) { mtu = IPV6_MIN_MTU; df = 0; } if (tunnel->parms.iph.daddr) skb_dst_update_pmtu(skb, mtu); if (skb->len > mtu && !skb_is_gso(skb)) { icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); ip_rt_put(rt); goto tx_error; } } if (tunnel->err_count > 0) { if (time_before(jiffies, tunnel->err_time + IPTUNNEL_ERR_TIMEO)) { tunnel->err_count--; dst_link_failure(skb); } else tunnel->err_count = 0; } /* * Okay, now see if we can stuff it in the buffer as-is. */ max_headroom = LL_RESERVED_SPACE(tdev) + t_hlen; if (skb_headroom(skb) < max_headroom || skb_shared(skb) || (skb_cloned(skb) && !skb_clone_writable(skb, 0))) { struct sk_buff *new_skb = skb_realloc_headroom(skb, max_headroom); if (!new_skb) { ip_rt_put(rt); dev->stats.tx_dropped++; kfree_skb(skb); return NETDEV_TX_OK; } if (skb->sk) skb_set_owner_w(new_skb, skb->sk); dev_kfree_skb(skb); skb = new_skb; iph6 = ipv6_hdr(skb); } ttl = tiph->ttl; if (ttl == 0) ttl = iph6->hop_limit; tos = INET_ECN_encapsulate(tos, ipv6_get_dsfield(iph6)); if (ip_tunnel_encap(skb, tunnel, &protocol, &fl4) < 0) { ip_rt_put(rt); goto tx_error; } skb_set_inner_ipproto(skb, IPPROTO_IPV6); iptunnel_xmit(NULL, rt, skb, fl4.saddr, fl4.daddr, protocol, tos, ttl, df, !net_eq(tunnel->net, dev_net(dev))); return NETDEV_TX_OK; tx_error_icmp: dst_link_failure(skb); tx_error: kfree_skb(skb); dev->stats.tx_errors++; return NETDEV_TX_OK; } static netdev_tx_t sit_tunnel_xmit__(struct sk_buff *skb, struct net_device *dev, u8 ipproto) { struct ip_tunnel *tunnel = netdev_priv(dev); const struct iphdr *tiph = &tunnel->parms.iph; if (iptunnel_handle_offloads(skb, SKB_GSO_IPXIP4)) goto tx_error; skb_set_inner_ipproto(skb, ipproto); ip_tunnel_xmit(skb, dev, tiph, ipproto); return NETDEV_TX_OK; tx_error: kfree_skb(skb); dev->stats.tx_errors++; return NETDEV_TX_OK; } static netdev_tx_t sit_tunnel_xmit(struct sk_buff *skb, struct net_device *dev) { if (!pskb_inet_may_pull(skb)) goto tx_err; switch (skb->protocol) { case htons(ETH_P_IP): sit_tunnel_xmit__(skb, dev, IPPROTO_IPIP); break; case htons(ETH_P_IPV6): ipip6_tunnel_xmit(skb, dev); break; #if IS_ENABLED(CONFIG_MPLS) case htons(ETH_P_MPLS_UC): sit_tunnel_xmit__(skb, dev, IPPROTO_MPLS); break; #endif default: goto tx_err; } return NETDEV_TX_OK; tx_err: dev->stats.tx_errors++; kfree_skb(skb); return NETDEV_TX_OK; } static void ipip6_tunnel_bind_dev(struct net_device *dev) { struct net_device *tdev = NULL; struct ip_tunnel *tunnel; const struct iphdr *iph; struct flowi4 fl4; tunnel = netdev_priv(dev); iph = &tunnel->parms.iph; if (iph->daddr) { struct rtable *rt = ip_route_output_ports(tunnel->net, &fl4, NULL, iph->daddr, iph->saddr, 0, 0, IPPROTO_IPV6, RT_TOS(iph->tos), tunnel->parms.link); if (!IS_ERR(rt)) { tdev = rt->dst.dev; ip_rt_put(rt); } dev->flags |= IFF_POINTOPOINT; } if (!tdev && tunnel->parms.link) tdev = __dev_get_by_index(tunnel->net, tunnel->parms.link); if (tdev) { int t_hlen = tunnel->hlen + sizeof(struct iphdr); dev->hard_header_len = tdev->hard_header_len + sizeof(struct iphdr); dev->mtu = tdev->mtu - t_hlen; if (dev->mtu < IPV6_MIN_MTU) dev->mtu = IPV6_MIN_MTU; } } static void ipip6_tunnel_update(struct ip_tunnel *t, struct ip_tunnel_parm *p, __u32 fwmark) { struct net *net = t->net; struct sit_net *sitn = net_generic(net, sit_net_id); ipip6_tunnel_unlink(sitn, t); synchronize_net(); t->parms.iph.saddr = p->iph.saddr; t->parms.iph.daddr = p->iph.daddr; memcpy(t->dev->dev_addr, &p->iph.saddr, 4); memcpy(t->dev->broadcast, &p->iph.daddr, 4); ipip6_tunnel_link(sitn, t); t->parms.iph.ttl = p->iph.ttl; t->parms.iph.tos = p->iph.tos; t->parms.iph.frag_off = p->iph.frag_off; if (t->parms.link != p->link || t->fwmark != fwmark) { t->parms.link = p->link; t->fwmark = fwmark; ipip6_tunnel_bind_dev(t->dev); } dst_cache_reset(&t->dst_cache); netdev_state_change(t->dev); } #ifdef CONFIG_IPV6_SIT_6RD static int ipip6_tunnel_update_6rd(struct ip_tunnel *t, struct ip_tunnel_6rd *ip6rd) { struct in6_addr prefix; __be32 relay_prefix; if (ip6rd->relay_prefixlen > 32 || ip6rd->prefixlen + (32 - ip6rd->relay_prefixlen) > 64) return -EINVAL; ipv6_addr_prefix(&prefix, &ip6rd->prefix, ip6rd->prefixlen); if (!ipv6_addr_equal(&prefix, &ip6rd->prefix)) return -EINVAL; if (ip6rd->relay_prefixlen) relay_prefix = ip6rd->relay_prefix & htonl(0xffffffffUL << (32 - ip6rd->relay_prefixlen)); else relay_prefix = 0; if (relay_prefix != ip6rd->relay_prefix) return -EINVAL; t->ip6rd.prefix = prefix; t->ip6rd.relay_prefix = relay_prefix; t->ip6rd.prefixlen = ip6rd->prefixlen; t->ip6rd.relay_prefixlen = ip6rd->relay_prefixlen; dst_cache_reset(&t->dst_cache); netdev_state_change(t->dev); return 0; } #endif static bool ipip6_valid_ip_proto(u8 ipproto) { return ipproto == IPPROTO_IPV6 || ipproto == IPPROTO_IPIP || #if IS_ENABLED(CONFIG_MPLS) ipproto == IPPROTO_MPLS || #endif ipproto == 0; } static int ipip6_tunnel_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { int err = 0; struct ip_tunnel_parm p; struct ip_tunnel_prl prl; struct ip_tunnel *t = netdev_priv(dev); struct net *net = t->net; struct sit_net *sitn = net_generic(net, sit_net_id); #ifdef CONFIG_IPV6_SIT_6RD struct ip_tunnel_6rd ip6rd; #endif switch (cmd) { case SIOCGETTUNNEL: #ifdef CONFIG_IPV6_SIT_6RD case SIOCGET6RD: #endif if (dev == sitn->fb_tunnel_dev) { if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p))) { err = -EFAULT; break; } t = ipip6_tunnel_locate(net, &p, 0); if (!t) t = netdev_priv(dev); } err = -EFAULT; if (cmd == SIOCGETTUNNEL) { memcpy(&p, &t->parms, sizeof(p)); if (copy_to_user(ifr->ifr_ifru.ifru_data, &p, sizeof(p))) goto done; #ifdef CONFIG_IPV6_SIT_6RD } else { ip6rd.prefix = t->ip6rd.prefix; ip6rd.relay_prefix = t->ip6rd.relay_prefix; ip6rd.prefixlen = t->ip6rd.prefixlen; ip6rd.relay_prefixlen = t->ip6rd.relay_prefixlen; if (copy_to_user(ifr->ifr_ifru.ifru_data, &ip6rd, sizeof(ip6rd))) goto done; #endif } err = 0; break; case SIOCADDTUNNEL: case SIOCCHGTUNNEL: err = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) goto done; err = -EFAULT; if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p))) goto done; err = -EINVAL; if (!ipip6_valid_ip_proto(p.iph.protocol)) goto done; if (p.iph.version != 4 || p.iph.ihl != 5 || (p.iph.frag_off&htons(~IP_DF))) goto done; if (p.iph.ttl) p.iph.frag_off |= htons(IP_DF); t = ipip6_tunnel_locate(net, &p, cmd == SIOCADDTUNNEL); if (dev != sitn->fb_tunnel_dev && cmd == SIOCCHGTUNNEL) { if (t) { if (t->dev != dev) { err = -EEXIST; break; } } else { if (((dev->flags&IFF_POINTOPOINT) && !p.iph.daddr) || (!(dev->flags&IFF_POINTOPOINT) && p.iph.daddr)) { err = -EINVAL; break; } t = netdev_priv(dev); } ipip6_tunnel_update(t, &p, t->fwmark); } if (t) { err = 0; if (copy_to_user(ifr->ifr_ifru.ifru_data, &t->parms, sizeof(p))) err = -EFAULT; } else err = (cmd == SIOCADDTUNNEL ? -ENOBUFS : -ENOENT); break; case SIOCDELTUNNEL: err = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) goto done; if (dev == sitn->fb_tunnel_dev) { err = -EFAULT; if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p))) goto done; err = -ENOENT; t = ipip6_tunnel_locate(net, &p, 0); if (!t) goto done; err = -EPERM; if (t == netdev_priv(sitn->fb_tunnel_dev)) goto done; dev = t->dev; } unregister_netdevice(dev); err = 0; break; case SIOCGETPRL: err = -EINVAL; if (dev == sitn->fb_tunnel_dev) goto done; err = ipip6_tunnel_get_prl(t, ifr->ifr_ifru.ifru_data); break; case SIOCADDPRL: case SIOCDELPRL: case SIOCCHGPRL: err = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) goto done; err = -EINVAL; if (dev == sitn->fb_tunnel_dev) goto done; err = -EFAULT; if (copy_from_user(&prl, ifr->ifr_ifru.ifru_data, sizeof(prl))) goto done; switch (cmd) { case SIOCDELPRL: err = ipip6_tunnel_del_prl(t, &prl); break; case SIOCADDPRL: case SIOCCHGPRL: err = ipip6_tunnel_add_prl(t, &prl, cmd == SIOCCHGPRL); break; } dst_cache_reset(&t->dst_cache); netdev_state_change(dev); break; #ifdef CONFIG_IPV6_SIT_6RD case SIOCADD6RD: case SIOCCHG6RD: case SIOCDEL6RD: err = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) goto done; err = -EFAULT; if (copy_from_user(&ip6rd, ifr->ifr_ifru.ifru_data, sizeof(ip6rd))) goto done; if (cmd != SIOCDEL6RD) { err = ipip6_tunnel_update_6rd(t, &ip6rd); if (err < 0) goto done; } else ipip6_tunnel_clone_6rd(dev, sitn); err = 0; break; #endif default: err = -EINVAL; } done: return err; } static const struct net_device_ops ipip6_netdev_ops = { .ndo_init = ipip6_tunnel_init, .ndo_uninit = ipip6_tunnel_uninit, .ndo_start_xmit = sit_tunnel_xmit, .ndo_do_ioctl = ipip6_tunnel_ioctl, .ndo_get_stats64 = ip_tunnel_get_stats64, .ndo_get_iflink = ip_tunnel_get_iflink, }; static void ipip6_dev_free(struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); dst_cache_destroy(&tunnel->dst_cache); free_percpu(dev->tstats); } #define SIT_FEATURES (NETIF_F_SG | \ NETIF_F_FRAGLIST | \ NETIF_F_HIGHDMA | \ NETIF_F_GSO_SOFTWARE | \ NETIF_F_HW_CSUM) static void ipip6_tunnel_setup(struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); int t_hlen = tunnel->hlen + sizeof(struct iphdr); dev->netdev_ops = &ipip6_netdev_ops; dev->needs_free_netdev = true; dev->priv_destructor = ipip6_dev_free; dev->type = ARPHRD_SIT; dev->hard_header_len = LL_MAX_HEADER + t_hlen; dev->mtu = ETH_DATA_LEN - t_hlen; dev->min_mtu = IPV6_MIN_MTU; dev->max_mtu = IP6_MAX_MTU - t_hlen; dev->flags = IFF_NOARP; netif_keep_dst(dev); dev->addr_len = 4; dev->features |= NETIF_F_LLTX; dev->features |= SIT_FEATURES; dev->hw_features |= SIT_FEATURES; } static int ipip6_tunnel_init(struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); int err; tunnel->dev = dev; tunnel->net = dev_net(dev); strcpy(tunnel->parms.name, dev->name); ipip6_tunnel_bind_dev(dev); dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats); if (!dev->tstats) return -ENOMEM; err = dst_cache_init(&tunnel->dst_cache, GFP_KERNEL); if (err) { free_percpu(dev->tstats); dev->tstats = NULL; return err; } return 0; } static void __net_init ipip6_fb_tunnel_init(struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); struct iphdr *iph = &tunnel->parms.iph; struct net *net = dev_net(dev); struct sit_net *sitn = net_generic(net, sit_net_id); iph->version = 4; iph->protocol = IPPROTO_IPV6; iph->ihl = 5; iph->ttl = 64; dev_hold(dev); rcu_assign_pointer(sitn->tunnels_wc[0], tunnel); } static int ipip6_validate(struct nlattr *tb[], struct nlattr *data[], struct netlink_ext_ack *extack) { u8 proto; if (!data || !data[IFLA_IPTUN_PROTO]) return 0; proto = nla_get_u8(data[IFLA_IPTUN_PROTO]); if (!ipip6_valid_ip_proto(proto)) return -EINVAL; return 0; } static void ipip6_netlink_parms(struct nlattr *data[], struct ip_tunnel_parm *parms, __u32 *fwmark) { memset(parms, 0, sizeof(*parms)); parms->iph.version = 4; parms->iph.protocol = IPPROTO_IPV6; parms->iph.ihl = 5; parms->iph.ttl = 64; if (!data) return; if (data[IFLA_IPTUN_LINK]) parms->link = nla_get_u32(data[IFLA_IPTUN_LINK]); if (data[IFLA_IPTUN_LOCAL]) parms->iph.saddr = nla_get_be32(data[IFLA_IPTUN_LOCAL]); if (data[IFLA_IPTUN_REMOTE]) parms->iph.daddr = nla_get_be32(data[IFLA_IPTUN_REMOTE]); if (data[IFLA_IPTUN_TTL]) { parms->iph.ttl = nla_get_u8(data[IFLA_IPTUN_TTL]); if (parms->iph.ttl) parms->iph.frag_off = htons(IP_DF); } if (data[IFLA_IPTUN_TOS]) parms->iph.tos = nla_get_u8(data[IFLA_IPTUN_TOS]); if (!data[IFLA_IPTUN_PMTUDISC] || nla_get_u8(data[IFLA_IPTUN_PMTUDISC])) parms->iph.frag_off = htons(IP_DF); if (data[IFLA_IPTUN_FLAGS]) parms->i_flags = nla_get_be16(data[IFLA_IPTUN_FLAGS]); if (data[IFLA_IPTUN_PROTO]) parms->iph.protocol = nla_get_u8(data[IFLA_IPTUN_PROTO]); if (data[IFLA_IPTUN_FWMARK]) *fwmark = nla_get_u32(data[IFLA_IPTUN_FWMARK]); } /* This function returns true when ENCAP attributes are present in the nl msg */ static bool ipip6_netlink_encap_parms(struct nlattr *data[], struct ip_tunnel_encap *ipencap) { bool ret = false; memset(ipencap, 0, sizeof(*ipencap)); if (!data) return ret; if (data[IFLA_IPTUN_ENCAP_TYPE]) { ret = true; ipencap->type = nla_get_u16(data[IFLA_IPTUN_ENCAP_TYPE]); } if (data[IFLA_IPTUN_ENCAP_FLAGS]) { ret = true; ipencap->flags = nla_get_u16(data[IFLA_IPTUN_ENCAP_FLAGS]); } if (data[IFLA_IPTUN_ENCAP_SPORT]) { ret = true; ipencap->sport = nla_get_be16(data[IFLA_IPTUN_ENCAP_SPORT]); } if (data[IFLA_IPTUN_ENCAP_DPORT]) { ret = true; ipencap->dport = nla_get_be16(data[IFLA_IPTUN_ENCAP_DPORT]); } return ret; } #ifdef CONFIG_IPV6_SIT_6RD /* This function returns true when 6RD attributes are present in the nl msg */ static bool ipip6_netlink_6rd_parms(struct nlattr *data[], struct ip_tunnel_6rd *ip6rd) { bool ret = false; memset(ip6rd, 0, sizeof(*ip6rd)); if (!data) return ret; if (data[IFLA_IPTUN_6RD_PREFIX]) { ret = true; ip6rd->prefix = nla_get_in6_addr(data[IFLA_IPTUN_6RD_PREFIX]); } if (data[IFLA_IPTUN_6RD_RELAY_PREFIX]) { ret = true; ip6rd->relay_prefix = nla_get_be32(data[IFLA_IPTUN_6RD_RELAY_PREFIX]); } if (data[IFLA_IPTUN_6RD_PREFIXLEN]) { ret = true; ip6rd->prefixlen = nla_get_u16(data[IFLA_IPTUN_6RD_PREFIXLEN]); } if (data[IFLA_IPTUN_6RD_RELAY_PREFIXLEN]) { ret = true; ip6rd->relay_prefixlen = nla_get_u16(data[IFLA_IPTUN_6RD_RELAY_PREFIXLEN]); } return ret; } #endif static int ipip6_newlink(struct net *src_net, struct net_device *dev, struct nlattr *tb[], struct nlattr *data[], struct netlink_ext_ack *extack) { struct net *net = dev_net(dev); struct ip_tunnel *nt; struct ip_tunnel_encap ipencap; #ifdef CONFIG_IPV6_SIT_6RD struct ip_tunnel_6rd ip6rd; #endif int err; nt = netdev_priv(dev); if (ipip6_netlink_encap_parms(data, &ipencap)) { err = ip_tunnel_encap_setup(nt, &ipencap); if (err < 0) return err; } ipip6_netlink_parms(data, &nt->parms, &nt->fwmark); if (ipip6_tunnel_locate(net, &nt->parms, 0)) return -EEXIST; err = ipip6_tunnel_create(dev); if (err < 0) return err; if (tb[IFLA_MTU]) { u32 mtu = nla_get_u32(tb[IFLA_MTU]); if (mtu >= IPV6_MIN_MTU && mtu <= IP6_MAX_MTU - dev->hard_header_len) dev->mtu = mtu; } #ifdef CONFIG_IPV6_SIT_6RD if (ipip6_netlink_6rd_parms(data, &ip6rd)) err = ipip6_tunnel_update_6rd(nt, &ip6rd); #endif return err; } static int ipip6_changelink(struct net_device *dev, struct nlattr *tb[], struct nlattr *data[], struct netlink_ext_ack *extack) { struct ip_tunnel *t = netdev_priv(dev); struct ip_tunnel_parm p; struct ip_tunnel_encap ipencap; struct net *net = t->net; struct sit_net *sitn = net_generic(net, sit_net_id); #ifdef CONFIG_IPV6_SIT_6RD struct ip_tunnel_6rd ip6rd; #endif __u32 fwmark = t->fwmark; int err; if (dev == sitn->fb_tunnel_dev) return -EINVAL; if (ipip6_netlink_encap_parms(data, &ipencap)) { err = ip_tunnel_encap_setup(t, &ipencap); if (err < 0) return err; } ipip6_netlink_parms(data, &p, &fwmark); if (((dev->flags & IFF_POINTOPOINT) && !p.iph.daddr) || (!(dev->flags & IFF_POINTOPOINT) && p.iph.daddr)) return -EINVAL; t = ipip6_tunnel_locate(net, &p, 0); if (t) { if (t->dev != dev) return -EEXIST; } else t = netdev_priv(dev); ipip6_tunnel_update(t, &p, fwmark); #ifdef CONFIG_IPV6_SIT_6RD if (ipip6_netlink_6rd_parms(data, &ip6rd)) return ipip6_tunnel_update_6rd(t, &ip6rd); #endif return 0; } static size_t ipip6_get_size(const struct net_device *dev) { return /* IFLA_IPTUN_LINK */ nla_total_size(4) + /* IFLA_IPTUN_LOCAL */ nla_total_size(4) + /* IFLA_IPTUN_REMOTE */ nla_total_size(4) + /* IFLA_IPTUN_TTL */ nla_total_size(1) + /* IFLA_IPTUN_TOS */ nla_total_size(1) + /* IFLA_IPTUN_PMTUDISC */ nla_total_size(1) + /* IFLA_IPTUN_FLAGS */ nla_total_size(2) + /* IFLA_IPTUN_PROTO */ nla_total_size(1) + #ifdef CONFIG_IPV6_SIT_6RD /* IFLA_IPTUN_6RD_PREFIX */ nla_total_size(sizeof(struct in6_addr)) + /* IFLA_IPTUN_6RD_RELAY_PREFIX */ nla_total_size(4) + /* IFLA_IPTUN_6RD_PREFIXLEN */ nla_total_size(2) + /* IFLA_IPTUN_6RD_RELAY_PREFIXLEN */ nla_total_size(2) + #endif /* IFLA_IPTUN_ENCAP_TYPE */ nla_total_size(2) + /* IFLA_IPTUN_ENCAP_FLAGS */ nla_total_size(2) + /* IFLA_IPTUN_ENCAP_SPORT */ nla_total_size(2) + /* IFLA_IPTUN_ENCAP_DPORT */ nla_total_size(2) + /* IFLA_IPTUN_FWMARK */ nla_total_size(4) + 0; } static int ipip6_fill_info(struct sk_buff *skb, const struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); struct ip_tunnel_parm *parm = &tunnel->parms; if (nla_put_u32(skb, IFLA_IPTUN_LINK, parm->link) || nla_put_in_addr(skb, IFLA_IPTUN_LOCAL, parm->iph.saddr) || nla_put_in_addr(skb, IFLA_IPTUN_REMOTE, parm->iph.daddr) || nla_put_u8(skb, IFLA_IPTUN_TTL, parm->iph.ttl) || nla_put_u8(skb, IFLA_IPTUN_TOS, parm->iph.tos) || nla_put_u8(skb, IFLA_IPTUN_PMTUDISC, !!(parm->iph.frag_off & htons(IP_DF))) || nla_put_u8(skb, IFLA_IPTUN_PROTO, parm->iph.protocol) || nla_put_be16(skb, IFLA_IPTUN_FLAGS, parm->i_flags) || nla_put_u32(skb, IFLA_IPTUN_FWMARK, tunnel->fwmark)) goto nla_put_failure; #ifdef CONFIG_IPV6_SIT_6RD if (nla_put_in6_addr(skb, IFLA_IPTUN_6RD_PREFIX, &tunnel->ip6rd.prefix) || nla_put_in_addr(skb, IFLA_IPTUN_6RD_RELAY_PREFIX, tunnel->ip6rd.relay_prefix) || nla_put_u16(skb, IFLA_IPTUN_6RD_PREFIXLEN, tunnel->ip6rd.prefixlen) || nla_put_u16(skb, IFLA_IPTUN_6RD_RELAY_PREFIXLEN, tunnel->ip6rd.relay_prefixlen)) goto nla_put_failure; #endif if (nla_put_u16(skb, IFLA_IPTUN_ENCAP_TYPE, tunnel->encap.type) || nla_put_be16(skb, IFLA_IPTUN_ENCAP_SPORT, tunnel->encap.sport) || nla_put_be16(skb, IFLA_IPTUN_ENCAP_DPORT, tunnel->encap.dport) || nla_put_u16(skb, IFLA_IPTUN_ENCAP_FLAGS, tunnel->encap.flags)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } static const struct nla_policy ipip6_policy[IFLA_IPTUN_MAX + 1] = { [IFLA_IPTUN_LINK] = { .type = NLA_U32 }, [IFLA_IPTUN_LOCAL] = { .type = NLA_U32 }, [IFLA_IPTUN_REMOTE] = { .type = NLA_U32 }, [IFLA_IPTUN_TTL] = { .type = NLA_U8 }, [IFLA_IPTUN_TOS] = { .type = NLA_U8 }, [IFLA_IPTUN_PMTUDISC] = { .type = NLA_U8 }, [IFLA_IPTUN_FLAGS] = { .type = NLA_U16 }, [IFLA_IPTUN_PROTO] = { .type = NLA_U8 }, #ifdef CONFIG_IPV6_SIT_6RD [IFLA_IPTUN_6RD_PREFIX] = { .len = sizeof(struct in6_addr) }, [IFLA_IPTUN_6RD_RELAY_PREFIX] = { .type = NLA_U32 }, [IFLA_IPTUN_6RD_PREFIXLEN] = { .type = NLA_U16 }, [IFLA_IPTUN_6RD_RELAY_PREFIXLEN] = { .type = NLA_U16 }, #endif [IFLA_IPTUN_ENCAP_TYPE] = { .type = NLA_U16 }, [IFLA_IPTUN_ENCAP_FLAGS] = { .type = NLA_U16 }, [IFLA_IPTUN_ENCAP_SPORT] = { .type = NLA_U16 }, [IFLA_IPTUN_ENCAP_DPORT] = { .type = NLA_U16 }, [IFLA_IPTUN_FWMARK] = { .type = NLA_U32 }, }; static void ipip6_dellink(struct net_device *dev, struct list_head *head) { struct net *net = dev_net(dev); struct sit_net *sitn = net_generic(net, sit_net_id); if (dev != sitn->fb_tunnel_dev) unregister_netdevice_queue(dev, head); } static struct rtnl_link_ops sit_link_ops __read_mostly = { .kind = "sit", .maxtype = IFLA_IPTUN_MAX, .policy = ipip6_policy, .priv_size = sizeof(struct ip_tunnel), .setup = ipip6_tunnel_setup, .validate = ipip6_validate, .newlink = ipip6_newlink, .changelink = ipip6_changelink, .get_size = ipip6_get_size, .fill_info = ipip6_fill_info, .dellink = ipip6_dellink, .get_link_net = ip_tunnel_get_link_net, }; static struct xfrm_tunnel sit_handler __read_mostly = { .handler = ipip6_rcv, .err_handler = ipip6_err, .priority = 1, }; static struct xfrm_tunnel ipip_handler __read_mostly = { .handler = ipip_rcv, .err_handler = ipip6_err, .priority = 2, }; #if IS_ENABLED(CONFIG_MPLS) static struct xfrm_tunnel mplsip_handler __read_mostly = { .handler = mplsip_rcv, .err_handler = ipip6_err, .priority = 2, }; #endif static void __net_exit sit_destroy_tunnels(struct net *net, struct list_head *head) { struct sit_net *sitn = net_generic(net, sit_net_id); struct net_device *dev, *aux; int prio; for_each_netdev_safe(net, dev, aux) if (dev->rtnl_link_ops == &sit_link_ops) unregister_netdevice_queue(dev, head); for (prio = 1; prio < 4; prio++) { int h; for (h = 0; h < IP6_SIT_HASH_SIZE; h++) { struct ip_tunnel *t; t = rtnl_dereference(sitn->tunnels[prio][h]); while (t) { /* If dev is in the same netns, it has already * been added to the list by the previous loop. */ if (!net_eq(dev_net(t->dev), net)) unregister_netdevice_queue(t->dev, head); t = rtnl_dereference(t->next); } } } } static int __net_init sit_init_net(struct net *net) { struct sit_net *sitn = net_generic(net, sit_net_id); struct ip_tunnel *t; int err; sitn->tunnels[0] = sitn->tunnels_wc; sitn->tunnels[1] = sitn->tunnels_l; sitn->tunnels[2] = sitn->tunnels_r; sitn->tunnels[3] = sitn->tunnels_r_l; if (!net_has_fallback_tunnels(net)) return 0; sitn->fb_tunnel_dev = alloc_netdev(sizeof(struct ip_tunnel), "sit0", NET_NAME_UNKNOWN, ipip6_tunnel_setup); if (!sitn->fb_tunnel_dev) { err = -ENOMEM; goto err_alloc_dev; } dev_net_set(sitn->fb_tunnel_dev, net); sitn->fb_tunnel_dev->rtnl_link_ops = &sit_link_ops; /* FB netdevice is special: we have one, and only one per netns. * Allowing to move it to another netns is clearly unsafe. */ sitn->fb_tunnel_dev->features |= NETIF_F_NETNS_LOCAL; err = register_netdev(sitn->fb_tunnel_dev); if (err) goto err_reg_dev; ipip6_tunnel_clone_6rd(sitn->fb_tunnel_dev, sitn); ipip6_fb_tunnel_init(sitn->fb_tunnel_dev); t = netdev_priv(sitn->fb_tunnel_dev); strcpy(t->parms.name, sitn->fb_tunnel_dev->name); return 0; err_reg_dev: ipip6_dev_free(sitn->fb_tunnel_dev); err_alloc_dev: return err; } static void __net_exit sit_exit_batch_net(struct list_head *net_list) { LIST_HEAD(list); struct net *net; rtnl_lock(); list_for_each_entry(net, net_list, exit_list) sit_destroy_tunnels(net, &list); unregister_netdevice_many(&list); rtnl_unlock(); } static struct pernet_operations sit_net_ops = { .init = sit_init_net, .exit_batch = sit_exit_batch_net, .id = &sit_net_id, .size = sizeof(struct sit_net), }; static void __exit sit_cleanup(void) { rtnl_link_unregister(&sit_link_ops); xfrm4_tunnel_deregister(&sit_handler, AF_INET6); xfrm4_tunnel_deregister(&ipip_handler, AF_INET); #if IS_ENABLED(CONFIG_MPLS) xfrm4_tunnel_deregister(&mplsip_handler, AF_MPLS); #endif unregister_pernet_device(&sit_net_ops); rcu_barrier(); /* Wait for completion of call_rcu()'s */ } static int __init sit_init(void) { int err; pr_info("IPv6, IPv4 and MPLS over IPv4 tunneling driver\n"); err = register_pernet_device(&sit_net_ops); if (err < 0) return err; err = xfrm4_tunnel_register(&sit_handler, AF_INET6); if (err < 0) { pr_info("%s: can't register ip6ip4\n", __func__); goto xfrm_tunnel_failed; } err = xfrm4_tunnel_register(&ipip_handler, AF_INET); if (err < 0) { pr_info("%s: can't register ip4ip4\n", __func__); goto xfrm_tunnel4_failed; } #if IS_ENABLED(CONFIG_MPLS) err = xfrm4_tunnel_register(&mplsip_handler, AF_MPLS); if (err < 0) { pr_info("%s: can't register mplsip\n", __func__); goto xfrm_tunnel_mpls_failed; } #endif err = rtnl_link_register(&sit_link_ops); if (err < 0) goto rtnl_link_failed; out: return err; rtnl_link_failed: #if IS_ENABLED(CONFIG_MPLS) xfrm4_tunnel_deregister(&mplsip_handler, AF_MPLS); xfrm_tunnel_mpls_failed: #endif xfrm4_tunnel_deregister(&ipip_handler, AF_INET); xfrm_tunnel4_failed: xfrm4_tunnel_deregister(&sit_handler, AF_INET6); xfrm_tunnel_failed: unregister_pernet_device(&sit_net_ops); goto out; } module_init(sit_init); module_exit(sit_cleanup); MODULE_LICENSE("GPL"); MODULE_ALIAS_RTNL_LINK("sit"); MODULE_ALIAS_NETDEV("sit0");
./CrossVul/dataset_final_sorted/CWE-772/c/bad_1161_0
crossvul-cpp_data_good_2613_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N GGGG % % P P NN N G % % PPPP N N N G GG % % P N NN G G % % P N N GGG % % % % % % Read/Write Portable Network Graphics Image Format % % % % Software Design % % Cristy % % Glenn Randers-Pehrson % % November 1997 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/histogram.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/layer.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/transform.h" #include "magick/utility.h" #if defined(MAGICKCORE_PNG_DELEGATE) /* Suppress libpng pedantic warnings that were added in * libpng-1.2.41 and libpng-1.4.0. If you are working on * migration to libpng-1.5, remove these defines and then * fix any code that generates warnings. */ /* #define PNG_DEPRECATED Use of this function is deprecated */ /* #define PNG_USE_RESULT The result of this function must be checked */ /* #define PNG_NORETURN This function does not return */ /* #define PNG_ALLOCATED The result of the function is new memory */ /* #define PNG_DEPSTRUCT Access to this struct member is deprecated */ /* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */ #define PNG_PTR_NORETURN #include "png.h" #include "zlib.h" /* ImageMagick differences */ #define first_scene scene #if PNG_LIBPNG_VER > 10011 /* Optional declarations. Define or undefine them as you like. */ /* #define PNG_DEBUG -- turning this on breaks VisualC compiling */ /* Features under construction. Define these to work on them. */ #undef MNG_OBJECT_BUFFERS #undef MNG_BASI_SUPPORTED #define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */ #define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */ #if defined(MAGICKCORE_JPEG_DELEGATE) # define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */ #endif #if !defined(RGBColorMatchExact) #define IsPNGColorEqual(color,target) \ (((color).red == (target).red) && \ ((color).green == (target).green) && \ ((color).blue == (target).blue)) #endif /* Table of recognized sRGB ICC profiles */ struct sRGB_info_struct { png_uint_32 len; png_uint_32 crc; png_byte intent; }; const struct sRGB_info_struct sRGB_info[] = { /* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */ { 3048, 0x3b8772b9UL, 0}, /* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */ { 3052, 0x427ebb21UL, 1}, /* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */ {60988, 0x306fd8aeUL, 0}, /* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */ {60960, 0xbbef7812UL, 0}, /* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */ { 3024, 0x5d5129ceUL, 1}, /* HP-Microsoft sRGB v2 perceptual */ { 3144, 0x182ea552UL, 0}, /* HP-Microsoft sRGB v2 media-relative */ { 3144, 0xf29e526dUL, 1}, /* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */ { 524, 0xd4938c39UL, 0}, /* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */ { 3212, 0x034af5a1UL, 0}, /* Not recognized */ { 0, 0x00000000UL, 0}, }; /* Macros for left-bit-replication to ensure that pixels * and PixelPackets all have the same image->depth, and for use * in PNG8 quantization. */ /* LBR01: Replicate top bit */ #define LBR01PacketRed(pixelpacket) \ (pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketGreen(pixelpacket) \ (pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketBlue(pixelpacket) \ (pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketOpacity(pixelpacket) \ (pixelpacket).opacity=(ScaleQuantumToChar((pixelpacket).opacity) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketRGB(pixelpacket) \ { \ LBR01PacketRed((pixelpacket)); \ LBR01PacketGreen((pixelpacket)); \ LBR01PacketBlue((pixelpacket)); \ } #define LBR01PacketRGBO(pixelpacket) \ { \ LBR01PacketRGB((pixelpacket)); \ LBR01PacketOpacity((pixelpacket)); \ } #define LBR01PixelRed(pixel) \ (SetPixelRed((pixel), \ ScaleQuantumToChar(GetPixelRed((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelGreen(pixel) \ (SetPixelGreen((pixel), \ ScaleQuantumToChar(GetPixelGreen((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelBlue(pixel) \ (SetPixelBlue((pixel), \ ScaleQuantumToChar(GetPixelBlue((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelOpacity(pixel) \ (SetPixelOpacity((pixel), \ ScaleQuantumToChar(GetPixelOpacity((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelRGB(pixel) \ { \ LBR01PixelRed((pixel)); \ LBR01PixelGreen((pixel)); \ LBR01PixelBlue((pixel)); \ } #define LBR01PixelRGBO(pixel) \ { \ LBR01PixelRGB((pixel)); \ LBR01PixelOpacity((pixel)); \ } /* LBR02: Replicate top 2 bits */ #define LBR02PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketOpacity(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xc0; \ (pixelpacket).opacity=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketRGB(pixelpacket) \ { \ LBR02PacketRed((pixelpacket)); \ LBR02PacketGreen((pixelpacket)); \ LBR02PacketBlue((pixelpacket)); \ } #define LBR02PacketRGBO(pixelpacket) \ { \ LBR02PacketRGB((pixelpacket)); \ LBR02PacketOpacity((pixelpacket)); \ } #define LBR02PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xc0; \ SetPixelRed((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xc0; \ SetPixelGreen((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xc0; \ SetPixelBlue((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02Opacity(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xc0; \ SetPixelOpacity((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelRGB(pixel) \ { \ LBR02PixelRed((pixel)); \ LBR02PixelGreen((pixel)); \ LBR02PixelBlue((pixel)); \ } #define LBR02PixelRGBO(pixel) \ { \ LBR02PixelRGB((pixel)); \ LBR02Opacity((pixel)); \ } /* LBR03: Replicate top 3 bits (only used with opaque pixels during PNG8 quantization) */ #define LBR03PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketRGB(pixelpacket) \ { \ LBR03PacketRed((pixelpacket)); \ LBR03PacketGreen((pixelpacket)); \ LBR03PacketBlue((pixelpacket)); \ } #define LBR03PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xe0; \ SetPixelRed((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xe0; \ SetPixelGreen((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelBlue(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue((pixel))) \ & 0xe0; \ SetPixelBlue((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelRGB(pixel) \ { \ LBR03PixelRed((pixel)); \ LBR03PixelGreen((pixel)); \ LBR03PixelBlue((pixel)); \ } /* LBR04: Replicate top 4 bits */ #define LBR04PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \ (pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \ (pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \ (pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketOpacity(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xf0; \ (pixelpacket).opacity=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketRGB(pixelpacket) \ { \ LBR04PacketRed((pixelpacket)); \ LBR04PacketGreen((pixelpacket)); \ LBR04PacketBlue((pixelpacket)); \ } #define LBR04PacketRGBO(pixelpacket) \ { \ LBR04PacketRGB((pixelpacket)); \ LBR04PacketOpacity((pixelpacket)); \ } #define LBR04PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xf0; \ SetPixelRed((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xf0; \ SetPixelGreen((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xf0; \ SetPixelBlue((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelOpacity(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xf0; \ SetPixelOpacity((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelRGB(pixel) \ { \ LBR04PixelRed((pixel)); \ LBR04PixelGreen((pixel)); \ LBR04PixelBlue((pixel)); \ } #define LBR04PixelRGBO(pixel) \ { \ LBR04PixelRGB((pixel)); \ LBR04PixelOpacity((pixel)); \ } /* Establish thread safety. setjmp/longjmp is claimed to be safe on these platforms: setjmp/longjmp is alleged to be unsafe on these platforms: */ #ifdef PNG_SETJMP_SUPPORTED # ifndef IMPNG_SETJMP_IS_THREAD_SAFE # define IMPNG_SETJMP_NOT_THREAD_SAFE # endif # ifdef IMPNG_SETJMP_NOT_THREAD_SAFE static SemaphoreInfo *ping_semaphore = (SemaphoreInfo *) NULL; # endif #endif /* This temporary until I set up malloc'ed object attributes array. Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but waste more memory. */ #define MNG_MAX_OBJECTS 256 /* If this not defined, spec is interpreted strictly. If it is defined, an attempt will be made to recover from some errors, including o global PLTE too short */ #undef MNG_LOOSE /* Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8, PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here. PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and will be enabled by default in libpng-1.2.0. */ #ifdef PNG_MNG_FEATURES_SUPPORTED # ifndef PNG_READ_EMPTY_PLTE_SUPPORTED # define PNG_READ_EMPTY_PLTE_SUPPORTED # endif # ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED # define PNG_WRITE_EMPTY_PLTE_SUPPORTED # endif #endif /* Maximum valid size_t in PNG/MNG chunks is (2^31)-1 This macro is only defined in libpng-1.0.3 and later. Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6 */ #ifndef PNG_UINT_31_MAX #define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL #endif /* Constant strings for known chunk types. If you need to add a chunk, add a string holding the name here. To make the code more portable, we use ASCII numbers like this, not characters. */ /* until registration of eXIf */ static const png_byte mng_exIf[5]={101, 120, 73, 102, (png_byte) '\0'}; /* after registration of eXIf */ static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'}; static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'}; static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'}; static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'}; static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'}; static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'}; static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'}; static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'}; static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'}; static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'}; static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'}; static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'}; static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'}; static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'}; static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'}; static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'}; static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'}; static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'}; static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'}; static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'}; static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'}; static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'}; static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'}; static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'}; static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'}; static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'}; static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'}; static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'}; static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'}; static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'}; #if defined(JNG_SUPPORTED) static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'}; static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'}; static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'}; static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'}; #endif #if 0 /* Other known chunks that are not yet supported by ImageMagick: */ static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'}; static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'}; static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'}; static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'}; static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'}; static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'}; static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'}; #endif typedef struct _MngBox { long left, right, top, bottom; } MngBox; typedef struct _MngPair { volatile long a, b; } MngPair; #ifdef MNG_OBJECT_BUFFERS typedef struct _MngBuffer { size_t height, width; Image *image; png_color plte[256]; int reference_count; unsigned char alpha_sample_depth, compression_method, color_type, concrete, filter_method, frozen, image_type, interlace_method, pixel_sample_depth, plte_length, sample_depth, viewable; } MngBuffer; #endif typedef struct _MngInfo { #ifdef MNG_OBJECT_BUFFERS MngBuffer *ob[MNG_MAX_OBJECTS]; #endif Image * image; RectangleInfo page; int adjoin, #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED bytes_in_read_buffer, found_empty_plte, #endif equal_backgrounds, equal_chrms, equal_gammas, #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) equal_palettes, #endif equal_physs, equal_srgbs, framing_mode, have_global_bkgd, have_global_chrm, have_global_gama, have_global_phys, have_global_sbit, have_global_srgb, have_saved_bkgd_index, have_write_global_chrm, have_write_global_gama, have_write_global_plte, have_write_global_srgb, need_fram, object_id, old_framing_mode, saved_bkgd_index; int new_number_colors; ssize_t image_found, loop_count[256], loop_iteration[256], scenes_found, x_off[MNG_MAX_OBJECTS], y_off[MNG_MAX_OBJECTS]; MngBox clip, frame, image_box, object_clip[MNG_MAX_OBJECTS]; unsigned char /* These flags could be combined into one byte */ exists[MNG_MAX_OBJECTS], frozen[MNG_MAX_OBJECTS], loop_active[256], invisible[MNG_MAX_OBJECTS], viewable[MNG_MAX_OBJECTS]; MagickOffsetType loop_jump[256]; png_colorp global_plte; png_color_8 global_sbit; png_byte #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED read_buffer[8], #endif global_trns[256]; float global_gamma; ChromaticityInfo global_chrm; RenderingIntent global_srgb_intent; unsigned int delay, global_plte_length, global_trns_length, global_x_pixels_per_unit, global_y_pixels_per_unit, mng_width, mng_height, ticks_per_second; MagickBooleanType need_blob; unsigned int IsPalette, global_phys_unit_type, basi_warning, clon_warning, dhdr_warning, jhdr_warning, magn_warning, past_warning, phyg_warning, phys_warning, sbit_warning, show_warning, mng_type, write_mng, write_png_colortype, write_png_depth, write_png_compression_level, write_png_compression_strategy, write_png_compression_filter, write_png8, write_png24, write_png32, write_png48, write_png64; #ifdef MNG_BASI_SUPPORTED size_t basi_width, basi_height; unsigned int basi_depth, basi_color_type, basi_compression_method, basi_filter_type, basi_interlace_method, basi_red, basi_green, basi_blue, basi_alpha, basi_viewable; #endif png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; PixelPacket mng_global_bkgd; /* Added at version 6.6.6-7 */ MagickBooleanType ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, ping_exclude_eXIf, ping_exclude_EXIF, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tRNS, ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, /* Added at version 6.8.5-7 */ ping_preserve_iCCP, /* Added at version 6.8.9-9 */ ping_exclude_tIME; } MngInfo; #endif /* VER */ /* Forward declarations. */ static MagickBooleanType WritePNGImage(const ImageInfo *,Image *); static MagickBooleanType WriteMNGImage(const ImageInfo *,Image *); #if defined(JNG_SUPPORTED) static MagickBooleanType WriteJNGImage(const ImageInfo *,Image *); #endif #if PNG_LIBPNG_VER > 10011 #if (MAGICKCORE_QUANTUM_DEPTH >= 16) static MagickBooleanType LosslessReduceDepthOK(Image *image) { /* Reduce bit depth if it can be reduced losslessly from 16+ to 8. * * This is true if the high byte and the next highest byte of * each sample of the image, the colormap, and the background color * are equal to each other. We check this by seeing if the samples * are unchanged when we scale them down to 8 and back up to Quantum. * * We don't use the method GetImageDepth() because it doesn't check * background and doesn't handle PseudoClass specially. */ #define QuantumToCharToQuantumEqQuantum(quantum) \ ((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum) MagickBooleanType ok_to_reduce=MagickFalse; if (image->depth >= 16) { const PixelPacket *p; ok_to_reduce= QuantumToCharToQuantumEqQuantum(image->background_color.red) && QuantumToCharToQuantumEqQuantum(image->background_color.green) && QuantumToCharToQuantumEqQuantum(image->background_color.blue) ? MagickTrue : MagickFalse; if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass) { int indx; for (indx=0; indx < (ssize_t) image->colors; indx++) { ok_to_reduce=( QuantumToCharToQuantumEqQuantum( image->colormap[indx].red) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].green) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].blue)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; } } if ((ok_to_reduce != MagickFalse) && (image->storage_class != PseudoClass)) { ssize_t y; register ssize_t x; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) { ok_to_reduce = MagickFalse; break; } for (x=(ssize_t) image->columns-1; x >= 0; x--) { ok_to_reduce= QuantumToCharToQuantumEqQuantum(GetPixelRed(p)) && QuantumToCharToQuantumEqQuantum(GetPixelGreen(p)) && QuantumToCharToQuantumEqQuantum(GetPixelBlue(p)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; p++; } if (x >= 0) break; } } if (ok_to_reduce != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " OK to reduce PNG bit depth to 8 without loss of info"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Not OK to reduce PNG bit depth to 8 without loss of info"); } } return ok_to_reduce; } #endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */ static const char* PngColorTypeToString(const unsigned int color_type) { const char *result = "Unknown"; switch (color_type) { case PNG_COLOR_TYPE_GRAY: result = "Gray"; break; case PNG_COLOR_TYPE_GRAY_ALPHA: result = "Gray+Alpha"; break; case PNG_COLOR_TYPE_PALETTE: result = "Palette"; break; case PNG_COLOR_TYPE_RGB: result = "RGB"; break; case PNG_COLOR_TYPE_RGB_ALPHA: result = "RGB+Alpha"; break; } return result; } static int Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent) { switch (intent) { case PerceptualIntent: return 0; case RelativeIntent: return 1; case SaturationIntent: return 2; case AbsoluteIntent: return 3; default: return -1; } } static RenderingIntent Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return PerceptualIntent; case 1: return RelativeIntent; case 2: return SaturationIntent; case 3: return AbsoluteIntent; default: return UndefinedIntent; } } static const char * Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return "Perceptual Intent"; case 1: return "Relative Intent"; case 2: return "Saturation Intent"; case 3: return "Absolute Intent"; default: return "Undefined Intent"; } } static const char * Magick_ColorType_from_PNG_ColorType(const int ping_colortype) { switch (ping_colortype) { case 0: return "Grayscale"; case 2: return "Truecolor"; case 3: return "Indexed"; case 4: return "GrayAlpha"; case 6: return "RGBA"; default: return "UndefinedColorType"; } } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* MAGICKCORE_PNG_DELEGATE */ /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMNG() returns MagickTrue if the image format type, identified by the % magick string, is MNG. % % The format of the IsMNG method is: % % MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJNG() returns MagickTrue if the image format type, identified by the % magick string, is JNG. % % The format of the IsJNG method is: % % MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNG() returns MagickTrue if the image format type, identified by the % magick string, is PNG. % % The format of the IsPNG method is: % % MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_PNG_DELEGATE) #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if (PNG_LIBPNG_VER > 10011) static size_t WriteBlobMSBULong(Image *image,const size_t value) { unsigned char buffer[4]; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; return((size_t) WriteBlob(image,4,buffer)); } static void PNGLong(png_bytep p,png_uint_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGsLong(png_bytep p,png_int_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGShort(png_bytep p,png_uint_16 value) { *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGType(png_bytep p,const png_byte *type) { (void) CopyMagickMemory(p,type,4*sizeof(png_byte)); } static void LogPNGChunk(MagickBooleanType logging, const png_byte *type, size_t length) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing %c%c%c%c chunk, length: %.20g", type[0],type[1],type[2],type[3],(double) length); } #endif /* PNG_LIBPNG_VER > 10011 */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNGImage() reads a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image or set of images. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadPNGImage method is: % % Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % % To do, more or less in chronological order (as of version 5.5.2, % November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage): % % Get 16-bit cheap transparency working. % % (At this point, PNG decoding is supposed to be in full MNG-LC compliance) % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % (At this point, PNG encoding should be in full MNG compliance) % % Provide options for choice of background to use when the MNG BACK % chunk is not present or is not mandatory (i.e., leave transparent, % user specified, MNG BACK, PNG bKGD) % % Implement LOOP/ENDL [done, but could do discretionary loops more % efficiently by linking in the duplicate frames.]. % % Decode and act on the MHDR simplicity profile (offer option to reject % files or attempt to process them anyway when the profile isn't LC or VLC). % % Upgrade to full MNG without Delta-PNG. % % o BACK [done a while ago except for background image ID] % o MOVE [done 15 May 1999] % o CLIP [done 15 May 1999] % o DISC [done 19 May 1999] % o SAVE [partially done 19 May 1999 (marks objects frozen)] % o SEEK [partially done 19 May 1999 (discard function only)] % o SHOW % o PAST % o BASI % o MNG-level tEXt/iTXt/zTXt % o pHYg % o pHYs % o sBIT % o bKGD % o iTXt (wait for libpng implementation). % % Use the scene signature to discover when an identical scene is % being reused, and just point to the original image->exception instead % of storing another set of pixels. This not specific to MNG % but could be applied generally. % % Upgrade to full MNG with Delta-PNG. % % JNG tEXt/iTXt/zTXt % % We will not attempt to read files containing the CgBI chunk. % They are really Xcode files meant for display on the iPhone. % These are not valid PNG files and it is impossible to recover % the original PNG from files that have been converted to Xcode-PNG, % since irretrievable loss of color data has occurred due to the % use of premultiplied alpha. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* This the function that does the actual reading of data. It is the same as the one supplied in libpng, except that it receives the datastream from the ReadBlob() function instead of standard input. */ static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) ReadBlob(image,(size_t) length,data); if (check != length) { char msg[MaxTextExtent]; (void) FormatLocaleString(msg,MaxTextExtent, "Expected %.20g bytes; found %.20g bytes",(double) length, (double) check); png_warning(png_ptr,msg); png_error(png_ptr,"Read Exception"); } } } #if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \ !defined(PNG_MNG_FEATURES_SUPPORTED) /* We use mng_get_data() instead of png_get_data() if we have a libpng * older than libpng-1.0.3a, which was the first to allow the empty * PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was * ifdef'ed out. Earlier versions would crash if the bKGD chunk was * encountered after an empty PLTE, so we have to look ahead for bKGD * chunks and remove them from the datastream that is passed to libpng, * and store their contents for later use. */ static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { MngInfo *mng_info; Image *image; png_size_t check; register ssize_t i; i=0; mng_info=(MngInfo *) png_get_io_ptr(png_ptr); image=(Image *) mng_info->image; while (mng_info->bytes_in_read_buffer && length) { data[i]=mng_info->read_buffer[i]; mng_info->bytes_in_read_buffer--; length--; i++; } if (length != 0) { check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data); if (check != length) png_error(png_ptr,"Read Exception"); if (length == 4) { if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 0)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0) mng_info->found_empty_plte=MagickTrue; if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0) { mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; } } if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 1)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0) if (mng_info->found_empty_plte) { /* Skip the bKGD data byte and CRC. */ check=(png_size_t) ReadBlob(image,5,(char *) mng_info->read_buffer); check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->saved_bkgd_index=mng_info->read_buffer[0]; mng_info->have_saved_bkgd_index=MagickTrue; mng_info->bytes_in_read_buffer=0; } } } } } #endif static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) WriteBlob(image,(size_t) length,data); if (check != length) png_error(png_ptr,"WriteBlob Failed"); } } static void png_flush_data(png_structp png_ptr) { (void) png_ptr; } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED static int PalettesAreEqual(Image *a,Image *b) { ssize_t i; if ((a == (Image *) NULL) || (b == (Image *) NULL)) return((int) MagickFalse); if (a->storage_class != PseudoClass || b->storage_class != PseudoClass) return((int) MagickFalse); if (a->colors != b->colors) return((int) MagickFalse); for (i=0; i < (ssize_t) a->colors; i++) { if ((a->colormap[i].red != b->colormap[i].red) || (a->colormap[i].green != b->colormap[i].green) || (a->colormap[i].blue != b->colormap[i].blue)) return((int) MagickFalse); } return((int) MagickTrue); } #endif static void MngInfoDiscardObject(MngInfo *mng_info,int i) { if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) && mng_info->exists[i] && !mng_info->frozen[i]) { #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) { if (mng_info->ob[i]->reference_count > 0) mng_info->ob[i]->reference_count--; if (mng_info->ob[i]->reference_count == 0) { if (mng_info->ob[i]->image != (Image *) NULL) mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image); mng_info->ob[i]=DestroyString(mng_info->ob[i]); } } mng_info->ob[i]=(MngBuffer *) NULL; #endif mng_info->exists[i]=MagickFalse; mng_info->invisible[i]=MagickFalse; mng_info->viewable[i]=MagickFalse; mng_info->frozen[i]=MagickFalse; mng_info->x_off[i]=0; mng_info->y_off[i]=0; mng_info->object_clip[i].left=0; mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].top=0; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } } static MngInfo *MngInfoFreeStruct(MngInfo *mng_info) { register ssize_t i; if (mng_info == (MngInfo *) NULL) return((MngInfo *) NULL); for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); if (mng_info->global_plte != (png_colorp) NULL) mng_info->global_plte=(png_colorp) RelinquishMagickMemory(mng_info->global_plte); return((MngInfo *) RelinquishMagickMemory(mng_info)); } static MngBox mng_minimum_box(MngBox box1,MngBox box2) { MngBox box; box=box1; if (box.left < box2.left) box.left=box2.left; if (box.top < box2.top) box.top=box2.top; if (box.right > box2.right) box.right=box2.right; if (box.bottom > box2.bottom) box.bottom=box2.bottom; return box; } static MngBox mng_read_box(MngBox previous_box,char delta_type,unsigned char *p) { MngBox box; /* Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk. */ box.left=(ssize_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); box.right=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); box.top=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); box.bottom=(ssize_t) ((p[12] << 24) | (p[13] << 16) | (p[14] << 8) | p[15]); if (delta_type != 0) { box.left+=previous_box.left; box.right+=previous_box.right; box.top+=previous_box.top; box.bottom+=previous_box.bottom; } return(box); } static MngPair mng_read_pair(MngPair previous_pair,int delta_type, unsigned char *p) { MngPair pair; /* Read two ssize_ts from CLON, MOVE or PAST chunk */ pair.a=(long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); pair.b=(long) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (delta_type != 0) { pair.a+=previous_pair.a; pair.b+=previous_pair.b; } return(pair); } static long mng_get_long(unsigned char *p) { return((long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3])); } typedef struct _PNGErrorInfo { Image *image; ExceptionInfo *exception; } PNGErrorInfo; static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message) { Image *image; image=(Image *) png_get_error_ptr(ping); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s error: %s", PNG_LIBPNG_VER_STRING,message); (void) ThrowMagickException(&image->exception,GetMagickModule(),CoderError, message,"`%s'",image->filename); #if (PNG_LIBPNG_VER < 10500) /* A warning about deprecated use of jmpbuf here is unavoidable if you * are building with libpng-1.4.x and can be ignored. */ longjmp(ping->jmpbuf,1); #else png_longjmp(ping,1); #endif } static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message) { Image *image; if (LocaleCompare(message, "Missing PLTE before tRNS") == 0) png_error(ping, message); image=(Image *) png_get_error_ptr(ping); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s warning: %s", PNG_LIBPNG_VER_STRING,message); (void) ThrowMagickException(&image->exception,GetMagickModule(),CoderWarning, message,"`%s'",image->filename); } #ifdef PNG_USER_MEM_SUPPORTED #if PNG_LIBPNG_VER >= 10400 static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size) #else static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size) #endif { (void) png_ptr; return((png_voidp) AcquireMagickMemory((size_t) size)); } /* Free a pointer. It is removed from the list at the same time. */ static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr) { (void) png_ptr; ptr=RelinquishMagickMemory(ptr); return((png_free_ptr) NULL); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static int Magick_png_read_raw_profile(png_struct *ping,Image *image, const ImageInfo *image_info, png_textp text,int ii) { register ssize_t i; register unsigned char *dp; register png_charp sp; png_uint_32 length, nibbles; StringInfo *profile; const unsigned char unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12, 13,14,15}; sp=text[ii].text+1; /* look for newline */ while (*sp != '\n') sp++; /* look for length */ while (*sp == '\0' || *sp == ' ' || *sp == '\n') sp++; length=(png_uint_32) StringToLong(sp); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu",(unsigned long) length); while (*sp != ' ' && *sp != '\n') sp++; /* allocate space */ if (length == 0) { png_warning(ping,"invalid profile length"); return(MagickFalse); } profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { png_warning(ping, "unable to copy profile"); return(MagickFalse); } /* copy profile, skipping white space and column 1 "=" signs */ dp=GetStringInfoDatum(profile); nibbles=length*2; for (i=0; i < (ssize_t) nibbles; i++) { while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f') { if (*sp == '\0') { png_warning(ping, "ran out of profile data"); return(MagickFalse); } sp++; } if (i%2 == 0) *dp=(unsigned char) (16*unhex[(int) *sp++]); else (*dp++)+=unhex[(int) *sp++]; } /* We have already read "Raw profile type. */ (void) SetImageProfile(image,&text[ii].key[17],profile); profile=DestroyStringInfo(profile); if (image_info->verbose) (void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]); return MagickTrue; } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk) { Image *image; /* The unknown chunk structure contains the chunk data: png_byte name[5]; png_byte *data; png_size_t size; Note that libpng has already taken care of the CRC handling. */ LogMagickEvent(CoderEvent,GetMagickModule(), " read_user_chunk: found %c%c%c%c chunk", chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]); if (chunk->name[0] == 101 && (chunk->name[1] == 88 || chunk->name[1] == 120 ) && chunk->name[2] == 73 && chunk-> name[3] == 102) { /* process eXIf or exIf chunk */ PNGErrorInfo *error_info; StringInfo *profile; unsigned char *p; png_byte *s; int i; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " recognized eXIf|exIf chunk"); image=(Image *) png_get_user_chunk_ptr(ping); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); profile=BlobToStringInfo((const void *) NULL,chunk->size+6); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(error_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1); } p=GetStringInfoDatum(profile); /* Initialize profile with "Exif\0\0" */ *p++ ='E'; *p++ ='x'; *p++ ='i'; *p++ ='f'; *p++ ='\0'; *p++ ='\0'; /* copy chunk->data to profile */ s=chunk->data; for (i=0; i < (ssize_t) chunk->size; i++) *p++ = *s++; (void) SetImageProfile(image,"exif",profile); return(1); } /* vpAg (deprecated, replaced by caNv) */ if (chunk->name[0] == 118 && chunk->name[1] == 112 && chunk->name[2] == 65 && chunk->name[3] == 103) { /* recognized vpAg */ if (chunk->size != 9) return(-1); /* Error return */ if (chunk->data[8] != 0) return(0); /* ImageMagick requires pixel units */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); return(1); } /* caNv */ if (chunk->name[0] == 99 && chunk->name[1] == 97 && chunk->name[2] == 78 && chunk->name[3] == 118) { /* recognized caNv */ if (chunk->size != 16) return(-1); /* Error return */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); image->page.x=(size_t) ((chunk->data[8] << 24) | (chunk->data[9] << 16) | (chunk->data[10] << 8) | chunk->data[11]); image->page.y=(size_t) ((chunk->data[12] << 24) | (chunk->data[13] << 16) | (chunk->data[14] << 8) | chunk->data[15]); /* Return one of the following: */ /* return(-n); chunk had an error */ /* return(0); did not recognize */ /* return(n); success */ return(1); } return(0); /* Did not recognize */ } #endif #if defined(PNG_tIME_SUPPORTED) static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info) { png_timep time; if (png_get_tIME(ping,info,&time)) { char timestamp[21]; FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ", time->year,time->month,time->day,time->hour,time->minute,time->second); SetImageProperty(image,"png:tIME",timestamp); } } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the ReadOnePNGImage method is: % % Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { /* Read one PNG image */ /* To do: Read the tEXt/Creation Time chunk into the date:create property */ Image *image; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; int intent, /* "PNG Rendering intent", which is ICC intent + 1 */ num_raw_profiles, num_text, num_text_total, num_passes, number_colors, pass, ping_bit_depth, ping_color_type, ping_file_depth, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans, unit_type; double file_gamma; LongPixelPacket transparent_color; MagickBooleanType logging, ping_found_cHRM, ping_found_gAMA, ping_found_iCCP, ping_found_sRGB, ping_found_sRGB_cHRM, ping_preserve_iCCP, status; MemoryInfo *volatile pixel_info; png_bytep ping_trans_alpha; png_color_16p ping_background, ping_trans_color; png_info *end_info, *ping_info; png_struct *ping; png_textp text; png_uint_32 ping_height, ping_width, x_resolution, y_resolution; ssize_t ping_rowbytes, y; register unsigned char *p; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; size_t length, row_offset; ssize_t j; unsigned char *ping_pixels; #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED png_byte unused_chunks[]= { 104, 73, 83, 84, (png_byte) '\0', /* hIST */ 105, 84, 88, 116, (png_byte) '\0', /* iTXt */ 112, 67, 65, 76, (png_byte) '\0', /* pCAL */ 115, 67, 65, 76, (png_byte) '\0', /* sCAL */ 115, 80, 76, 84, (png_byte) '\0', /* sPLT */ #if !defined(PNG_tIME_SUPPORTED) 116, 73, 77, 69, (png_byte) '\0', /* tIME */ #endif #ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */ /* ignore the APNG chunks */ 97, 99, 84, 76, (png_byte) '\0', /* acTL */ 102, 99, 84, 76, (png_byte) '\0', /* fcTL */ 102, 100, 65, 84, (png_byte) '\0', /* fdAT */ #endif }; #endif /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,32); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,32); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOnePNGImage()\n" " IM version = %s\n" " Libpng version = %s", im_vers, libpng_vers); if (logging != MagickFalse) { if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif #if (PNG_LIBPNG_VER >= 10400) # ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */ if (image_info->verbose) { printf("Your PNG library (libpng-%s) is an old beta version.\n", PNG_LIBPNG_VER_STRING); printf("Please update it.\n"); } # endif #endif image=mng_info->image; if (logging != MagickFalse) { (void)LogMagickEvent(CoderEvent,GetMagickModule(), " Before reading:\n" " image->matte=%d\n" " image->rendering_intent=%d\n" " image->colorspace=%d\n" " image->gamma=%f", (int) image->matte, (int) image->rendering_intent, (int) image->colorspace, image->gamma); } intent=Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent); /* Set to an out-of-range color unless tRNS chunk is present */ transparent_color.red=65537; transparent_color.green=65537; transparent_color.blue=65537; transparent_color.opacity=65537; number_colors=0; num_text = 0; num_text_total = 0; num_raw_profiles = 0; ping_found_cHRM = MagickFalse; ping_found_gAMA = MagickFalse; ping_found_iCCP = MagickFalse; ping_found_sRGB = MagickFalse; ping_found_sRGB_cHRM = MagickFalse; ping_preserve_iCCP = MagickFalse; /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING, image, MagickPNGErrorHandler,MagickPNGWarningHandler, NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } end_info=png_create_info_struct(ping); if (end_info == (png_info *) NULL) { png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG image is corrupt. */ png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() with error."); if (image != (Image *) NULL) InheritException(exception,&image->exception); return(GetFirstImageInList(image)); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for reading. */ mng_info->image_found++; png_set_sig_bytes(ping,8); if (LocaleCompare(image_info->magick,"MNG") == 0) { #if defined(PNG_MNG_FEATURES_SUPPORTED) (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); png_set_read_fn(ping,image,png_get_data); #else #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) png_permit_empty_plte(ping,MagickTrue); png_set_read_fn(ping,image,png_get_data); #else mng_info->image=image; mng_info->bytes_in_read_buffer=0; mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; png_set_read_fn(ping,mng_info,mng_get_data); #endif #endif } else png_set_read_fn(ping,image,png_get_data); { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",value) == MagickFalse) { value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) ping_preserve_iCCP=MagickTrue; #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) /* Don't let libpng check for ICC/sRGB profile because we're going * to do that anyway. This feature was added at libpng-1.6.12. * If logging, go ahead and check and issue a warning as appropriate. */ if (logging == MagickFalse) png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) else { /* Ignore the iCCP chunk */ png_set_keep_unknown_chunks(ping, 1, mng_iCCP, 1); } #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* Ignore unused chunks and all unknown chunks except for exIf, caNv, and vpAg */ # if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */ png_set_keep_unknown_chunks(ping, 2, NULL, 0); # else png_set_keep_unknown_chunks(ping, 1, NULL, 0); # endif png_set_keep_unknown_chunks(ping, 2, mng_exIf, 1); png_set_keep_unknown_chunks(ping, 2, mng_caNv, 1); png_set_keep_unknown_chunks(ping, 2, mng_vpAg, 1); png_set_keep_unknown_chunks(ping, 1, unused_chunks, (int)sizeof(unused_chunks)/5); /* Callback for other unknown chunks */ png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED #if (PNG_LIBPNG_VER >= 10400) /* Limit the size of the chunk storage cache used for sPLT, text, * and unknown chunks. */ png_set_chunk_cache_max(ping, 32767); #endif #endif #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature */ png_set_check_for_invalid_index (ping, 0); #endif #if (PNG_LIBPNG_VER < 10400) # if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \ (PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__) /* Disable thread-unsafe features of pnggccrd */ if (png_access_version_number() >= 10200) { png_uint_32 mmx_disable_mask=0; png_uint_32 asm_flags; mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \ | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \ | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \ | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ); asm_flags=png_get_asm_flags(ping); png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask); } # endif #endif png_read_info(ping,ping_info); /* Read and check IHDR chunk data */ png_get_IHDR(ping,ping_info,&ping_width,&ping_height, &ping_bit_depth,&ping_color_type, &ping_interlace_method,&ping_compression_method, &ping_filter_method); ping_file_depth = ping_bit_depth; /* Swap bytes if requested */ if (ping_file_depth == 16) { const char *value; value=GetImageOption(image_info,"png:swap-bytes"); if (value == NULL) value=GetImageArtifact(image,"png:swap-bytes"); if (value != NULL) png_set_swap(ping); } /* Save bit-depth and color-type in case we later want to write a PNG00 */ { char msg[MaxTextExtent]; (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_color_type); (void) SetImageProperty(image,"png:IHDR.color-type-orig",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_bit_depth); (void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg); } (void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans, &ping_trans_color); (void) png_get_bKGD(ping, ping_info, &ping_background); if (ping_bit_depth < 8) { png_set_packing(ping); ping_bit_depth = 8; } image->depth=ping_bit_depth; image->depth=GetImageQuantumDepth(image,MagickFalse); image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { image->rendering_intent=UndefinedIntent; intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent); (void) ResetMagickMemory(&image->chromaticity,0, sizeof(image->chromaticity)); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG width: %.20g, height: %.20g\n" " PNG color_type: %d, bit_depth: %d\n" " PNG compression_method: %d\n" " PNG interlace_method: %d, filter_method: %d", (double) ping_width, (double) ping_height, ping_color_type, ping_bit_depth, ping_compression_method, ping_interlace_method,ping_filter_method); } if (png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_gAMA)) { ping_found_gAMA=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG gAMA chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { ping_found_cHRM=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG cHRM chunk."); } if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { ping_found_sRGB=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG sRGB chunk."); } #ifdef PNG_READ_iCCP_SUPPORTED if (ping_found_iCCP !=MagickTrue && ping_found_sRGB != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_iCCP)) { int compression; #if (PNG_LIBPNG_VER < 10500) png_charp info; #else png_bytep info; #endif png_charp name; png_uint_32 profile_length; (void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info, &profile_length); if (profile_length != 0) { StringInfo *profile; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG iCCP chunk."); profile=BlobToStringInfo(info,profile_length); if (profile == (StringInfo *) NULL) { png_warning(ping, "ICC profile is NULL"); profile=DestroyStringInfo(profile); } else { if (ping_preserve_iCCP == MagickFalse) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } break; } } } if (sRGB_info[icheck].len == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); (void) SetImageProfile(image,"icc",profile); } } else /* Preserve-iCCP */ { (void) SetImageProfile(image,"icc",profile); } profile=DestroyStringInfo(profile); } } } #endif #if defined(PNG_READ_sRGB_SUPPORTED) { if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { if (png_get_sRGB(ping,ping_info,&intent)) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (intent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG sRGB chunk: rendering_intent: %d",intent); } } else if (mng_info->have_global_srgb) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (mng_info->global_srgb_intent); } } #endif { if (!png_get_gAMA(ping,ping_info,&file_gamma)) if (mng_info->have_global_gama) png_set_gAMA(ping,ping_info,mng_info->global_gamma); if (png_get_gAMA(ping,ping_info,&file_gamma)) { image->gamma=(float) file_gamma; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG gAMA chunk: gamma: %f",file_gamma); } } if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { if (mng_info->have_global_chrm != MagickFalse) { (void) png_set_cHRM(ping,ping_info, mng_info->global_chrm.white_point.x, mng_info->global_chrm.white_point.y, mng_info->global_chrm.red_primary.x, mng_info->global_chrm.red_primary.y, mng_info->global_chrm.green_primary.x, mng_info->global_chrm.green_primary.y, mng_info->global_chrm.blue_primary.x, mng_info->global_chrm.blue_primary.y); } } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { (void) png_get_cHRM(ping,ping_info, &image->chromaticity.white_point.x, &image->chromaticity.white_point.y, &image->chromaticity.red_primary.x, &image->chromaticity.red_primary.y, &image->chromaticity.green_primary.x, &image->chromaticity.green_primary.y, &image->chromaticity.blue_primary.x, &image->chromaticity.blue_primary.y); ping_found_cHRM=MagickTrue; if (image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f) ping_found_sRGB_cHRM=MagickTrue; } if (image->rendering_intent != UndefinedIntent) { if (ping_found_sRGB != MagickTrue && (ping_found_gAMA != MagickTrue || (image->gamma > .45 && image->gamma < .46)) && (ping_found_cHRM != MagickTrue || ping_found_sRGB_cHRM != MagickFalse) && ping_found_iCCP != MagickTrue) { png_set_sRGB(ping,ping_info, Magick_RenderingIntent_to_PNG_RenderingIntent (image->rendering_intent)); file_gamma=1.000f/2.200f; ping_found_sRGB=MagickTrue; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting sRGB as if in input"); } } #if defined(PNG_oFFs_SUPPORTED) if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info); image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info); if (logging != MagickFalse) if (image->page.x || image->page.y) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double) image->page.x,(double) image->page.y); } #endif #if defined(PNG_pHYs_SUPPORTED) if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { if (mng_info->have_global_phys) { png_set_pHYs(ping,ping_info, mng_info->global_x_pixels_per_unit, mng_info->global_y_pixels_per_unit, mng_info->global_phys_unit_type); } } x_resolution=0; y_resolution=0; unit_type=0; if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { /* Set image resolution. */ (void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution, &unit_type); image->x_resolution=(double) x_resolution; image->y_resolution=(double) y_resolution; if (unit_type == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=(double) x_resolution/100.0; image->y_resolution=(double) y_resolution/100.0; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) x_resolution,(double) y_resolution,unit_type); } #endif if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); if ((number_colors == 0) && ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)) { if (mng_info->global_plte_length) { png_set_PLTE(ping,ping_info,mng_info->global_plte, (int) mng_info->global_plte_length); if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS)) if (mng_info->global_trns_length) { if (mng_info->global_trns_length > mng_info->global_plte_length) { png_warning(ping, "global tRNS has more entries than global PLTE"); } else { png_set_tRNS(ping,ping_info,mng_info->global_trns, (int) mng_info->global_trns_length,NULL); } } #ifdef PNG_READ_bKGD_SUPPORTED if ( #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED mng_info->have_saved_bkgd_index || #endif png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { png_color_16 background; #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED if (mng_info->have_saved_bkgd_index) background.index=mng_info->saved_bkgd_index; #endif if (png_get_valid(ping, ping_info, PNG_INFO_bKGD)) background.index=ping_background->index; background.red=(png_uint_16) mng_info->global_plte[background.index].red; background.green=(png_uint_16) mng_info->global_plte[background.index].green; background.blue=(png_uint_16) mng_info->global_plte[background.index].blue; background.gray=(png_uint_16) mng_info->global_plte[background.index].green; png_set_bKGD(ping,ping_info,&background); } #endif } else png_error(ping,"No global PLTE in file"); } } #ifdef PNG_READ_bKGD_SUPPORTED if (mng_info->have_global_bkgd && (!png_get_valid(ping,ping_info,PNG_INFO_bKGD))) image->background_color=mng_info->mng_global_bkgd; if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { unsigned int bkgd_scale; /* Set image background color. * Scale background components to 16-bit, then scale * to quantum depth */ bkgd_scale = 1; if (ping_file_depth == 1) bkgd_scale = 255; else if (ping_file_depth == 2) bkgd_scale = 85; else if (ping_file_depth == 4) bkgd_scale = 17; if (ping_file_depth <= 8) bkgd_scale *= 257; ping_background->red *= bkgd_scale; ping_background->green *= bkgd_scale; ping_background->blue *= bkgd_scale; if (logging != MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d).\n" " bkgd_scale=%d. ping_background=(%d,%d,%d).", ping_background->red,ping_background->green, ping_background->blue, bkgd_scale,ping_background->red, ping_background->green,ping_background->blue); } image->background_color.red= ScaleShortToQuantum(ping_background->red); image->background_color.green= ScaleShortToQuantum(ping_background->green); image->background_color.blue= ScaleShortToQuantum(ping_background->blue); image->background_color.opacity=OpaqueOpacity; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->background_color=(%.20g,%.20g,%.20g).", (double) image->background_color.red, (double) image->background_color.green, (double) image->background_color.blue); } #endif /* PNG_READ_bKGD_SUPPORTED */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { /* Image has a tRNS chunk. */ int max_sample; size_t one=1; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG tRNS chunk."); max_sample = (int) ((one << ping_file_depth) - 1); if ((ping_color_type == PNG_COLOR_TYPE_GRAY && (int)ping_trans_color->gray > max_sample) || (ping_color_type == PNG_COLOR_TYPE_RGB && ((int)ping_trans_color->red > max_sample || (int)ping_trans_color->green > max_sample || (int)ping_trans_color->blue > max_sample))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Ignoring PNG tRNS chunk with out-of-range sample."); png_free_data(ping, ping_info, PNG_FREE_TRNS, 0); png_set_invalid(ping,ping_info,PNG_INFO_tRNS); image->matte=MagickFalse; } else { int scale_to_short; scale_to_short = 65535L/((1UL << ping_file_depth)-1); /* Scale transparent_color to short */ transparent_color.red= scale_to_short*ping_trans_color->red; transparent_color.green= scale_to_short*ping_trans_color->green; transparent_color.blue= scale_to_short*ping_trans_color->blue; transparent_color.opacity= scale_to_short*ping_trans_color->gray; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Raw tRNS graylevel = %d, scaled graylevel = %d.", ping_trans_color->gray,transparent_color.opacity); } transparent_color.red=transparent_color.opacity; transparent_color.green=transparent_color.opacity; transparent_color.blue=transparent_color.opacity; } } } #if defined(PNG_READ_sBIT_SUPPORTED) if (mng_info->have_global_sbit) { if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT)) png_set_sBIT(ping,ping_info,&mng_info->global_sbit); } #endif num_passes=png_set_interlace_handling(ping); png_read_update_info(ping,ping_info); ping_rowbytes=png_get_rowbytes(ping,ping_info); /* Initialize image structure. */ mng_info->image_box.left=0; mng_info->image_box.right=(ssize_t) ping_width; mng_info->image_box.top=0; mng_info->image_box.bottom=(ssize_t) ping_height; if (mng_info->mng_type == 0) { mng_info->mng_width=ping_width; mng_info->mng_height=ping_height; mng_info->frame=mng_info->image_box; mng_info->clip=mng_info->image_box; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } image->compression=ZipCompression; image->columns=ping_width; image->rows=ping_height; if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || ((int) ping_bit_depth < 16 && (int) ping_color_type == PNG_COLOR_TYPE_GRAY)) { size_t one; image->storage_class=PseudoClass; one=1; image->colors=one << ping_file_depth; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->colors > 256) image->colors=256; #else if (image->colors > 65536L) image->colors=65536L; #endif if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); image->colors=(size_t) number_colors; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG PLTE chunk: number_colors: %d.",number_colors); } } if (image->storage_class == PseudoClass) { /* Initialize image colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) png_error(ping,"Memory allocation failed"); if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); for (i=0; i < (ssize_t) number_colors; i++) { image->colormap[i].red=ScaleCharToQuantum(palette[i].red); image->colormap[i].green=ScaleCharToQuantum(palette[i].green); image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue); } for ( ; i < (ssize_t) image->colors; i++) { image->colormap[i].red=0; image->colormap[i].green=0; image->colormap[i].blue=0; } } else { Quantum scale; scale = 65535/((1UL << ping_file_depth)-1); #if (MAGICKCORE_QUANTUM_DEPTH > 16) scale = ScaleShortToQuantum(scale); #endif for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(Quantum) (i*scale); image->colormap[i].green=(Quantum) (i*scale); image->colormap[i].blue=(Quantum) (i*scale); } } } /* Set some properties for reporting by "identify" */ { char msg[MaxTextExtent]; /* encode ping_width, ping_height, ping_file_depth, ping_color_type, ping_interlace_method in value */ (void) FormatLocaleString(msg,MaxTextExtent, "%d, %d",(int) ping_width, (int) ping_height); (void) SetImageProperty(image,"png:IHDR.width,height",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_file_depth); (void) SetImageProperty(image,"png:IHDR.bit_depth",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d (%s)", (int) ping_color_type, Magick_ColorType_from_PNG_ColorType((int)ping_color_type)); (void) SetImageProperty(image,"png:IHDR.color_type",msg); if (ping_interlace_method == 0) { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Not interlaced)", (int) ping_interlace_method); } else if (ping_interlace_method == 1) { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Adam7 method)", (int) ping_interlace_method); } else { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Unknown method)", (int) ping_interlace_method); } (void) SetImageProperty(image,"png:IHDR.interlace_method",msg); if (number_colors != 0) { (void) FormatLocaleString(msg,MaxTextExtent,"%d", (int) number_colors); (void) SetImageProperty(image,"png:PLTE.number_colors",msg); } } #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,ping_info); #endif /* Read image scanlines. */ if (image->delay != 0) mng_info->scenes_found++; if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || ( (image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)))) { /* This happens later in non-ping decodes */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) image->storage_class=DirectClass; image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping PNG image data for scene %.20g",(double) mng_info->scenes_found-1); png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()."); return(image); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG IDAT chunk(s)"); if (num_passes > 1) pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes* sizeof(*ping_pixels)); else pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Memory allocation failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting PNG pixels to pixel packets"); /* Convert PNG pixels to pixel packets. */ { MagickBooleanType found_transparent_pixel; found_transparent_pixel=MagickFalse; if (image->storage_class == DirectClass) { QuantumInfo *quantum_info; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Failed to allocate quantum_info"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (pass=0; pass < num_passes; pass++) { /* Convert image to DirectClass pixel packets. */ image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; for (y=0; y < (ssize_t) image->rows; y++) { if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; else { if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayAlphaQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBAQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, IndexQuantum,ping_pixels+row_offset,exception); else /* ping_color_type == PNG_COLOR_TYPE_RGB */ (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBQuantum,ping_pixels+row_offset,exception); } if (found_transparent_pixel == MagickFalse) { /* Is there a transparent pixel in the row? */ if (y== 0 && logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Looking for cheap transparent pixel"); for (x=(ssize_t) image->columns-1; x >= 0; x--) { if ((ping_color_type == PNG_COLOR_TYPE_RGBA || ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) && (GetPixelOpacity(q) != OpaqueOpacity)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } if ((ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_GRAY) && (ScaleQuantumToShort(GetPixelRed(q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(q)) == transparent_color.blue)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } q++; } } if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag, (MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); } else /* image->storage_class != DirectClass */ for (pass=0; pass < num_passes; pass++) { Quantum *quantum_scanline; register Quantum *r; /* Convert grayscale image to PseudoClass pixel packets. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting grayscale pixels to pixel packets"); image->matte=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ? MagickTrue : MagickFalse; quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns, (image->matte ? 2 : 1)*sizeof(*quantum_scanline)); if (quantum_scanline == (Quantum *) NULL) png_error(ping,"Memory allocation failed"); for (y=0; y < (ssize_t) image->rows; y++) { Quantum alpha; if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=ping_pixels+row_offset; r=quantum_scanline; switch (ping_bit_depth) { case 8: { if (ping_color_type == 4) for (x=(ssize_t) image->columns-1; x >= 0; x--) { *r++=*p++; /* In image.h, OpaqueOpacity is 0 * TransparentOpacity is QuantumRange * In a PNG datastream, Opaque is QuantumRange * and Transparent is 0. */ alpha=ScaleCharToQuantum((unsigned char)*p++); SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; q++; } else for (x=(ssize_t) image->columns-1; x >= 0; x--) *r++=*p++; break; } case 16: { for (x=(ssize_t) image->columns-1; x >= 0; x--) { #if (MAGICKCORE_QUANTUM_DEPTH >= 16) size_t quantum; if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); *r=ScaleShortToQuantum(quantum); r++; if (ping_color_type == 4) { if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); alpha=ScaleShortToQuantum(quantum); SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; q++; } #else /* MAGICKCORE_QUANTUM_DEPTH == 8 */ *r++=(*p++); p++; /* strip low byte */ if (ping_color_type == 4) { alpha=*p++; SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; p++; q++; } #endif } break; } default: break; } /* Transfer image scanline. */ r=quantum_scanline; for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*r++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline); } image->matte=found_transparent_pixel; if (logging != MagickFalse) { if (found_transparent_pixel != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found transparent pixel"); else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No transparent pixel was found"); ping_color_type&=0x03; } } } if (image->storage_class == PseudoClass) { MagickBooleanType matte; matte=image->matte; image->matte=MagickFalse; (void) SyncImage(image); image->matte=matte; } png_read_end(ping,end_info); if (image_info->number_scenes != 0 && mng_info->scenes_found-1 < (ssize_t) image_info->first_scene && image->delay != 0) { png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); image->colors=2; (void) SetImageBackgroundColor(image); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() early."); return(image); } if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { ClassType storage_class; /* Image has a transparent background. */ storage_class=image->storage_class; image->matte=MagickTrue; /* Balfour fix from imagemagick discourse server, 5 Feb 2010 */ if (storage_class == PseudoClass) { if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { for (x=0; x < ping_num_trans; x++) { image->colormap[x].opacity = ScaleCharToQuantum((unsigned char)(255-ping_trans_alpha[x])); } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY) { for (x=0; x < (int) image->colors; x++) { if (ScaleQuantumToShort(image->colormap[x].red) == transparent_color.opacity) { image->colormap[x].opacity = (Quantum) TransparentOpacity; } } } (void) SyncImage(image); } #if 1 /* Should have already been done above, but glennrp problem P10 * needs this. */ else { for (y=0; y < (ssize_t) image->rows; y++) { image->storage_class=storage_class; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); /* Caution: on a Q8 build, this does not distinguish between * 16-bit colors that differ only in the low byte */ for (x=(ssize_t) image->columns-1; x >= 0; x--) { if (ScaleQuantumToShort(GetPixelRed(q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(q)) == transparent_color.blue) { SetPixelOpacity(q,TransparentOpacity); } #if 0 /* I have not found a case where this is needed. */ else { SetPixelOpacity(q)=(Quantum) OpaqueOpacity; } #endif q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif image->storage_class=DirectClass; } if ((ping_color_type == PNG_COLOR_TYPE_GRAY) || (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { double image_gamma = image->gamma; (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%f",(float) image_gamma); if (image_gamma > 0.75) { /* Set image->rendering_intent to Undefined, * image->colorspace to GRAY, and reset image->chromaticity. */ image->intensity = Rec709LuminancePixelIntensityMethod; SetImageColorspace(image,GRAYColorspace); } else { RenderingIntent save_rendering_intent = image->rendering_intent; ChromaticityInfo save_chromaticity = image->chromaticity; SetImageColorspace(image,GRAYColorspace); image->rendering_intent = save_rendering_intent; image->chromaticity = save_chromaticity; } image->gamma = image_gamma; } (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace=%d",(int) image->colorspace); for (j = 0; j < 2; j++) { if (j == 0) status = png_get_text(ping,ping_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; else status = png_get_text(ping,end_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) for (i=0; i < (ssize_t) num_text; i++) { /* Check for a profile */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG text chunk"); if (strlen(text[i].key) > 16 && memcmp(text[i].key, "Raw profile type ",17) == 0) { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember(text[i].key+17,value) == MagickFalse) { (void) Magick_png_read_raw_profile(ping,image,image_info,text, (int) i); num_raw_profiles++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Read raw profile %s",text[i].key+17); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping raw profile %s",text[i].key+17); } } else { char *value; length=text[i].text_length; value=(char *) AcquireQuantumMemory(length+MaxTextExtent, sizeof(*value)); if (value == (char *) NULL) png_error(ping,"Memory allocation failed"); *value='\0'; (void) ConcatenateMagickString(value,text[i].text,length+2); /* Don't save "density" or "units" property if we have a pHYs * chunk */ if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) || (LocaleCompare(text[i].key,"density") != 0 && LocaleCompare(text[i].key,"units") != 0)) (void) SetImageProperty(image,text[i].key,value); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu\n" " Keyword: %s", (unsigned long) length, text[i].key); } value=DestroyString(value); } } num_text_total += num_text; } #ifdef MNG_OBJECT_BUFFERS /* Store the object if necessary. */ if (object_id && !mng_info->frozen[object_id]) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) { /* create a new object buffer. */ mng_info->ob[object_id]=(MngBuffer *) AcquireMagickMemory(sizeof(MngBuffer)); if (mng_info->ob[object_id] != (MngBuffer *) NULL) { mng_info->ob[object_id]->image=(Image *) NULL; mng_info->ob[object_id]->reference_count=1; } } if ((mng_info->ob[object_id] == (MngBuffer *) NULL) || mng_info->ob[object_id]->frozen) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) png_error(ping,"Memory allocation failed"); if (mng_info->ob[object_id]->frozen) png_error(ping,"Cannot overwrite frozen MNG object buffer"); } else { if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image=DestroyImage (mng_info->ob[object_id]->image); mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue, &image->exception); if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image->file=(FILE *) NULL; else png_error(ping, "Cloning image for object buffer failed"); if (ping_width > 250000L || ping_height > 250000L) png_error(ping,"PNG Image dimensions are too large."); mng_info->ob[object_id]->width=ping_width; mng_info->ob[object_id]->height=ping_height; mng_info->ob[object_id]->color_type=ping_color_type; mng_info->ob[object_id]->sample_depth=ping_bit_depth; mng_info->ob[object_id]->interlace_method=ping_interlace_method; mng_info->ob[object_id]->compression_method= ping_compression_method; mng_info->ob[object_id]->filter_method=ping_filter_method; if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp plte; /* Copy the PLTE to the object buffer. */ png_get_PLTE(ping,ping_info,&plte,&number_colors); mng_info->ob[object_id]->plte_length=number_colors; for (i=0; i < number_colors; i++) { mng_info->ob[object_id]->plte[i]=plte[i]; } } else mng_info->ob[object_id]->plte_length=0; } } #endif /* Set image->matte to MagickTrue if the input colortype supports * alpha or if a valid tRNS chunk is present, no matter whether there * is actual transparency present. */ image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; #if 0 /* I'm not sure what's wrong here but it does not work. */ if (image->matte != MagickFalse) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) SetImageType(image,GrayscaleMatteType); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteMatteType); else (void) SetImageType(image,TrueColorMatteType); } else { if (ping_color_type == PNG_COLOR_TYPE_GRAY) (void) SetImageType(image,GrayscaleType); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteType); else (void) SetImageType(image,TrueColorType); } #endif /* Set more properties for identify to retrieve */ { char msg[MaxTextExtent]; if (num_text_total != 0) { /* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */ (void) FormatLocaleString(msg,MaxTextExtent, "%d tEXt/zTXt/iTXt chunks were found", num_text_total); (void) SetImageProperty(image,"png:text",msg); } if (num_raw_profiles != 0) { (void) FormatLocaleString(msg,MaxTextExtent, "%d were found", num_raw_profiles); (void) SetImageProperty(image,"png:text-encoded profiles",msg); } /* cHRM chunk: */ if (ping_found_cHRM != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found (see Chromaticity, above)"); (void) SetImageProperty(image,"png:cHRM",msg); } /* bKGD chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found (see Background color, above)"); (void) SetImageProperty(image,"png:bKGD",msg); } (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found"); /* iCCP chunk: */ if (ping_found_iCCP != MagickFalse) (void) SetImageProperty(image,"png:iCCP",msg); if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) (void) SetImageProperty(image,"png:tRNS",msg); #if defined(PNG_sRGB_SUPPORTED) /* sRGB chunk: */ if (ping_found_sRGB != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent, "intent=%d (%s)", (int) intent, Magick_RenderingIntentString_from_PNG_RenderingIntent(intent)); (void) SetImageProperty(image,"png:sRGB",msg); } #endif /* gAMA chunk: */ if (ping_found_gAMA != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent, "gamma=%.8g (See Gamma, above)", file_gamma); (void) SetImageProperty(image,"png:gAMA",msg); } #if defined(PNG_pHYs_SUPPORTED) /* pHYs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { (void) FormatLocaleString(msg,MaxTextExtent, "x_res=%.10g, y_res=%.10g, units=%d", (double) x_resolution,(double) y_resolution, unit_type); (void) SetImageProperty(image,"png:pHYs",msg); } #endif #if defined(PNG_oFFs_SUPPORTED) /* oFFs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { (void) FormatLocaleString(msg,MaxTextExtent,"x_off=%.20g, y_off=%.20g", (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:oFFs",msg); } #endif #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,end_info); #endif /* caNv chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || (image->page.x != 0 || image->page.y != 0)) { (void) FormatLocaleString(msg,MaxTextExtent, "width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:caNv",msg); } /* vpAg chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { (void) FormatLocaleString(msg,MaxTextExtent, "width=%.20g, height=%.20g", (double) image->page.width,(double) image->page.height); (void) SetImageProperty(image,"png:vpAg",msg); } } /* Relinquish resources. */ png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block, revert to * Throwing an Exception when an error occurs. */ return(image); /* end of reading one PNG image */ } static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; ssize_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) ThrowReaderException(FileOpenError,"UnableToOpenFile"); /* Verify PNG signature. */ count=ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a PNG datastream. */ if (GetBlobSize(image) < 61) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOnePNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if ((image->columns == 0) || (image->rows == 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if ((IssRGBColorspace(image->colorspace) != MagickFalse) && ((image->gamma < .45) || (image->gamma > .46)) && !(image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f)) SetImageColorspace(image,RGBColorspace); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()"); return(image); } #if defined(JNG_SUPPORTED) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadOneJNGImage method is: % % Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) { if (color_image != (Image *) NULL) color_image=DestroyImage(color_image); if (color_image_info != (Image *) NULL) color_image_info=DestroyImageInfo(color_image_info); ThrowReaderException(CorruptImageError,"CorruptImage"); } p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJNGImage() reads a JPEG Network Graphics (JNG) image file % (including the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadJNGImage method is: % % Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo % *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; size_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); if (LocaleCompare(image_info->magick,"JNG") != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify JNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a JNG datastream. */ if (GetBlobSize(image) < 147) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneJNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (image->columns == 0 || image->rows == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); ThrowReaderException(CorruptImageError,"CorruptImage"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()"); return(image); } #endif static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream", "`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, "object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters ", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage();"); return(image); } static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneMNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadMNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()"); return(GetFirstImageInList(image)); } #else /* PNG_LIBPNG_VER > 10011 */ static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "PNG library is too old","`%s'",image_info->filename); return(Image *) NULL; } static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { return(ReadPNGImage(image_info,exception)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNGImage() adds properties for the PNG image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNGImage method is: % % size_t RegisterPNGImage(void) % */ ModuleExport size_t RegisterPNGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char *PNGNote= { "See http://www.libpng.org/ for details about the PNG format." }, *JNGNote= { "See http://www.libpng.org/pub/mng/ for details about the JNG\n" "format." }, *MNGNote= { "See http://www.libpng.org/pub/mng/ for details about the MNG\n" "format." }; *version='\0'; #if defined(PNG_LIBPNG_VER_STRING) (void) ConcatenateMagickString(version,"libpng ",MaxTextExtent); (void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING,MaxTextExtent); if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0) { (void) ConcatenateMagickString(version,",",MaxTextExtent); (void) ConcatenateMagickString(version,png_get_libpng_ver(NULL), MaxTextExtent); } #endif entry=SetMagickInfo("MNG"); entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMNGImage; entry->encoder=(EncodeImageHandler *) WriteMNGImage; #endif entry->magick=(IsImageFormatHandler *) IsMNG; entry->description=ConstantString("Multiple-image Network Graphics"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("video/x-mng"); entry->module=ConstantString("PNG"); entry->note=ConstantString(MNGNote); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("Portable Network Graphics"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); if (*version != '\0') entry->version=ConstantString(version); entry->note=ConstantString(PNGNote); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG8"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString( "8-bit indexed with optional binary transparency"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG24"); *version='\0'; #if defined(ZLIB_VERSION) (void) ConcatenateMagickString(version,"zlib ",MaxTextExtent); (void) ConcatenateMagickString(version,ZLIB_VERSION,MaxTextExtent); if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0) { (void) ConcatenateMagickString(version,",",MaxTextExtent); (void) ConcatenateMagickString(version,zlib_version,MaxTextExtent); } #endif if (*version != '\0') entry->version=ConstantString(version); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or binary transparent 24-bit RGB"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG32"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or transparent 32-bit RGBA"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG48"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or binary transparent 48-bit RGB"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG64"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or transparent 64-bit RGBA"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG00"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString( "PNG inheriting bit-depth, color-type from original if possible"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JNG"); #if defined(JNG_SUPPORTED) #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJNGImage; entry->encoder=(EncodeImageHandler *) WriteJNGImage; #endif #endif entry->magick=(IsImageFormatHandler *) IsJNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("JPEG Network Graphics"); entry->mime_type=ConstantString("image/x-jng"); entry->module=ConstantString("PNG"); entry->note=ConstantString(JNGNote); (void) RegisterMagickInfo(entry); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE ping_semaphore=AllocateSemaphoreInfo(); #endif return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNGImage() removes format registrations made by the % PNG module from the list of supported formats. % % The format of the UnregisterPNGImage method is: % % UnregisterPNGImage(void) % */ ModuleExport void UnregisterPNGImage(void) { (void) UnregisterMagickInfo("MNG"); (void) UnregisterMagickInfo("PNG"); (void) UnregisterMagickInfo("PNG8"); (void) UnregisterMagickInfo("PNG24"); (void) UnregisterMagickInfo("PNG32"); (void) UnregisterMagickInfo("PNG48"); (void) UnregisterMagickInfo("PNG64"); (void) UnregisterMagickInfo("PNG00"); (void) UnregisterMagickInfo("JNG"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE if (ping_semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&ping_semaphore); #endif } #if defined(MAGICKCORE_PNG_DELEGATE) #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMNGImage() writes an image in the Portable Network Graphics % Group's "Multiple-image Network Graphics" encoded image format. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteMNGImage method is: % % MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % % To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also % "To do" under ReadPNGImage): % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % Write the iCCP chunk at MNG level when (icc profile length > 0) % % Improve selection of color type (use indexed-colour or indexed-colour % with tRNS when 256 or fewer unique RGBA values are present). % % Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3) % This will be complicated if we limit ourselves to generating MNG-LC % files. For now we ignore disposal method 3 and simply overlay the next % image on it. % % Check for identical PLTE's or PLTE/tRNS combinations and use a % global MNG PLTE or PLTE/tRNS combination when appropriate. % [mostly done 15 June 1999 but still need to take care of tRNS] % % Check for identical sRGB and replace with a global sRGB (and remove % gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and % replace with global gAMA/cHRM (or with sRGB if appropriate; replace % local gAMA/cHRM with local sRGB if appropriate). % % Check for identical sBIT chunks and write global ones. % % Provide option to skip writing the signature tEXt chunks. % % Use signatures to detect identical objects and reuse the first % instance of such objects instead of writing duplicate objects. % % Use a smaller-than-32k value of compression window size when % appropriate. % % Encode JNG datastreams. Mostly done as of 5.5.2; need to write % ancillary text chunks and save profiles. % % Provide an option to force LC files (to ensure exact framing rate) % instead of VLC. % % Provide an option to force VLC files instead of LC, even when offsets % are present. This will involve expanding the embedded images with a % transparent region at the top and/or left. */ static void Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping, png_info *ping_info, unsigned char *profile_type, unsigned char *profile_description, unsigned char *profile_data, png_uint_32 length) { png_textp text; register ssize_t i; unsigned char *sp; png_charp dp; png_uint_32 allocated_length, description_length; unsigned char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0) return; if (image_info->verbose) { (void) printf("writing raw profile: type=%s, length=%.20g\n", (char *) profile_type, (double) length); } #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif description_length=(png_uint_32) strlen((const char *) profile_description); allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20 + description_length); #if PNG_LIBPNG_VER >= 10400 text[0].text=(png_charp) png_malloc(ping, (png_alloc_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80); #else text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80); #endif text[0].key[0]='\0'; (void) ConcatenateMagickString(text[0].key, "Raw profile type ",MaxTextExtent); (void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62); sp=profile_data; dp=text[0].text; *dp++='\n'; (void) CopyMagickString(dp,(const char *) profile_description, allocated_length); dp+=description_length; *dp++='\n'; (void) FormatLocaleString(dp,allocated_length- (png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length); dp+=8; for (i=0; i < (ssize_t) length; i++) { if (i%36 == 0) *dp++='\n'; *(dp++)=(char) hex[((*sp >> 4) & 0x0f)]; *(dp++)=(char) hex[((*sp++ ) & 0x0f)]; } *dp++='\n'; *dp='\0'; text[0].text_length=(png_size_t) (dp-text[0].text); text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? -1 : 0; if (text[0].text_length <= allocated_length) png_set_text(ping,ping_info,text,1); png_free(ping,text[0].text); png_free(ping,text[0].key); png_free(ping,text); } static MagickBooleanType Magick_png_write_chunk_from_profile(Image *image, const char *string, MagickBooleanType logging) { char *name; const StringInfo *profile; unsigned char *data; png_uint_32 length; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (const StringInfo *) NULL) { StringInfo *ping_profile; if (LocaleNCompare(name,string,11) == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found %s profile",name); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); data[4]=data[3]; data[3]=data[2]; data[2]=data[1]; data[1]=data[0]; (void) WriteBlobMSBULong(image,length-5); /* data length */ (void) WriteBlob(image,length-1,data+1); (void) WriteBlobMSBULong(image,crc32(0,data+1,(uInt) length-1)); ping_profile=DestroyStringInfo(ping_profile); } } name=GetNextImageProfile(image); } return(MagickTrue); } #if defined(PNG_tIME_SUPPORTED) static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info, const char *date) { unsigned int day, hour, minute, month, second, year; png_time ptime; time_t ttime; if (date != (const char *) NULL) { if (sscanf(date,"%d-%d-%dT%d:%d:%dZ",&year,&month,&day,&hour,&minute, &second) != 6) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError, "Invalid date format specified for png:tIME","`%s'", image->filename); return; } ptime.year=(png_uint_16) year; ptime.month=(png_byte) month; ptime.day=(png_byte) day; ptime.hour=(png_byte) hour; ptime.minute=(png_byte) minute; ptime.second=(png_byte) second; } else { time(&ttime); png_convert_from_time_t(&ptime,ttime); } png_set_tIME(ping,info,&ptime); } #endif /* Write one PNG image */ static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { char s[2]; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MaxTextExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MaxTextExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; /* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; */ ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_vpAg=mng_info->ping_exclude_vpAg; ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; property=(const char *) NULL; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->magick= %s",image_info->magick); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register PixelPacket *r; ExceptionInfo *exception; exception=(&image->exception); if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->matte == MagickFalse))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ number_opaque = (int) image->colors; if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; else ping_have_color=MagickTrue; ping_have_non_bw=MagickFalse; if (image->matte != MagickFalse) { number_transparent = 2; number_semitransparent = 1; } else { number_transparent = 0; number_semitransparent = 0; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->matte is MagickFalse, we ignore the opacity channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ ExceptionInfo *exception; int n; PixelPacket opaque[260], semitransparent[260], transparent[260]; register IndexPacket *indexes; register const PixelPacket *s, *q; register PixelPacket *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->matte=%.20g",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,opacity)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } exception=(&image->exception); image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte == MagickFalse || GetPixelOpacity(q) == OpaqueOpacity) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelRGB(q, opaque); opaque[0].opacity=OpaqueOpacity; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(q, opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelRGB(q, opaque+i); opaque[i].opacity=OpaqueOpacity; } } } else if (q->opacity == TransparentOpacity) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelRGBO(q, transparent); ping_trans_color.red= (unsigned short) GetPixelRed(q); ping_trans_color.green= (unsigned short) GetPixelGreen(q); ping_trans_color.blue= (unsigned short) GetPixelBlue(q); ping_trans_color.gray= (unsigned short) GetPixelRed(q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(q, transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelRGBO(q, transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelRGBO(q, semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(q, semitransparent+i) && GetPixelOpacity(q) == semitransparent[i].opacity) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelRGBO(q, semitransparent+i); } } } q++; } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != GetPixelGreen(s) || GetPixelRed(s) != GetPixelBlue(s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s++; } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != 0 && GetPixelRed(s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s++; } } } } } if (image_colors < 257) { PixelPacket colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors) == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->matte == MagickFalse || image->colormap[i].opacity == GetPixelOpacity(q)) && image->colormap[i].red == GetPixelRed(q) && image->colormap[i].green == GetPixelGreen(q) && image->colormap[i].blue == GetPixelBlue(q)) { SetPixelIndex(indexes+x,i); break; } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,opacity)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) > TransparentOpacity/2) { SetPixelOpacity(r,TransparentOpacity); SetPixelRgb(r,&image->background_color); } else SetPixelOpacity(r,OpaqueOpacity); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].opacity = (image->colormap[i].opacity > TransparentOpacity/2 ? TransparentOpacity : OpaqueOpacity); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR04PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR03PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR02PixelBlue(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(r)) == 0x00 && GetPixelOpacity(r) == OpaqueOpacity) { SetPixelRed(r,ScaleCharToQuantum(0x24)); } r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { ExceptionInfo *exception; register const PixelPacket *q; exception=(&image->exception); for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (q->opacity != TransparentOpacity && (unsigned short) GetPixelRed(q) == ping_trans_color.red && (unsigned short) GetPixelGreen(q) == ping_trans_color.green && (unsigned short) GetPixelBlue(q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q++; } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->matte; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",image->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->x_resolution != 0) && (image->y_resolution != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->x_resolution+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->y_resolution+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->x_resolution+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->y_resolution+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->x_resolution; ping_pHYs_y_resolution=(png_uint_32) image->y_resolution; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorMatteType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteMatteType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->matte == MagickFalse && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image, image->colormap))) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) (255- ScaleQuantumToChar(image->colormap[i].opacity)); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)*(ScaleQuantumToShort((Quantum) GetPixelLuma(image,&image->background_color)))+.5); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_background.index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_background.gray is %d", (int) ping_background.gray); } ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This is addressed by using "-define png:compression-strategy", etc., which takes precedence over -quality. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->matte == MagickFalse) { /* Add an opaque matte channel */ image->matte = MagickTrue; (void) SetImageOpacity(image,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { if (mng_info->have_write_global_plte && matte == MagickFalse) { png_set_PLTE(ping,ping_info,NULL,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up empty PLTE chunk"); } else png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(const png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } else #endif if (ping_exclude_zCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXT chunk with uuencoded ICC"); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk with %s profile",name); name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify"); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; (void) ping_have_blob; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } /* write any png-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging); png_write_info(ping,ping_info); /* write any PNG-chunk-m profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging); ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif /* write vpAg chunk (deprecated, replaced by caNv) */ if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { unsigned char chunk[14]; (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } } #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const PixelPacket *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,&image->exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",pass); p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write any PNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging); /* write exIf profile */ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); #if 0 /* eXIf chunk is registered */ PNGType(chunk,mng_eXIf); #else /* eXIf chunk not yet registered; write exIf instead */ PNGType(chunk,mng_exIf); #endif if (length < 7) break; /* othewise crashes */ /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data+6); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data+6, (uInt) length)); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(image,"png:bit-depth-written",s); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNGImage() writes a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WritePNGImage method is: % % MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % Returns MagickTrue on success, MagickFalse on failure. % % Communicating with the PNG encoder: % % While the datastream written is always in PNG format and normally would % be given the "png" file extension, this method also writes the following % pseudo-formats which are subsets of png: % % o PNG8: An 8-bit indexed PNG datastream is written. If the image has % a depth greater than 8, the depth is reduced. If transparency % is present, the tRNS chunk must only have values 0 and 255 % (i.e., transparency is binary: fully opaque or fully % transparent). If other values are present they will be % 50%-thresholded to binary transparency. If more than 256 % colors are present, they will be quantized to the 4-4-4-1, % 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color % of any resulting fully-transparent pixels is changed to % the image's background color. % % If you want better quantization or dithering of the colors % or alpha than that, you need to do it before calling the % PNG encoder. The pixels contain 8-bit indices even if % they could be represented with 1, 2, or 4 bits. Grayscale % images will be written as indexed PNG files even though the % PNG grayscale type might be slightly more efficient. Please % note that writing to the PNG8 format may result in loss % of color and alpha data. % % o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. The only loss incurred % is reduction of sample depth to 8. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG32: An 8-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 255. The alpha % channel is present even if the image is fully opaque. % The only loss in data is the reduction of the sample depth % to 8. % % o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG64: A 16-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 65535. The alpha % channel is present even if the image is fully opaque. % % o PNG00: A PNG that inherits its colortype and bit-depth from the input % image, if the input was a PNG, is written. If these values % cannot be found, or if the pixels have been changed in a way % that makes this impossible, then "PNG00" falls back to the % regular "PNG" format. % % o -define: For more precise control of the PNG output, you can use the % Image options "png:bit-depth" and "png:color-type". These % can be set from the commandline with "-define" and also % from the application programming interfaces. The options % are case-independent and are converted to lowercase before % being passed to this encoder. % % png:color-type can be 0, 2, 3, 4, or 6. % % When png:color-type is 0 (Grayscale), png:bit-depth can % be 1, 2, 4, 8, or 16. % % When png:color-type is 2 (RGB), png:bit-depth can % be 8 or 16. % % When png:color-type is 3 (Indexed), png:bit-depth can % be 1, 2, 4, or 8. This refers to the number of bits % used to store the index. The color samples always have % bit-depth 8 in indexed PNG files. % % When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte), % png:bit-depth can be 8 or 16. % % If the image cannot be written without loss with the % requested bit-depth and color-type, a PNG file will not % be written, a warning will be issued, and the encoder will % return MagickFalse. % % Since image encoders should not be responsible for the "heavy lifting", % the user should make sure that ImageMagick has already reduced the % image depth and number of colors and limit transparency to binary % transparency prior to attempting to write the image with depth, color, % or transparency limitations. % % To do: Enforce the previous paragraph. % % Note that another definition, "png:bit-depth-written" exists, but it % is not intended for external use. It is only used internally by the % PNG encoder to inform the JNG encoder of the depth of the alpha channel. % % It is possible to request that the PNG encoder write previously-formatted % ancillary chunks in the output PNG file, using the "-profile" commandline % option as shown below or by setting the profile via a programming % interface: % % -profile PNG-chunk-x:<file> % % where x is a location flag and <file> is a file containing the chunk % name in the first 4 bytes, then a colon (":"), followed by the chunk data. % This encoder will compute the chunk length and CRC, so those must not % be included in the file. % % "x" can be "b" (before PLTE), "m" (middle, i.e., between PLTE and IDAT), % or "e" (end, i.e., after IDAT). If you want to write multiple chunks % of the same type, then add a short unique string after the "x" to prevent % subsequent profiles from overwriting the preceding ones, e.g., % % -profile PNG-chunk-b01:file01 -profile PNG-chunk-b02:file02 % % As of version 6.6.6 the following optimizations are always done: % % o 32-bit depth is reduced to 16. % o 16-bit depth is reduced to 8 if all pixels contain samples whose % high byte and low byte are identical. % o Palette is sorted to remove unused entries and to put a % transparent color first, if BUILD_PNG_PALETTE is defined. % o Opaque matte channel is removed when writing an indexed PNG. % o Grayscale images are reduced to 1, 2, or 4 bit depth if % this can be done without loss and a larger bit depth N was not % requested via the "-define png:bit-depth=N" option. % o If matte channel is present but only one transparent color is % present, RGB+tRNS is written instead of RGBA % o Opaque matte channel is removed (or added, if color-type 4 or 6 % was requested when converting an opaque image). % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) { MagickBooleanType excluding, logging, status; MngInfo *mng_info; const char *value; int source; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; mng_info->equal_backgrounds=MagickTrue; /* See if user has requested a specific PNG subformat */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0; mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0; value=GetImageOption(image_info,"png:format"); if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0) { mng_info->write_png8 = MagickFalse; mng_info->write_png24 = MagickFalse; mng_info->write_png32 = MagickFalse; mng_info->write_png48 = MagickFalse; mng_info->write_png64 = MagickFalse; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",value); if (LocaleCompare(value,"png8") == 0) mng_info->write_png8 = MagickTrue; else if (LocaleCompare(value,"png24") == 0) mng_info->write_png24 = MagickTrue; else if (LocaleCompare(value,"png32") == 0) mng_info->write_png32 = MagickTrue; else if (LocaleCompare(value,"png48") == 0) mng_info->write_png48 = MagickTrue; else if (LocaleCompare(value,"png64") == 0) mng_info->write_png64 = MagickTrue; else if ((LocaleCompare(value,"png00") == 0) || LocaleCompare(image_info->magick,"PNG00") == 0) { /* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig */ value=GetImageProperty(image,"png:IHDR.bit-depth-orig"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited bit depth=%s",value); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; } value=GetImageProperty(image,"png:IHDR.color-type-orig"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited color type=%s",value); if (value != (char *) NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; } } } if (mng_info->write_png8) { mng_info->write_png_colortype = /* 3 */ 4; mng_info->write_png_depth = 8; image->depth = 8; } if (mng_info->write_png24) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 8; image->depth = 8; if (image->matte != MagickFalse) (void) SetImageType(image,TrueColorMatteType); else (void) SetImageType(image,TrueColorType); (void) SyncImage(image); } if (mng_info->write_png32) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 8; image->depth = 8; image->matte = MagickTrue; (void) SetImageType(image,TrueColorMatteType); (void) SyncImage(image); } if (mng_info->write_png48) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 16; image->depth = 16; if (image->matte != MagickFalse) (void) SetImageType(image,TrueColorMatteType); else (void) SetImageType(image,TrueColorType); (void) SyncImage(image); } if (mng_info->write_png64) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 16; image->depth = 16; image->matte = MagickTrue; (void) SetImageType(image,TrueColorMatteType); (void) SyncImage(image); } value=GetImageOption(image_info,"png:bit-depth"); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:bit-depth", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:bit-depth=%d was defined.\n",mng_info->write_png_depth); } value=GetImageOption(image_info,"png:color-type"); if (value != (char *) NULL) { /* We must store colortype+1 because 0 is a valid colortype */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:color-type", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:color-type=%d was defined.\n",mng_info->write_png_colortype-1); } /* Check for chunks to be excluded: * * The default is to not exclude any known chunks except for any * listed in the "unused_chunks" array, above. * * Chunks can be listed for exclusion via a "png:exclude-chunk" * define (in the image properties or in the image artifacts) * or via a mng_info member. For convenience, in addition * to or instead of a comma-separated list of chunks, the * "exclude-chunk" string can be simply "all" or "none". * * The exclude-chunk define takes priority over the mng_info. * * A "png:include-chunk" define takes priority over both the * mng_info and the "png:exclude-chunk" define. Like the * "exclude-chunk" string, it can define "all" or "none" as * well as a comma-separated list. Chunks that are unknown to * ImageMagick are always excluded, regardless of their "copy-safe" * status according to the PNG specification, and even if they * appear in the "include-chunk" list. Such defines appearing among * the image options take priority over those found among the image * artifacts. * * Finally, all chunks listed in the "unused_chunks" array are * automatically excluded, regardless of the other instructions * or lack thereof. * * if you exclude sRGB but not gAMA (recommended), then sRGB chunk * will not be written and the gAMA chunk will only be written if it * is not between .45 and .46, or approximately (1.0/2.2). * * If you exclude tRNS and the image has transparency, the colortype * is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA). * * The -strip option causes StripImage() to set the png:include-chunk * artifact to "none,trns,gama". */ mng_info->ping_exclude_bKGD=MagickFalse; mng_info->ping_exclude_caNv=MagickFalse; mng_info->ping_exclude_cHRM=MagickFalse; mng_info->ping_exclude_date=MagickFalse; mng_info->ping_exclude_eXIf=MagickFalse; mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */ mng_info->ping_exclude_gAMA=MagickFalse; mng_info->ping_exclude_iCCP=MagickFalse; /* mng_info->ping_exclude_iTXt=MagickFalse; */ mng_info->ping_exclude_oFFs=MagickFalse; mng_info->ping_exclude_pHYs=MagickFalse; mng_info->ping_exclude_sRGB=MagickFalse; mng_info->ping_exclude_tEXt=MagickFalse; mng_info->ping_exclude_tIME=MagickFalse; mng_info->ping_exclude_tRNS=MagickFalse; mng_info->ping_exclude_vpAg=MagickFalse; mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */ mng_info->ping_exclude_zTXt=MagickFalse; mng_info->ping_preserve_colormap=MagickFalse; value=GetImageOption(image_info,"png:preserve-colormap"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-colormap"); if (value != NULL) mng_info->ping_preserve_colormap=MagickTrue; mng_info->ping_preserve_iCCP=MagickFalse; value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) mng_info->ping_preserve_iCCP=MagickTrue; /* These compression-level, compression-strategy, and compression-filter * defines take precedence over values from the -quality option. */ value=GetImageOption(image_info,"png:compression-level"); if (value == NULL) value=GetImageArtifact(image,"png:compression-level"); if (value != NULL) { /* To do: use a "LocaleInteger:()" function here. */ /* We have to add 1 to everything because 0 is a valid input, * and we want to use 0 (the default) to mean undefined. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_level = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_level = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_level = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_level = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_level = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_level = 6; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_compression_level = 7; else if (LocaleCompare(value,"7") == 0) mng_info->write_png_compression_level = 8; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_compression_level = 9; else if (LocaleCompare(value,"9") == 0) mng_info->write_png_compression_level = 10; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-level", "=%s",value); } value=GetImageOption(image_info,"png:compression-strategy"); if (value == NULL) value=GetImageArtifact(image,"png:compression-strategy"); if (value != NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_strategy = Z_FILTERED+1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; else if (LocaleCompare(value,"3") == 0) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy = Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else if (LocaleCompare(value,"4") == 0) #ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */ mng_info->write_png_compression_strategy = Z_FIXED+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-strategy", "=%s",value); } value=GetImageOption(image_info,"png:compression-filter"); if (value == NULL) value=GetImageArtifact(image,"png:compression-filter"); if (value != NULL) { /* To do: combinations of filters allowed by libpng * masks 0x08 through 0xf8 * * Implement this as a comma-separated list of 0,1,2,3,4,5 * where 5 is a special case meaning PNG_ALL_FILTERS. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_filter = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_filter = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_filter = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_filter = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_filter = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_filter = 6; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-filter", "=%s",value); } for (source=0; source<8; source++) { value = NULL; if (source == 0) value=GetImageOption(image_info,"png:exclude-chunks"); if (source == 1) value=GetImageArtifact(image,"png:exclude-chunks"); if (source == 2) value=GetImageOption(image_info,"png:exclude-chunk"); if (source == 3) value=GetImageArtifact(image,"png:exclude-chunk"); if (source == 4) value=GetImageOption(image_info,"png:include-chunks"); if (source == 5) value=GetImageArtifact(image,"png:include-chunks"); if (source == 6) value=GetImageOption(image_info,"png:include-chunk"); if (source == 7) value=GetImageArtifact(image,"png:include-chunk"); if (value == NULL) continue; if (source < 4) excluding = MagickTrue; else excluding = MagickFalse; if (logging != MagickFalse) { if (source == 0 || source == 2) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image options.\n", value); else if (source == 1 || source == 3) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image artifacts.\n", value); else if (source == 4 || source == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image options.\n", value); else /* if (source == 5 || source == 7) */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image artifacts.\n", value); } if (IsOptionMember("all",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding; mng_info->ping_exclude_caNv=excluding; mng_info->ping_exclude_cHRM=excluding; mng_info->ping_exclude_date=excluding; mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; mng_info->ping_exclude_gAMA=excluding; mng_info->ping_exclude_iCCP=excluding; /* mng_info->ping_exclude_iTXt=excluding; */ mng_info->ping_exclude_oFFs=excluding; mng_info->ping_exclude_pHYs=excluding; mng_info->ping_exclude_sRGB=excluding; mng_info->ping_exclude_tIME=excluding; mng_info->ping_exclude_tEXt=excluding; mng_info->ping_exclude_tRNS=excluding; mng_info->ping_exclude_vpAg=excluding; mng_info->ping_exclude_zCCP=excluding; mng_info->ping_exclude_zTXt=excluding; } if (IsOptionMember("none",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; /* mng_info->ping_exclude_iTXt=!excluding; */ mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_vpAg=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse : MagickTrue; } if (IsOptionMember("bkgd",value) != MagickFalse) mng_info->ping_exclude_bKGD=excluding; if (IsOptionMember("caNv",value) != MagickFalse) mng_info->ping_exclude_caNv=excluding; if (IsOptionMember("chrm",value) != MagickFalse) mng_info->ping_exclude_cHRM=excluding; if (IsOptionMember("date",value) != MagickFalse) mng_info->ping_exclude_date=excluding; if (IsOptionMember("exif",value) != MagickFalse) { mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; } if (IsOptionMember("gama",value) != MagickFalse) mng_info->ping_exclude_gAMA=excluding; if (IsOptionMember("iccp",value) != MagickFalse) mng_info->ping_exclude_iCCP=excluding; #if 0 if (IsOptionMember("itxt",value) != MagickFalse) mng_info->ping_exclude_iTXt=excluding; #endif if (IsOptionMember("offs",value) != MagickFalse) mng_info->ping_exclude_oFFs=excluding; if (IsOptionMember("phys",value) != MagickFalse) mng_info->ping_exclude_pHYs=excluding; if (IsOptionMember("srgb",value) != MagickFalse) mng_info->ping_exclude_sRGB=excluding; if (IsOptionMember("text",value) != MagickFalse) mng_info->ping_exclude_tEXt=excluding; if (IsOptionMember("time",value) != MagickFalse) mng_info->ping_exclude_tIME=excluding; if (IsOptionMember("trns",value) != MagickFalse) mng_info->ping_exclude_tRNS=excluding; if (IsOptionMember("vpag",value) != MagickFalse) mng_info->ping_exclude_vpAg=excluding; if (IsOptionMember("zccp",value) != MagickFalse) mng_info->ping_exclude_zCCP=excluding; if (IsOptionMember("ztxt",value) != MagickFalse) mng_info->ping_exclude_zTXt=excluding; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Chunks to be excluded from the output png:"); if (mng_info->ping_exclude_bKGD != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bKGD"); if (mng_info->ping_exclude_caNv != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " caNv"); if (mng_info->ping_exclude_cHRM != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " cHRM"); if (mng_info->ping_exclude_date != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " date"); if (mng_info->ping_exclude_EXIF != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " EXIF"); if (mng_info->ping_exclude_eXIf != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " eXIf"); if (mng_info->ping_exclude_gAMA != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " gAMA"); if (mng_info->ping_exclude_iCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iCCP"); #if 0 if (mng_info->ping_exclude_iTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iTXt"); #endif if (mng_info->ping_exclude_oFFs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " oFFs"); if (mng_info->ping_exclude_pHYs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pHYs"); if (mng_info->ping_exclude_sRGB != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " sRGB"); if (mng_info->ping_exclude_tEXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tEXt"); if (mng_info->ping_exclude_tIME != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tIME"); if (mng_info->ping_exclude_tRNS != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS"); if (mng_info->ping_exclude_vpAg != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " vpAg"); if (mng_info->ping_exclude_zCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zCCP"); if (mng_info->ping_exclude_zTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zTXt"); } mng_info->need_blob = MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image); (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()"); return(status); } #if defined(JNG_SUPPORTED) /* Write one JNG image */ static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { Image *jpeg_image; ImageInfo *jpeg_image_info; int unique_filenames; MagickBooleanType logging, status; size_t length; unsigned char *blob, chunk[80], *p; unsigned int jng_alpha_compression_method, jng_alpha_sample_depth, jng_color_type, transparent; size_t jng_alpha_quality, jng_quality; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOneJNGImage()"); blob=(unsigned char *) NULL; jpeg_image=(Image *) NULL; jpeg_image_info=(ImageInfo *) NULL; length=0; unique_filenames=0; status=MagickTrue; transparent=image_info->type==GrayscaleMatteType || image_info->type==TrueColorMatteType || image->matte != MagickFalse; jng_alpha_sample_depth = 0; jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000; jng_alpha_compression_method=image->compression==JPEGCompression? 8 : 0; jng_alpha_quality=image_info->quality == 0UL ? 75UL : image_info->quality; if (jng_alpha_quality >= 1000) jng_alpha_quality /= 1000; if (transparent != 0) { jng_color_type=14; /* Create JPEG blob, image, and image_info */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info for opacity."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); status=SeparateImageChannel(jpeg_image,OpacityChannel); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=NegateImage(jpeg_image,MagickFalse); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); jpeg_image->matte=MagickFalse; jpeg_image_info->type=GrayscaleType; jpeg_image->quality=jng_alpha_quality; (void) SetImageType(jpeg_image,GrayscaleType); (void) AcquireUniqueFilename(jpeg_image->filename); unique_filenames++; (void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent, "%s",jpeg_image->filename); } else { jng_alpha_compression_method=0; jng_color_type=10; jng_alpha_sample_depth=0; } /* To do: check bit depth of PNG alpha channel */ /* Check if image is grayscale. */ if (image_info->type != TrueColorMatteType && image_info->type != TrueColorType && SetImageGray(image,&image->exception)) jng_color_type-=2; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Quality = %d",(int) jng_quality); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Color Type = %d",jng_color_type); if (transparent != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Compression = %d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Depth = %d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Quality = %d",(int) jng_alpha_quality); } } if (transparent != 0) { if (jng_alpha_compression_method==0) { const char *value; /* Encode opacity as a grayscale PNG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating PNG blob for alpha."); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); length=0; (void) CopyMagickString(jpeg_image_info->magick,"PNG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"PNG",MaxTextExtent); jpeg_image_info->interlace=NoInterlace; /* Exclude all ancillary chunks */ (void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all"); blob=ImageToBlob(jpeg_image_info,jpeg_image,&length, &image->exception); /* Retrieve sample depth used */ value=GetImageProperty(jpeg_image,"png:bit-depth-written"); if (value != (char *) NULL) jng_alpha_sample_depth= (unsigned int) value[0]; } else { /* Encode opacity as a grayscale JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating JPEG blob for alpha."); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); jpeg_image_info->interlace=NoInterlace; blob=ImageToBlob(jpeg_image_info,jpeg_image,&length, &image->exception); jng_alpha_sample_depth=8; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); } /* Destroy JPEG image and image_info */ jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); unique_filenames--; jpeg_image_info=DestroyImageInfo(jpeg_image_info); } /* Write JHDR chunk */ (void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */ PNGType(chunk,mng_JHDR); LogPNGChunk(logging,mng_JHDR,16L); PNGLong(chunk+4,(png_uint_32) image->columns); PNGLong(chunk+8,(png_uint_32) image->rows); chunk[12]=jng_color_type; chunk[13]=8; /* sample depth */ chunk[14]=8; /*jng_image_compression_method */ chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8); chunk[16]=jng_alpha_sample_depth; chunk[17]=jng_alpha_compression_method; chunk[18]=0; /*jng_alpha_filter_method */ chunk[19]=0; /*jng_alpha_interlace_method */ (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width:%15lu",(unsigned long) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG height:%14lu",(unsigned long) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG color type:%10d",jng_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG sample depth:%8d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG compression:%9d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG interlace:%11d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha depth:%9d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha compression:%3d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha filter:%8d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha interlace:%5d",0); } /* Write any JNG-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-b",logging); /* Write leading ancillary chunks */ if (transparent != 0) { /* Write JNG bKGD chunk */ unsigned char blue, green, red; ssize_t num_bytes; if (jng_color_type == 8 || jng_color_type == 12) num_bytes=6L; else num_bytes=10L; (void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L)); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L)); red=ScaleQuantumToChar(image->background_color.red); green=ScaleQuantumToChar(image->background_color.green); blue=ScaleQuantumToChar(image->background_color.blue); *(chunk+4)=0; *(chunk+5)=red; *(chunk+6)=0; *(chunk+7)=green; *(chunk+8)=0; *(chunk+9)=blue; (void) WriteBlob(image,(size_t) num_bytes,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes)); } if ((image->colorspace == sRGBColorspace || image->rendering_intent)) { /* Write JNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { if (image->gamma != 0.0) { /* Write JNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); } if ((mng_info->equal_chrms == MagickFalse) && (image->chromaticity.red_primary.x != 0.0)) { PrimaryInfo primary; /* Write JNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); } } if (image->x_resolution && image->y_resolution && !mng_info->equal_physs) { /* Write JNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.x || image->page.y)) { /* Write JNG oFFs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_oFFs); LogPNGChunk(logging,mng_oFFs,9L); PNGsLong(chunk+4,(ssize_t) (image->page.x)); PNGsLong(chunk+8,(ssize_t) (image->page.y)); chunk[12]=0; (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.width || image->page.height)) { (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (transparent != 0) { if (jng_alpha_compression_method==0) { register ssize_t i; size_t len; /* Write IDAT chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write IDAT chunks from blob, length=%.20g.",(double) length); /* Copy IDAT chunks */ len=0; p=blob+8; for (i=8; i<(ssize_t) length; i+=len+12) { len=(size_t) (*p) << 24; len|=(size_t) (*(p+1)) << 16; len|=(size_t) (*(p+2)) << 8; len|=(size_t) (*(p+3)); p+=4; if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */ { /* Found an IDAT chunk. */ (void) WriteBlobMSBULong(image,len); LogPNGChunk(logging,mng_IDAT,len); (void) WriteBlob(image,len+4,p); (void) WriteBlobMSBULong(image,crc32(0,p,(uInt) len+4)); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping %c%c%c%c chunk, length=%.20g.", *(p),*(p+1),*(p+2),*(p+3),(double) len); } p+=(8+len); } } else if (length != 0) { /* Write JDAA chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAA chunk, length=%.20g.",(double) length); (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAA); LogPNGChunk(logging,mng_JDAA,length); /* Write JDAT chunk(s) data */ (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob, (uInt) length)); } blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Encode image as a JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); (void) AcquireUniqueFilename(jpeg_image->filename); unique_filenames++; (void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent,"%s", jpeg_image->filename); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns, (double) jpeg_image->rows); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (jng_color_type == 8 || jng_color_type == 12) jpeg_image_info->type=GrayscaleType; jpeg_image_info->quality=jng_quality; jpeg_image->quality=jng_quality; (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,&image->exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAT chunk, length=%.20g.",(double) length); } /* Write JDAT chunk(s) */ (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAT); LogPNGChunk(logging,mng_JDAT,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length)); jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); unique_filenames--; jpeg_image_info=DestroyImageInfo(jpeg_image_info); blob=(unsigned char *) RelinquishMagickMemory(blob); /* Write any JNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-e",logging); /* Write IEND chunk */ (void) WriteBlobMSBULong(image,0L); PNGType(chunk,mng_IEND); LogPNGChunk(logging,mng_IEND,0); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOneJNGImage(); unique_filenames=%d",unique_filenames); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJNGImage() writes a JPEG Network Graphics (JNG) image file. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteJNGImage method is: % % MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image) { MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; (void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n"); status=WriteOneJNGImage(mng_info,image_info,image); mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); (void) CatchImageException(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteJNGImage()"); return(status); } #endif static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) { const char *option; Image *next_image; MagickBooleanType status; volatile MagickBooleanType logging; MngInfo *mng_info; int image_count, need_iterations, need_matte; volatile int #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) need_local_plte, #endif all_images_are_gray, need_defi, use_global_plte; register ssize_t i; unsigned char chunk[800]; volatile unsigned int write_jng, write_mng; volatile size_t scene; size_t final_delay=0, initial_delay; #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; write_mng=LocaleCompare(image_info->magick,"MNG") == 0; /* * See if user has requested a specific PNG subformat to be used * for all of the PNGs in the MNG being written, e.g., * * convert *.png png8:animation.mng * * To do: check -define png:bit_depth and png:color_type as well, * or perhaps use mng:bit_depth and mng:color_type instead for * global settings. */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; write_jng=MagickFalse; if (image_info->compression == JPEGCompression) write_jng=MagickTrue; mng_info->adjoin=image_info->adjoin && (GetNextImageInList(image) != (Image *) NULL) && write_mng; if (logging != MagickFalse) { /* Log some info about the input */ Image *p; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Checking input image(s)\n" " Image_info depth: %.20g, Type: %d", (double) image_info->depth, image_info->type); scene=0; for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scene: %.20g\n, Image depth: %.20g", (double) scene++, (double) p->depth); if (p->matte) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: False"); if (p->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: PseudoClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: DirectClass"); if (p->colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) p->colors); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: unspecified"); if (mng_info->adjoin == MagickFalse) break; } } use_global_plte=MagickFalse; all_images_are_gray=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_defi=MagickFalse; need_matte=MagickFalse; mng_info->framing_mode=1; mng_info->old_framing_mode=1; if (write_mng) if (image_info->page != (char *) NULL) { /* Determine image bounding box. */ SetGeometry(image,&mng_info->page); (void) ParseMetaGeometry(image_info->page,&mng_info->page.x, &mng_info->page.y,&mng_info->page.width,&mng_info->page.height); } if (write_mng) { unsigned int need_geom; unsigned short red, green, blue; mng_info->page=image->page; need_geom=MagickTrue; if (mng_info->page.width || mng_info->page.height) need_geom=MagickFalse; /* Check all the scenes. */ initial_delay=image->delay; need_iterations=MagickFalse; mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0; mng_info->equal_physs=MagickTrue, mng_info->equal_gammas=MagickTrue; mng_info->equal_srgbs=MagickTrue; mng_info->equal_backgrounds=MagickTrue; image_count=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) all_images_are_gray=MagickTrue; mng_info->equal_palettes=MagickFalse; need_local_plte=MagickFalse; #endif for (next_image=image; next_image != (Image *) NULL; ) { if (need_geom) { if ((next_image->columns+next_image->page.x) > mng_info->page.width) mng_info->page.width=next_image->columns+next_image->page.x; if ((next_image->rows+next_image->page.y) > mng_info->page.height) mng_info->page.height=next_image->rows+next_image->page.y; } if (next_image->page.x || next_image->page.y) need_defi=MagickTrue; if (next_image->matte) need_matte=MagickTrue; if ((int) next_image->dispose >= BackgroundDispose) if (next_image->matte || next_image->page.x || next_image->page.y || ((next_image->columns < mng_info->page.width) && (next_image->rows < mng_info->page.height))) mng_info->need_fram=MagickTrue; if (next_image->iterations) need_iterations=MagickTrue; final_delay=next_image->delay; if (final_delay != initial_delay || final_delay > 1UL* next_image->ticks_per_second) mng_info->need_fram=1; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* check for global palette possibility. */ if (image->matte != MagickFalse) need_local_plte=MagickTrue; if (need_local_plte == 0) { if (SetImageGray(image,&image->exception) == MagickFalse) all_images_are_gray=MagickFalse; mng_info->equal_palettes=PalettesAreEqual(image,next_image); if (use_global_plte == 0) use_global_plte=mng_info->equal_palettes; need_local_plte=!mng_info->equal_palettes; } #endif if (GetNextImageInList(next_image) != (Image *) NULL) { if (next_image->background_color.red != next_image->next->background_color.red || next_image->background_color.green != next_image->next->background_color.green || next_image->background_color.blue != next_image->next->background_color.blue) mng_info->equal_backgrounds=MagickFalse; if (next_image->gamma != next_image->next->gamma) mng_info->equal_gammas=MagickFalse; if (next_image->rendering_intent != next_image->next->rendering_intent) mng_info->equal_srgbs=MagickFalse; if ((next_image->units != next_image->next->units) || (next_image->x_resolution != next_image->next->x_resolution) || (next_image->y_resolution != next_image->next->y_resolution)) mng_info->equal_physs=MagickFalse; if (mng_info->equal_chrms) { if (next_image->chromaticity.red_primary.x != next_image->next->chromaticity.red_primary.x || next_image->chromaticity.red_primary.y != next_image->next->chromaticity.red_primary.y || next_image->chromaticity.green_primary.x != next_image->next->chromaticity.green_primary.x || next_image->chromaticity.green_primary.y != next_image->next->chromaticity.green_primary.y || next_image->chromaticity.blue_primary.x != next_image->next->chromaticity.blue_primary.x || next_image->chromaticity.blue_primary.y != next_image->next->chromaticity.blue_primary.y || next_image->chromaticity.white_point.x != next_image->next->chromaticity.white_point.x || next_image->chromaticity.white_point.y != next_image->next->chromaticity.white_point.y) mng_info->equal_chrms=MagickFalse; } } image_count++; next_image=GetNextImageInList(next_image); } if (image_count < 2) { mng_info->equal_backgrounds=MagickFalse; mng_info->equal_chrms=MagickFalse; mng_info->equal_gammas=MagickFalse; mng_info->equal_srgbs=MagickFalse; mng_info->equal_physs=MagickFalse; use_global_plte=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_iterations=MagickFalse; } if (mng_info->need_fram == MagickFalse) { /* Only certain framing rates 100/n are exactly representable without the FRAM chunk but we'll allow some slop in VLC files */ if (final_delay == 0) { if (need_iterations != MagickFalse) { /* It's probably a GIF with loop; don't run it *too* fast. */ if (mng_info->adjoin) { final_delay=10; (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "input has zero delay between all frames; assuming", " 10 cs `%s'",""); } } else mng_info->ticks_per_second=0; } if (final_delay != 0) mng_info->ticks_per_second=(png_uint_32) (image->ticks_per_second/final_delay); if (final_delay > 50) mng_info->ticks_per_second=2; if (final_delay > 75) mng_info->ticks_per_second=1; if (final_delay > 125) mng_info->need_fram=MagickTrue; if (need_defi && final_delay > 2 && (final_delay != 4) && (final_delay != 5) && (final_delay != 10) && (final_delay != 20) && (final_delay != 25) && (final_delay != 50) && (final_delay != (size_t) image->ticks_per_second)) mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */ } if (mng_info->need_fram != MagickFalse) mng_info->ticks_per_second=1UL*image->ticks_per_second; /* If pseudocolor, we should also check to see if all the palettes are identical and write a global PLTE if they are. ../glennrp Feb 99. */ /* Write the MNG version 1.0 signature and MHDR chunk. */ (void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n"); (void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */ PNGType(chunk,mng_MHDR); LogPNGChunk(logging,mng_MHDR,28L); PNGLong(chunk+4,(png_uint_32) mng_info->page.width); PNGLong(chunk+8,(png_uint_32) mng_info->page.height); PNGLong(chunk+12,mng_info->ticks_per_second); PNGLong(chunk+16,0L); /* layer count=unknown */ PNGLong(chunk+20,0L); /* frame count=unknown */ PNGLong(chunk+24,0L); /* play time=unknown */ if (write_jng) { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,27L); /* simplicity=LC+JNG */ else PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */ else PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */ } } else { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,11L); /* simplicity=LC */ else PNGLong(chunk+28,9L); /* simplicity=VLC */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */ else PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */ } } (void) WriteBlob(image,32,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,32)); option=GetImageOption(image_info,"mng:need-cacheoff"); if (option != (const char *) NULL) { size_t length; /* Write "nEED CACHEOFF" to turn playback caching off for streaming MNG. */ PNGType(chunk,mng_nEED); length=CopyMagickString((char *) chunk+4,"CACHEOFF",20); (void) WriteBlobMSBULong(image,(size_t) length); LogPNGChunk(logging,mng_nEED,(size_t) length); length+=4; (void) WriteBlob(image,length,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length)); } if ((GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) != (Image *) NULL) && (image->iterations != 1)) { /* Write MNG TERM chunk */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_TERM); LogPNGChunk(logging,mng_TERM,10L); chunk[4]=3; /* repeat animation */ chunk[5]=0; /* show last frame when done */ PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) PNGLong(chunk+10,PNG_UINT_31_MAX); else PNGLong(chunk+10,(png_uint_32) image->iterations); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM delay: %.20g",(double) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM iterations: %.20g",(double) PNG_UINT_31_MAX); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image iterations: %.20g",(double) image->iterations); } (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); } /* To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if ((image->colorspace == sRGBColorspace || image->rendering_intent) && mng_info->equal_srgbs) { /* Write MNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); mng_info->have_write_global_srgb=MagickTrue; } else { if (image->gamma && mng_info->equal_gammas) { /* Write MNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); mng_info->have_write_global_gama=MagickTrue; } if (mng_info->equal_chrms) { PrimaryInfo primary; /* Write MNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); mng_info->have_write_global_chrm=MagickTrue; } } if (image->x_resolution && image->y_resolution && mng_info->equal_physs) { /* Write MNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } /* Write MNG BACK chunk and global bKGD chunk, if the image is transparent or does not cover the entire frame. */ if (write_mng && (image->matte || image->page.x > 0 || image->page.y > 0 || (image->page.width && (image->page.width+image->page.x < mng_info->page.width)) || (image->page.height && (image->page.height+image->page.y < mng_info->page.height)))) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_BACK); LogPNGChunk(logging,mng_BACK,6L); red=ScaleQuantumToShort(image->background_color.red); green=ScaleQuantumToShort(image->background_color.green); blue=ScaleQuantumToShort(image->background_color.blue); PNGShort(chunk+4,red); PNGShort(chunk+6,green); PNGShort(chunk+8,blue); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); if (mng_info->equal_backgrounds) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,6L); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); } } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if ((need_local_plte == MagickFalse) && (image->storage_class == PseudoClass) && (all_images_are_gray == MagickFalse)) { size_t data_length; /* Write MNG PLTE chunk */ data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red) & 0xff; chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green) & 0xff; chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue) & 0xff; } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } #endif } scene=0; mng_info->delay=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) mng_info->equal_palettes=MagickFalse; #endif do { if (mng_info->adjoin) { #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* If we aren't using a global palette for the entire MNG, check to see if we can use one for two or more consecutive images. */ if (need_local_plte && use_global_plte && !all_images_are_gray) { if (mng_info->IsPalette) { /* When equal_palettes is true, this image has the same palette as the previous PseudoClass image */ mng_info->have_write_global_plte=mng_info->equal_palettes; mng_info->equal_palettes=PalettesAreEqual(image,image->next); if (mng_info->equal_palettes && !mng_info->have_write_global_plte) { /* Write MNG PLTE chunk */ size_t data_length; data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red); chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green); chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk, (uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } } else mng_info->have_write_global_plte=MagickFalse; } #endif if (need_defi) { ssize_t previous_x, previous_y; if (scene != 0) { previous_x=mng_info->page.x; previous_y=mng_info->page.y; } else { previous_x=0; previous_y=0; } mng_info->page=image->page; if ((mng_info->page.x != previous_x) || (mng_info->page.y != previous_y)) { (void) WriteBlobMSBULong(image,12L); /* data length=12 */ PNGType(chunk,mng_DEFI); LogPNGChunk(logging,mng_DEFI,12L); chunk[4]=0; /* object 0 MSB */ chunk[5]=0; /* object 0 LSB */ chunk[6]=0; /* visible */ chunk[7]=0; /* abstract */ PNGLong(chunk+8,(png_uint_32) mng_info->page.x); PNGLong(chunk+12,(png_uint_32) mng_info->page.y); (void) WriteBlob(image,16,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,16)); } } } mng_info->write_mng=write_mng; if ((int) image->dispose >= 3) mng_info->framing_mode=3; if (mng_info->need_fram && mng_info->adjoin && ((image->delay != mng_info->delay) || (mng_info->framing_mode != mng_info->old_framing_mode))) { if (image->delay == mng_info->delay) { /* Write a MNG FRAM chunk with the new framing mode. */ (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,1L); chunk[4]=(unsigned char) mng_info->framing_mode; (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { /* Write a MNG FRAM chunk with the delay. */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,10L); chunk[4]=(unsigned char) mng_info->framing_mode; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=2; /* flag for changing default delay */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=0; /* flag for changing frame clipping */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) ((mng_info->ticks_per_second* image->delay)/MagickMax(image->ticks_per_second,1))); (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); mng_info->delay=(png_uint_32) image->delay; } mng_info->old_framing_mode=mng_info->framing_mode; } #if defined(JNG_SUPPORTED) if (image_info->compression == JPEGCompression) { ImageInfo *write_info; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing JNG object."); /* To do: specify the desired alpha compression method. */ write_info=CloneImageInfo(image_info); write_info->compression=UndefinedCompression; status=WriteOneJNGImage(mng_info,write_info,image); write_info=DestroyImageInfo(write_info); } else #endif { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG object."); mng_info->need_blob = MagickFalse; mng_info->ping_preserve_colormap = MagickFalse; /* We don't want any ancillary chunks written */ mng_info->ping_exclude_bKGD=MagickTrue; mng_info->ping_exclude_caNv=MagickTrue; mng_info->ping_exclude_cHRM=MagickTrue; mng_info->ping_exclude_date=MagickTrue; mng_info->ping_exclude_EXIF=MagickTrue; mng_info->ping_exclude_eXIf=MagickTrue; mng_info->ping_exclude_gAMA=MagickTrue; mng_info->ping_exclude_iCCP=MagickTrue; /* mng_info->ping_exclude_iTXt=MagickTrue; */ mng_info->ping_exclude_oFFs=MagickTrue; mng_info->ping_exclude_pHYs=MagickTrue; mng_info->ping_exclude_sRGB=MagickTrue; mng_info->ping_exclude_tEXt=MagickTrue; mng_info->ping_exclude_tRNS=MagickTrue; mng_info->ping_exclude_vpAg=MagickTrue; mng_info->ping_exclude_zCCP=MagickTrue; mng_info->ping_exclude_zTXt=MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image); } if (status == MagickFalse) { mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); return(MagickFalse); } (void) CatchImageException(image); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (mng_info->adjoin); if (write_mng) { while (GetPreviousImageInList(image) != (Image *) NULL) image=GetPreviousImageInList(image); /* Write the MEND chunk. */ (void) WriteBlobMSBULong(image,0x00000000L); PNGType(chunk,mng_MEND); LogPNGChunk(logging,mng_MEND,0L); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); } /* Relinquish resources. */ (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()"); return(MagickTrue); } #else /* PNG_LIBPNG_VER > 10011 */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) { (void) image; printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); ThrowBinaryException(CoderError,"PNG library is too old", image_info->filename); } static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) { return(WritePNGImage(image_info,image)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif
./CrossVul/dataset_final_sorted/CWE-772/c/good_2613_1
crossvul-cpp_data_bad_2618_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE % % Q Q U U A A NN N T I ZZ E % % Q Q U U AAAAA N N N T I ZZZ EEEEE % % Q QQ U U A A N NN T I ZZ E % % QQQQ UUU A A N N T IIIII ZZZZZ EEEEE % % % % % % MagickCore Methods to Reduce the Number of Unique Colors in an Image % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Realism in computer graphics typically requires using 24 bits/pixel to % generate an image. Yet many graphic display devices do not contain the % amount of memory necessary to match the spatial and color resolution of % the human eye. The Quantize methods takes a 24 bit image and reduces % the number of colors so it can be displayed on raster device with less % bits per pixel. In most instances, the quantized image closely % resembles the original reference image. % % A reduction of colors in an image is also desirable for image % transmission and real-time animation. % % QuantizeImage() takes a standard RGB or monochrome images and quantizes % them down to some fixed number of colors. % % For purposes of color allocation, an image is a set of n pixels, where % each pixel is a point in RGB space. RGB space is a 3-dimensional % vector space, and each pixel, Pi, is defined by an ordered triple of % red, green, and blue coordinates, (Ri, Gi, Bi). % % Each primary color component (red, green, or blue) represents an % intensity which varies linearly from 0 to a maximum value, Cmax, which % corresponds to full saturation of that color. Color allocation is % defined over a domain consisting of the cube in RGB space with opposite % vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax = % 255. % % The algorithm maps this domain onto a tree in which each node % represents a cube within that domain. In the following discussion % these cubes are defined by the coordinate of two opposite vertices (vertex % nearest the origin in RGB space and the vertex farthest from the origin). % % The tree's root node represents the entire domain, (0,0,0) through % (Cmax,Cmax,Cmax). Each lower level in the tree is generated by % subdividing one node's cube into eight smaller cubes of equal size. % This corresponds to bisecting the parent cube with planes passing % through the midpoints of each edge. % % The basic algorithm operates in three phases: Classification, % Reduction, and Assignment. Classification builds a color description % tree for the image. Reduction collapses the tree until the number it % represents, at most, the number of colors desired in the output image. % Assignment defines the output image's color map and sets each pixel's % color by restorage_class in the reduced tree. Our goal is to minimize % the numerical discrepancies between the original colors and quantized % colors (quantization error). % % Classification begins by initializing a color description tree of % sufficient depth to represent each possible input color in a leaf. % However, it is impractical to generate a fully-formed color description % tree in the storage_class phase for realistic values of Cmax. If % colors components in the input image are quantized to k-bit precision, % so that Cmax= 2k-1, the tree would need k levels below the root node to % allow representing each possible input color in a leaf. This becomes % prohibitive because the tree's total number of nodes is 1 + % sum(i=1, k, 8k). % % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255. % Therefore, to avoid building a fully populated tree, QUANTIZE: (1) % Initializes data structures for nodes only as they are needed; (2) % Chooses a maximum depth for the tree as a function of the desired % number of colors in the output image (currently log2(colormap size)). % % For each pixel in the input image, storage_class scans downward from % the root of the color description tree. At each level of the tree it % identifies the single node which represents a cube in RGB space % containing the pixel's color. It updates the following data for each % such node: % % n1: Number of pixels whose color is contained in the RGB cube which % this node represents; % % n2: Number of pixels whose color is not represented in a node at % lower depth in the tree; initially, n2 = 0 for all nodes except % leaves of the tree. % % Sr, Sg, Sb: Sums of the red, green, and blue component values for all % pixels not classified at a lower depth. The combination of these sums % and n2 will ultimately characterize the mean color of a set of % pixels represented by this node. % % E: the distance squared in RGB space between each pixel contained % within a node and the nodes' center. This represents the % quantization error for a node. % % Reduction repeatedly prunes the tree until the number of nodes with n2 % > 0 is less than or equal to the maximum number of colors allowed in % the output image. On any given iteration over the tree, it selects % those nodes whose E count is minimal for pruning and merges their color % statistics upward. It uses a pruning threshold, Ep, to govern node % selection as follows: % % Ep = 0 % while number of nodes with (n2 > 0) > required maximum number of colors % prune all nodes such that E <= Ep % Set Ep to minimum E in remaining nodes % % This has the effect of minimizing any quantization error when merging % two nodes together. % % When a node to be pruned has offspring, the pruning procedure invokes % itself recursively in order to prune the tree from the leaves upward. % n2, Sr, Sg, and Sb in a node being pruned are always added to the % corresponding data in that node's parent. This retains the pruned % node's color characteristics for later averaging. % % For each node, n2 pixels exist for which that node represents the % smallest volume in RGB space containing those pixel's colors. When n2 % > 0 the node will uniquely define a color in the output image. At the % beginning of reduction, n2 = 0 for all nodes except a the leaves of % the tree which represent colors present in the input image. % % The other pixel count, n1, indicates the total number of colors within % the cubic volume which the node represents. This includes n1 - n2 % pixels whose colors should be defined by nodes at a lower level in the % tree. % % Assignment generates the output image from the pruned tree. The output % image consists of two parts: (1) A color map, which is an array of % color descriptions (RGB triples) for each color present in the output % image; (2) A pixel array, which represents each pixel as an index % into the color map array. % % First, the assignment phase makes one pass over the pruned color % description tree to establish the image's color map. For each node % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean % color of all pixels that classify no lower than this node. Each of % these colors becomes an entry in the color map. % % Finally, the assignment phase reclassifies each pixel in the pruned % tree to identify the deepest node containing the pixel's color. The % pixel's value in the pixel array becomes the index of this node's mean % color in the color map. % % This method is based on a similar algorithm written by Paul Raveling. % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/histogram.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/resource_.h" #include "magick/string_.h" #include "magick/thread-private.h" /* Define declarations. */ #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE) #define CacheShift 2 #else #define CacheShift 3 #endif #define ErrorQueueLength 16 #define MaxNodes 266817 #define MaxTreeDepth 8 #define NodesInAList 1920 /* Typdef declarations. */ typedef struct _NodeInfo { struct _NodeInfo *parent, *child[16]; MagickSizeType number_unique; DoublePixelPacket total_color; MagickRealType quantize_error; size_t color_number, id, level; } NodeInfo; typedef struct _Nodes { NodeInfo *nodes; struct _Nodes *next; } Nodes; typedef struct _CubeInfo { NodeInfo *root; size_t colors, maximum_colors; ssize_t transparent_index; MagickSizeType transparent_pixels; DoublePixelPacket target; MagickRealType distance, pruning_threshold, next_threshold; size_t nodes, free_nodes, color_number; NodeInfo *next_node; Nodes *node_queue; MemoryInfo *memory_info; ssize_t *cache; DoublePixelPacket error[ErrorQueueLength]; MagickRealType weights[ErrorQueueLength]; QuantizeInfo *quantize_info; MagickBooleanType associate_alpha; ssize_t x, y; size_t depth; MagickOffsetType offset; MagickSizeType span; } CubeInfo; /* Method prototypes. */ static CubeInfo *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t); static NodeInfo *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *); static MagickBooleanType AssignImageColors(Image *,CubeInfo *), ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *), DitherImage(Image *,CubeInfo *), SetGrayscaleImage(Image *); static size_t DefineImageColormap(Image *,CubeInfo *,NodeInfo *); static void ClosestColor(const Image *,CubeInfo *,const NodeInfo *), DestroyCubeInfo(CubeInfo *), PruneLevel(CubeInfo *,const NodeInfo *), PruneToCubeDepth(CubeInfo *,const NodeInfo *), ReduceImageColors(const Image *,CubeInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantizeInfo() allocates the QuantizeInfo structure. % % The format of the AcquireQuantizeInfo method is: % % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info) { QuantizeInfo *quantize_info; quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info)); if (quantize_info == (QuantizeInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); GetQuantizeInfo(quantize_info); if (image_info != (ImageInfo *) NULL) { const char *option; quantize_info->dither=image_info->dither; option=GetImageOption(image_info,"dither"); if (option != (const char *) NULL) quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,option); quantize_info->measure_error=image_info->verbose; } return(quantize_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A s s i g n I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AssignImageColors() generates the output image from the pruned tree. The % output image consists of two parts: (1) A color map, which is an array % of color descriptions (RGB triples) for each color present in the % output image; (2) A pixel array, which represents each pixel as an % index into the color map array. % % First, the assignment phase makes one pass over the pruned color % description tree to establish the image's color map. For each node % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean % color of all pixels that classify no lower than this node. Each of % these colors becomes an entry in the color map. % % Finally, the assignment phase reclassifies each pixel in the pruned % tree to identify the deepest node containing the pixel's color. The % pixel's value in the pixel array becomes the index of this node's mean % color in the color map. % % The format of the AssignImageColors() method is: % % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static inline void AssociateAlphaPixel(const CubeInfo *cube_info, const PixelPacket *pixel,DoublePixelPacket *alpha_pixel) { MagickRealType alpha; alpha_pixel->index=0; if ((cube_info->associate_alpha == MagickFalse) || (pixel->opacity == OpaqueOpacity)) { alpha_pixel->red=(MagickRealType) GetPixelRed(pixel); alpha_pixel->green=(MagickRealType) GetPixelGreen(pixel); alpha_pixel->blue=(MagickRealType) GetPixelBlue(pixel); alpha_pixel->opacity=(MagickRealType) GetPixelOpacity(pixel); return; } alpha=(MagickRealType) (QuantumScale*(QuantumRange-GetPixelOpacity(pixel))); alpha_pixel->red=alpha*GetPixelRed(pixel); alpha_pixel->green=alpha*GetPixelGreen(pixel); alpha_pixel->blue=alpha*GetPixelBlue(pixel); alpha_pixel->opacity=(MagickRealType) GetPixelOpacity(pixel); } static inline size_t ColorToNodeId(const CubeInfo *cube_info, const DoublePixelPacket *pixel,size_t index) { size_t id; id=(size_t) (((ScaleQuantumToChar(ClampPixel(GetPixelRed(pixel))) >> index) & 0x01) | ((ScaleQuantumToChar(ClampPixel(GetPixelGreen(pixel))) >> index) & 0x01) << 1 | ((ScaleQuantumToChar(ClampPixel(GetPixelBlue(pixel))) >> index) & 0x01) << 2); if (cube_info->associate_alpha != MagickFalse) id|=((ScaleQuantumToChar(ClampPixel(GetPixelOpacity(pixel))) >> index) & 0x1) << 3; return(id); } static inline MagickBooleanType IsSameColor(const Image *image, const PixelPacket *p,const PixelPacket *q) { if ((GetPixelRed(p) != GetPixelRed(q)) || (GetPixelGreen(p) != GetPixelGreen(q)) || (GetPixelBlue(p) != GetPixelBlue(q))) return(MagickFalse); if ((image->matte != MagickFalse) && (GetPixelOpacity(p) != GetPixelOpacity(q))) return(MagickFalse); return(MagickTrue); } static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info) { #define AssignImageTag "Assign/Image" ssize_t y; /* Allocate image colormap. */ if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace(image,cube_info->quantize_info->colorspace); else if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); if (AcquireImageColormap(image,cube_info->colors) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); image->colors=0; cube_info->transparent_pixels=0; cube_info->transparent_index=(-1); (void) DefineImageColormap(image,cube_info,cube_info->root); /* Create a reduced color image. */ if ((cube_info->quantize_info->dither != MagickFalse) && (cube_info->quantize_info->dither_method != NoDitherMethod)) (void) DitherImage(image,cube_info); else { CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CubeInfo cube; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t count; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); cube=(*cube_info); for (x=0; x < (ssize_t) image->columns; x+=count) { DoublePixelPacket pixel; register const NodeInfo *node_info; register ssize_t i; size_t id, index; /* Identify the deepest node containing the pixel's color. */ for (count=1; (x+count) < (ssize_t) image->columns; count++) if (IsSameColor(image,q,q+count) == MagickFalse) break; AssociateAlphaPixel(&cube,q,&pixel); node_info=cube.root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(&cube,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ cube.target=pixel; cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)* (QuantumRange+1.0)+1.0); ClosestColor(image,&cube,node_info->parent); index=cube.color_number; for (i=0; i < (ssize_t) count; i++) { if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+i,index); if (cube.quantize_info->measure_error == MagickFalse) { SetPixelRgb(q,image->colormap+index); if (cube.associate_alpha != MagickFalse) SetPixelOpacity(q,image->colormap[index].opacity); } q++; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AssignImageColors) #endif proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); } if (cube_info->quantize_info->measure_error != MagickFalse) (void) GetImageQuantizeError(image); if ((cube_info->quantize_info->number_colors == 2) && (cube_info->quantize_info->colorspace == GRAYColorspace)) { double intensity; /* Monochrome image. */ intensity=0.0; if ((image->colors > 1) && (GetPixelLuma(image,image->colormap+0) > GetPixelLuma(image,image->colormap+1))) intensity=(double) QuantumRange; image->colormap[0].red=intensity; image->colormap[0].green=intensity; image->colormap[0].blue=intensity; if (image->colors > 1) { image->colormap[1].red=(double) QuantumRange-intensity; image->colormap[1].green=(double) QuantumRange-intensity; image->colormap[1].blue=(double) QuantumRange-intensity; } } (void) SyncImage(image); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace((Image *) image,sRGBColorspace); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l a s s i f y I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClassifyImageColors() begins by initializing a color description tree % of sufficient depth to represent each possible input color in a leaf. % However, it is impractical to generate a fully-formed color % description tree in the storage_class phase for realistic values of % Cmax. If colors components in the input image are quantized to k-bit % precision, so that Cmax= 2k-1, the tree would need k levels below the % root node to allow representing each possible input color in a leaf. % This becomes prohibitive because the tree's total number of nodes is % 1 + sum(i=1,k,8k). % % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255. % Therefore, to avoid building a fully populated tree, QUANTIZE: (1) % Initializes data structures for nodes only as they are needed; (2) % Chooses a maximum depth for the tree as a function of the desired % number of colors in the output image (currently log2(colormap size)). % % For each pixel in the input image, storage_class scans downward from % the root of the color description tree. At each level of the tree it % identifies the single node which represents a cube in RGB space % containing It updates the following data for each such node: % % n1 : Number of pixels whose color is contained in the RGB cube % which this node represents; % % n2 : Number of pixels whose color is not represented in a node at % lower depth in the tree; initially, n2 = 0 for all nodes except % leaves of the tree. % % Sr, Sg, Sb : Sums of the red, green, and blue component values for % all pixels not classified at a lower depth. The combination of % these sums and n2 will ultimately characterize the mean color of a % set of pixels represented by this node. % % E: the distance squared in RGB space between each pixel contained % within a node and the nodes' center. This represents the quantization % error for a node. % % The format of the ClassifyImageColors() method is: % % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info, % const Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o image: the image. % */ static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info) { MagickBooleanType associate_alpha; associate_alpha=image->matte; if ((cube_info->quantize_info->number_colors == 2) && (cube_info->quantize_info->colorspace == GRAYColorspace)) associate_alpha=MagickFalse; cube_info->associate_alpha=associate_alpha; } static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info, const Image *image,ExceptionInfo *exception) { #define ClassifyImageTag "Classify/Image" CacheView *image_view; DoublePixelPacket error, mid, midpoint, pixel; MagickBooleanType proceed; MagickRealType bisect; NodeInfo *node_info; size_t count, id, index, level; ssize_t y; /* Classify the first cube_info->maximum_colors colors to a tree depth of 8. */ SetAssociatedAlpha(image,cube_info); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace((Image *) image, cube_info->quantize_info->colorspace); else if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace((Image *) image,sRGBColorspace); midpoint.red=(MagickRealType) QuantumRange/2.0; midpoint.green=(MagickRealType) QuantumRange/2.0; midpoint.blue=(MagickRealType) QuantumRange/2.0; midpoint.opacity=(MagickRealType) QuantumRange/2.0; midpoint.index=(MagickRealType) QuantumRange/2.0; error.opacity=0.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; if (cube_info->nodes > MaxNodes) { /* Prune one level if the color tree is too large. */ PruneLevel(cube_info,cube_info->root); cube_info->depth--; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count) { /* Start at the root and descend the color cube tree. */ for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++) if (IsSameColor(image,p,p+count) == MagickFalse) break; AssociateAlphaPixel(cube_info,p,&pixel); index=MaxTreeDepth-1; bisect=((MagickRealType) QuantumRange+1.0)/2.0; mid=midpoint; node_info=cube_info->root; for (level=1; level <= MaxTreeDepth; level++) { double distance; bisect*=0.5; id=ColorToNodeId(cube_info,&pixel,index); mid.red+=(id & 1) != 0 ? bisect : -bisect; mid.green+=(id & 2) != 0 ? bisect : -bisect; mid.blue+=(id & 4) != 0 ? bisect : -bisect; mid.opacity+=(id & 8) != 0 ? bisect : -bisect; if (node_info->child[id] == (NodeInfo *) NULL) { /* Set colors of new node to contain pixel. */ node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info); if (node_info->child[id] == (NodeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); continue; } if (level == MaxTreeDepth) cube_info->colors++; } /* Approximate the quantization error represented by this node. */ node_info=node_info->child[id]; error.red=QuantumScale*(pixel.red-mid.red); error.green=QuantumScale*(pixel.green-mid.green); error.blue=QuantumScale*(pixel.blue-mid.blue); if (cube_info->associate_alpha != MagickFalse) error.opacity=QuantumScale*(pixel.opacity-mid.opacity); distance=(double) (error.red*error.red+error.green*error.green+ error.blue*error.blue+error.opacity*error.opacity); if (IsNaN(distance)) distance=0.0; node_info->quantize_error+=count*sqrt(distance); cube_info->root->quantize_error+=node_info->quantize_error; index--; } /* Sum RGB for this leaf for later derivation of the mean cube color. */ node_info->number_unique+=count; node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red); node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green); node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) node_info->total_color.opacity+=count*QuantumScale* ClampPixel(pixel.opacity); else node_info->total_color.opacity+=count*QuantumScale* ClampPixel(OpaqueOpacity); p+=count; } if (cube_info->colors > cube_info->maximum_colors) { PruneToCubeDepth(cube_info,cube_info->root); break; } proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } for (y++; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; if (cube_info->nodes > MaxNodes) { /* Prune one level if the color tree is too large. */ PruneLevel(cube_info,cube_info->root); cube_info->depth--; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count) { /* Start at the root and descend the color cube tree. */ for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++) if (IsSameColor(image,p,p+count) == MagickFalse) break; AssociateAlphaPixel(cube_info,p,&pixel); index=MaxTreeDepth-1; bisect=((MagickRealType) QuantumRange+1.0)/2.0; mid=midpoint; node_info=cube_info->root; for (level=1; level <= cube_info->depth; level++) { double distance; bisect*=0.5; id=ColorToNodeId(cube_info,&pixel,index); mid.red+=(id & 1) != 0 ? bisect : -bisect; mid.green+=(id & 2) != 0 ? bisect : -bisect; mid.blue+=(id & 4) != 0 ? bisect : -bisect; mid.opacity+=(id & 8) != 0 ? bisect : -bisect; if (node_info->child[id] == (NodeInfo *) NULL) { /* Set colors of new node to contain pixel. */ node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info); if (node_info->child[id] == (NodeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","%s", image->filename); continue; } if (level == cube_info->depth) cube_info->colors++; } /* Approximate the quantization error represented by this node. */ node_info=node_info->child[id]; error.red=QuantumScale*(pixel.red-mid.red); error.green=QuantumScale*(pixel.green-mid.green); error.blue=QuantumScale*(pixel.blue-mid.blue); if (cube_info->associate_alpha != MagickFalse) error.opacity=QuantumScale*(pixel.opacity-mid.opacity); distance=(double) (error.red*error.red+error.green*error.green+ error.blue*error.blue+error.opacity*error.opacity); if (IsNaN(distance)) distance=0.0; node_info->quantize_error+=count*sqrt(distance); cube_info->root->quantize_error+=node_info->quantize_error; index--; } /* Sum RGB for this leaf for later derivation of the mean cube color. */ node_info->number_unique+=count; node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red); node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green); node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) node_info->total_color.opacity+=count*QuantumScale*ClampPixel( pixel.opacity); else node_info->total_color.opacity+=count*QuantumScale* ClampPixel(OpaqueOpacity); p+=count; } proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } image_view=DestroyCacheView(image_view); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace((Image *) image,sRGBColorspace); return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneQuantizeInfo() makes a duplicate of the given quantize info structure, % or if quantize info is NULL, a new one. % % The format of the CloneQuantizeInfo method is: % % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given % quantize info, or if image info is NULL a new one. % % o quantize_info: a structure of type info. % */ MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info) { QuantizeInfo *clone_info; clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info)); if (clone_info == (QuantizeInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); GetQuantizeInfo(clone_info); if (quantize_info == (QuantizeInfo *) NULL) return(clone_info); clone_info->number_colors=quantize_info->number_colors; clone_info->tree_depth=quantize_info->tree_depth; clone_info->dither=quantize_info->dither; clone_info->dither_method=quantize_info->dither_method; clone_info->colorspace=quantize_info->colorspace; clone_info->measure_error=quantize_info->measure_error; return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o s e s t C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClosestColor() traverses the color cube tree at a particular node and % determines which colormap entry best represents the input color. % % The format of the ClosestColor method is: % % void ClosestColor(const Image *image,CubeInfo *cube_info, % const NodeInfo *node_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o node_info: the address of a structure of type NodeInfo which points to a % node in the color cube tree that is to be pruned. % */ static void ClosestColor(const Image *image,CubeInfo *cube_info, const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) ClosestColor(image,cube_info,node_info->child[i]); if (node_info->number_unique != 0) { MagickRealType pixel; register DoublePixelPacket *magick_restrict q; register MagickRealType alpha, beta, distance; register PixelPacket *magick_restrict p; /* Determine if this color is "closest". */ p=image->colormap+node_info->color_number; q=(&cube_info->target); alpha=1.0; beta=1.0; if (cube_info->associate_alpha != MagickFalse) { alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p)); beta=(MagickRealType) (QuantumScale*GetPixelAlpha(q)); } pixel=alpha*GetPixelRed(p)-beta*GetPixelRed(q); distance=pixel*pixel; if (distance <= cube_info->distance) { pixel=alpha*GetPixelGreen(p)-beta*GetPixelGreen(q); distance+=pixel*pixel; if (distance <= cube_info->distance) { pixel=alpha*GetPixelBlue(p)-beta*GetPixelBlue(q); distance+=pixel*pixel; if (distance <= cube_info->distance) { if (cube_info->associate_alpha != MagickFalse) { pixel=GetPixelAlpha(p)-GetPixelAlpha(q); distance+=pixel*pixel; } if (distance <= cube_info->distance) { cube_info->distance=distance; cube_info->color_number=node_info->color_number; } } } } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p r e s s I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompressImageColormap() compresses an image colormap by removing any % duplicate or unused color entries. % % The format of the CompressImageColormap method is: % % MagickBooleanType CompressImageColormap(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType CompressImageColormap(Image *image) { QuantizeInfo quantize_info; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (IsPaletteImage(image,&image->exception) == MagickFalse) return(MagickFalse); GetQuantizeInfo(&quantize_info); quantize_info.number_colors=image->colors; quantize_info.tree_depth=MaxTreeDepth; return(QuantizeImage(&quantize_info,image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e f i n e I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DefineImageColormap() traverses the color cube tree and notes each colormap % entry. A colormap entry is any node in the color cube tree where the % of unique colors is not zero. DefineImageColormap() returns the number of % colors in the image colormap. % % The format of the DefineImageColormap method is: % % size_t DefineImageColormap(Image *image,CubeInfo *cube_info, % NodeInfo *node_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o node_info: the address of a structure of type NodeInfo which points to a % node in the color cube tree that is to be pruned. % */ static size_t DefineImageColormap(Image *image,CubeInfo *cube_info, NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) (void) DefineImageColormap(image,cube_info,node_info->child[i]); if (node_info->number_unique != 0) { register MagickRealType alpha; register PixelPacket *magick_restrict q; /* Colormap entry is defined by the mean color in this cube. */ q=image->colormap+image->colors; alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique); alpha=PerceptibleReciprocal(alpha); if (cube_info->associate_alpha == MagickFalse) { SetPixelRed(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.red))); SetPixelGreen(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.green))); SetPixelBlue(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.blue))); SetPixelOpacity(q,OpaqueOpacity); } else { MagickRealType opacity; opacity=(MagickRealType) (alpha*QuantumRange* node_info->total_color.opacity); SetPixelOpacity(q,ClampToQuantum(opacity)); if (q->opacity == OpaqueOpacity) { SetPixelRed(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.red))); SetPixelGreen(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.green))); SetPixelBlue(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.blue))); } else { double gamma; gamma=(double) (QuantumScale*(QuantumRange-(double) q->opacity)); gamma=PerceptibleReciprocal(gamma); SetPixelRed(q,ClampToQuantum((MagickRealType) (alpha* gamma*QuantumRange*node_info->total_color.red))); SetPixelGreen(q,ClampToQuantum((MagickRealType) (alpha* gamma*QuantumRange*node_info->total_color.green))); SetPixelBlue(q,ClampToQuantum((MagickRealType) (alpha* gamma*QuantumRange*node_info->total_color.blue))); if (node_info->number_unique > cube_info->transparent_pixels) { cube_info->transparent_pixels=node_info->number_unique; cube_info->transparent_index=(ssize_t) image->colors; } } } node_info->color_number=image->colors++; } return(image->colors); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y C u b e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyCubeInfo() deallocates memory associated with an image. % % The format of the DestroyCubeInfo method is: % % DestroyCubeInfo(CubeInfo *cube_info) % % A description of each parameter follows: % % o cube_info: the address of a structure of type CubeInfo. % */ static void DestroyCubeInfo(CubeInfo *cube_info) { register Nodes *nodes; /* Release color cube tree storage. */ do { nodes=cube_info->node_queue->next; cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory( cube_info->node_queue->nodes); cube_info->node_queue=(Nodes *) RelinquishMagickMemory( cube_info->node_queue); cube_info->node_queue=nodes; } while (cube_info->node_queue != (Nodes *) NULL); if (cube_info->memory_info != (MemoryInfo *) NULL) cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info); cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info); cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo % structure. % % The format of the DestroyQuantizeInfo method is: % % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % */ MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(quantize_info != (QuantizeInfo *) NULL); assert(quantize_info->signature == MagickSignature); quantize_info->signature=(~MagickSignature); quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info); return(quantize_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DitherImage() distributes the difference between an original image and % the corresponding color reduced algorithm to neighboring pixels using % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns % MagickTrue if the image is dithered otherwise MagickFalse. % % The format of the DitherImage method is: % % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static DoublePixelPacket **DestroyPixelThreadSet(DoublePixelPacket **pixels) { register ssize_t i; assert(pixels != (DoublePixelPacket **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (DoublePixelPacket *) NULL) pixels[i]=(DoublePixelPacket *) RelinquishMagickMemory(pixels[i]); pixels=(DoublePixelPacket **) RelinquishMagickMemory(pixels); return(pixels); } static DoublePixelPacket **AcquirePixelThreadSet(const size_t count) { DoublePixelPacket **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(DoublePixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (DoublePixelPacket **) NULL) return((DoublePixelPacket **) NULL); (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(DoublePixelPacket *) AcquireQuantumMemory(count, 2*sizeof(**pixels)); if (pixels[i] == (DoublePixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); } return(pixels); } static inline ssize_t CacheOffset(CubeInfo *cube_info, const DoublePixelPacket *pixel) { #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift))) #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift))) #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift))) #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift))) ssize_t offset; offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) | GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) | BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue)))); if (cube_info->associate_alpha != MagickFalse) offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->opacity))); return(offset); } static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info) { #define DitherImageTag "Dither/Image" CacheView *image_view; DoublePixelPacket **pixels; ExceptionInfo *exception; MagickBooleanType status; ssize_t y; /* Distribute quantization error using Floyd-Steinberg. */ pixels=AcquirePixelThreadSet(image->columns); if (pixels == (DoublePixelPacket **) NULL) return(MagickFalse); exception=(&image->exception); status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); CubeInfo cube; DoublePixelPacket *current, *previous; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; size_t index; ssize_t v; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); cube=(*cube_info); current=pixels[id]+(y & 0x01)*image->columns; previous=pixels[id]+((y+1) & 0x01)*image->columns; v=(ssize_t) ((y & 0x01) ? -1 : 1); for (x=0; x < (ssize_t) image->columns; x++) { DoublePixelPacket color, pixel; register ssize_t i; ssize_t u; u=(y & 0x01) ? (ssize_t) image->columns-1-x : x; AssociateAlphaPixel(&cube,q+u,&pixel); if (x > 0) { pixel.red+=7*current[u-v].red/16; pixel.green+=7*current[u-v].green/16; pixel.blue+=7*current[u-v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.opacity+=7*current[u-v].opacity/16; } if (y > 0) { if (x < (ssize_t) (image->columns-1)) { pixel.red+=previous[u+v].red/16; pixel.green+=previous[u+v].green/16; pixel.blue+=previous[u+v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.opacity+=previous[u+v].opacity/16; } pixel.red+=5*previous[u].red/16; pixel.green+=5*previous[u].green/16; pixel.blue+=5*previous[u].blue/16; if (cube.associate_alpha != MagickFalse) pixel.opacity+=5*previous[u].opacity/16; if (x > 0) { pixel.red+=3*previous[u-v].red/16; pixel.green+=3*previous[u-v].green/16; pixel.blue+=3*previous[u-v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.opacity+=3*previous[u-v].opacity/16; } } pixel.red=(MagickRealType) ClampPixel(pixel.red); pixel.green=(MagickRealType) ClampPixel(pixel.green); pixel.blue=(MagickRealType) ClampPixel(pixel.blue); if (cube.associate_alpha != MagickFalse) pixel.opacity=(MagickRealType) ClampPixel(pixel.opacity); i=CacheOffset(&cube,&pixel); if (cube.cache[i] < 0) { register NodeInfo *node_info; register size_t id; /* Identify the deepest node containing the pixel's color. */ node_info=cube.root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(&cube,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ cube.target=pixel; cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+ 1.0)+1.0); ClosestColor(image,&cube,node_info->parent); cube.cache[i]=(ssize_t) cube.color_number; } /* Assign pixel to closest colormap entry. */ index=(size_t) cube.cache[i]; if (image->storage_class == PseudoClass) SetPixelIndex(indexes+u,index); if (cube.quantize_info->measure_error == MagickFalse) { SetPixelRgb(q+u,image->colormap+index); if (cube.associate_alpha != MagickFalse) SetPixelOpacity(q+u,image->colormap[index].opacity); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; /* Store the error. */ AssociateAlphaPixel(&cube,image->colormap+index,&color); current[u].red=pixel.red-color.red; current[u].green=pixel.green-color.green; current[u].blue=pixel.blue-color.blue; if (cube.associate_alpha != MagickFalse) current[u].opacity=pixel.opacity-color.opacity; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } image_view=DestroyCacheView(image_view); pixels=DestroyPixelThreadSet(pixels); return(MagickTrue); } static MagickBooleanType RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int); static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info, const size_t level,const unsigned int direction) { if (level == 1) switch (direction) { case WestGravity: { (void) RiemersmaDither(image,image_view,cube_info,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); break; } case EastGravity: { (void) RiemersmaDither(image,image_view,cube_info,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); break; } case NorthGravity: { (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); break; } case SouthGravity: { (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); break; } default: break; } else switch (direction) { case WestGravity: { Riemersma(image,image_view,cube_info,level-1,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); Riemersma(image,image_view,cube_info,level-1,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); Riemersma(image,image_view,cube_info,level-1,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); Riemersma(image,image_view,cube_info,level-1,SouthGravity); break; } case EastGravity: { Riemersma(image,image_view,cube_info,level-1,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); Riemersma(image,image_view,cube_info,level-1,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); Riemersma(image,image_view,cube_info,level-1,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); Riemersma(image,image_view,cube_info,level-1,NorthGravity); break; } case NorthGravity: { Riemersma(image,image_view,cube_info,level-1,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); Riemersma(image,image_view,cube_info,level-1,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); Riemersma(image,image_view,cube_info,level-1,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); Riemersma(image,image_view,cube_info,level-1,EastGravity); break; } case SouthGravity: { Riemersma(image,image_view,cube_info,level-1,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); Riemersma(image,image_view,cube_info,level-1,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); Riemersma(image,image_view,cube_info,level-1,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); Riemersma(image,image_view,cube_info,level-1,WestGravity); break; } default: break; } } static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view, CubeInfo *cube_info,const unsigned int direction) { #define DitherImageTag "Dither/Image" DoublePixelPacket color, pixel; MagickBooleanType proceed; register CubeInfo *p; size_t index; p=cube_info; if ((p->x >= 0) && (p->x < (ssize_t) image->columns) && (p->y >= 0) && (p->y < (ssize_t) image->rows)) { ExceptionInfo *exception; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t i; /* Distribute error. */ exception=(&image->exception); q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickFalse); indexes=GetCacheViewAuthenticIndexQueue(image_view); AssociateAlphaPixel(cube_info,q,&pixel); for (i=0; i < ErrorQueueLength; i++) { pixel.red+=p->weights[i]*p->error[i].red; pixel.green+=p->weights[i]*p->error[i].green; pixel.blue+=p->weights[i]*p->error[i].blue; if (cube_info->associate_alpha != MagickFalse) pixel.opacity+=p->weights[i]*p->error[i].opacity; } pixel.red=(MagickRealType) ClampPixel(pixel.red); pixel.green=(MagickRealType) ClampPixel(pixel.green); pixel.blue=(MagickRealType) ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) pixel.opacity=(MagickRealType) ClampPixel(pixel.opacity); i=CacheOffset(cube_info,&pixel); if (p->cache[i] < 0) { register NodeInfo *node_info; register size_t id; /* Identify the deepest node containing the pixel's color. */ node_info=p->root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(cube_info,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ p->target=pixel; p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType) QuantumRange+1.0)+1.0); ClosestColor(image,p,node_info->parent); p->cache[i]=(ssize_t) p->color_number; } /* Assign pixel to closest colormap entry. */ index=(size_t) (1*p->cache[i]); if (image->storage_class == PseudoClass) *indexes=(IndexPacket) index; if (cube_info->quantize_info->measure_error == MagickFalse) { SetPixelRgb(q,image->colormap+index); if (cube_info->associate_alpha != MagickFalse) SetPixelOpacity(q,image->colormap[index].opacity); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) return(MagickFalse); /* Propagate the error as the last entry of the error queue. */ (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)* sizeof(p->error[0])); AssociateAlphaPixel(cube_info,image->colormap+index,&color); p->error[ErrorQueueLength-1].red=pixel.red-color.red; p->error[ErrorQueueLength-1].green=pixel.green-color.green; p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue; if (cube_info->associate_alpha != MagickFalse) p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity; proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span); if (proceed == MagickFalse) return(MagickFalse); p->offset++; } switch (direction) { case WestGravity: p->x--; break; case EastGravity: p->x++; break; case NorthGravity: p->y--; break; case SouthGravity: p->y++; break; } return(MagickTrue); } static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info) { CacheView *image_view; MagickBooleanType status; register ssize_t i; size_t depth; if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod) return(FloydSteinbergDither(image,cube_info)); /* Distribute quantization error along a Hilbert curve. */ (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength* sizeof(*cube_info->error)); cube_info->x=0; cube_info->y=0; i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows); for (depth=1; i != 0; depth++) i>>=1; if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows)) depth++; cube_info->offset=0; cube_info->span=(MagickSizeType) image->columns*image->rows; image_view=AcquireAuthenticCacheView(image,&image->exception); if (depth > 1) Riemersma(image,image_view,cube_info,depth-1,NorthGravity); status=RiemersmaDither(image,image_view,cube_info,ForgetGravity); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t C u b e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetCubeInfo() initialize the Cube data structure. % % The format of the GetCubeInfo method is: % % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info, % const size_t depth,const size_t maximum_colors) % % A description of each parameter follows. % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o depth: Normally, this integer value is zero or one. A zero or % one tells Quantize to choose a optimal tree depth of Log4(number_colors). % A tree of this depth generally allows the best representation of the % reference image with the least amount of memory and the fastest % computational speed. In some cases, such as an image with low color % dispersion (a few number of colors), a value other than % Log4(number_colors) is required. To expand the color tree completely, % use a value of 8. % % o maximum_colors: maximum colors. % */ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info, const size_t depth,const size_t maximum_colors) { CubeInfo *cube_info; MagickRealType sum, weight; register ssize_t i; size_t length; /* Initialize tree to describe color cube_info. */ cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info)); if (cube_info == (CubeInfo *) NULL) return((CubeInfo *) NULL); (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info)); cube_info->depth=depth; if (cube_info->depth > MaxTreeDepth) cube_info->depth=MaxTreeDepth; if (cube_info->depth < 2) cube_info->depth=2; cube_info->maximum_colors=maximum_colors; /* Initialize root node. */ cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL); if (cube_info->root == (NodeInfo *) NULL) return((CubeInfo *) NULL); cube_info->root->parent=cube_info->root; cube_info->quantize_info=CloneQuantizeInfo(quantize_info); if (cube_info->quantize_info->dither == MagickFalse) return(cube_info); /* Initialize dither resources. */ length=(size_t) (1UL << (4*(8-CacheShift))); cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache)); if (cube_info->memory_info == (MemoryInfo *) NULL) return((CubeInfo *) NULL); cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info); /* Initialize color cache. */ (void) ResetMagickMemory(cube_info->cache,(-1),sizeof(*cube_info->cache)* length); /* Distribute weights along a curve of exponential decay. */ weight=1.0; for (i=0; i < ErrorQueueLength; i++) { cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight); weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0)); } /* Normalize the weighting factors. */ weight=0.0; for (i=0; i < ErrorQueueLength; i++) weight+=cube_info->weights[i]; sum=0.0; for (i=0; i < ErrorQueueLength; i++) { cube_info->weights[i]/=weight; sum+=cube_info->weights[i]; } cube_info->weights[0]+=1.0-sum; return(cube_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t N o d e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNodeInfo() allocates memory for a new node in the color cube tree and % presets all fields to zero. % % The format of the GetNodeInfo method is: % % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id, % const size_t level,NodeInfo *parent) % % A description of each parameter follows. % % o node: The GetNodeInfo method returns a pointer to a queue of nodes. % % o id: Specifies the child number of the node. % % o level: Specifies the level in the storage_class the node resides. % */ static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id, const size_t level,NodeInfo *parent) { NodeInfo *node_info; if (cube_info->free_nodes == 0) { Nodes *nodes; /* Allocate a new queue of nodes. */ nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes)); if (nodes == (Nodes *) NULL) return((NodeInfo *) NULL); nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList, sizeof(*nodes->nodes)); if (nodes->nodes == (NodeInfo *) NULL) return((NodeInfo *) NULL); nodes->next=cube_info->node_queue; cube_info->node_queue=nodes; cube_info->next_node=nodes->nodes; cube_info->free_nodes=NodesInAList; } cube_info->nodes++; cube_info->free_nodes--; node_info=cube_info->next_node++; (void) ResetMagickMemory(node_info,0,sizeof(*node_info)); node_info->parent=parent; node_info->id=id; node_info->level=level; return(node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e Q u a n t i z e E r r o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageQuantizeError() measures the difference between the original % and quantized images. This difference is the total quantization error. % The error is computed by summing over all pixels in an image the distance % squared in RGB space between each reference pixel value and its quantized % value. These values are computed: % % o mean_error_per_pixel: This value is the mean error for any single % pixel in the image. % % o normalized_mean_square_error: This value is the normalized mean % quantization error for any single pixel in the image. This distance % measure is normalized to a range between 0 and 1. It is independent % of the range of red, green, and blue values in the image. % % o normalized_maximum_square_error: Thsi value is the normalized % maximum quantization error for any single pixel in the image. This % distance measure is normalized to a range between 0 and 1. It is % independent of the range of red, green, and blue values in your image. % % The format of the GetImageQuantizeError method is: % % MagickBooleanType GetImageQuantizeError(Image *image) % % A description of each parameter follows. % % o image: the image. % */ MagickExport MagickBooleanType GetImageQuantizeError(Image *image) { CacheView *image_view; ExceptionInfo *exception; IndexPacket *indexes; MagickRealType alpha, area, beta, distance, gamma, maximum_error, mean_error, mean_error_per_pixel; size_t index; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception); (void) ResetMagickMemory(&image->error,0,sizeof(image->error)); if (image->storage_class == DirectClass) return(MagickTrue); alpha=1.0; beta=1.0; area=3.0*image->columns*image->rows; maximum_error=0.0; mean_error_per_pixel=0.0; mean_error=0.0; exception=(&image->exception); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { index=1UL*GetPixelIndex(indexes+x); if (image->matte != MagickFalse) { alpha=(MagickRealType) (QuantumScale*(GetPixelAlpha(p))); beta=(MagickRealType) (QuantumScale*(QuantumRange- image->colormap[index].opacity)); } distance=fabs((double) (alpha*GetPixelRed(p)-beta* image->colormap[index].red)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; distance=fabs((double) (alpha*GetPixelGreen(p)-beta* image->colormap[index].green)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; distance=fabs((double) (alpha*GetPixelBlue(p)-beta* image->colormap[index].blue)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; p++; } } image_view=DestroyCacheView(image_view); gamma=PerceptibleReciprocal(area); image->error.mean_error_per_pixel=gamma*mean_error_per_pixel; image->error.normalized_mean_error=gamma*QuantumScale*QuantumScale*mean_error; image->error.normalized_maximum_error=QuantumScale*maximum_error; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantizeInfo() initializes the QuantizeInfo structure. % % The format of the GetQuantizeInfo method is: % % GetQuantizeInfo(QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to a QuantizeInfo structure. % */ MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(quantize_info != (QuantizeInfo *) NULL); (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info)); quantize_info->number_colors=256; quantize_info->dither=MagickTrue; quantize_info->dither_method=RiemersmaDitherMethod; quantize_info->colorspace=UndefinedColorspace; quantize_info->measure_error=MagickFalse; quantize_info->signature=MagickSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o s t e r i z e I m a g e C h a n n e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PosterizeImage() reduces the image to a limited number of colors for a % "poster" effect. % % The format of the PosterizeImage method is: % % MagickBooleanType PosterizeImage(Image *image,const size_t levels, % const MagickBooleanType dither) % MagickBooleanType PosterizeImageChannel(Image *image, % const ChannelType channel,const size_t levels, % const MagickBooleanType dither) % % A description of each parameter follows: % % o image: Specifies a pointer to an Image structure. % % o levels: Number of color levels allowed in each channel. Very low values % (2, 3, or 4) have the most visible effect. % % o dither: Set this integer value to something other than zero to dither % the mapped image. % */ static inline double MagickRound(double x) { /* Round the fraction to nearest integer. */ if ((x-floor(x)) < (ceil(x)-x)) return(floor(x)); return(ceil(x)); } MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels, const MagickBooleanType dither) { MagickBooleanType status; status=PosterizeImageChannel(image,DefaultChannels,levels,dither); return(status); } MagickExport MagickBooleanType PosterizeImageChannel(Image *image, const ChannelType channel,const size_t levels,const MagickBooleanType dither) { #define PosterizeImageTag "Posterize/Image" #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \ QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1)) CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; QuantizeInfo *quantize_info; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,1,1) #endif for (i=0; i < (ssize_t) image->colors; i++) { /* Posterize colormap. */ if ((channel & RedChannel) != 0) image->colormap[i].red=PosterizePixel(image->colormap[i].red); if ((channel & GreenChannel) != 0) image->colormap[i].green=PosterizePixel(image->colormap[i].green); if ((channel & BlueChannel) != 0) image->colormap[i].blue=PosterizePixel(image->colormap[i].blue); if ((channel & OpacityChannel) != 0) image->colormap[i].opacity=PosterizePixel(image->colormap[i].opacity); } /* Posterize image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,PosterizePixel(GetPixelRed(q))); if ((channel & GreenChannel) != 0) SetPixelGreen(q,PosterizePixel(GetPixelGreen(q))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,PosterizePixel(GetPixelBlue(q))); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetPixelOpacity(q,PosterizePixel(GetPixelOpacity(q))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,PosterizePixel(GetPixelIndex(indexes+x))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_PosterizeImageChannel) #endif proceed=SetImageProgress(image,PosterizeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL); quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels* levels,MaxColormapSize+1); quantize_info->dither=dither; quantize_info->tree_depth=MaxTreeDepth; status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e C h i l d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneChild() deletes the given node and merges its statistics into its % parent. % % The format of the PruneSubtree method is: % % PruneChild(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneChild(CubeInfo *cube_info,const NodeInfo *node_info) { NodeInfo *parent; register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneChild(cube_info,node_info->child[i]); /* Merge color statistics into parent. */ parent=node_info->parent; parent->number_unique+=node_info->number_unique; parent->total_color.red+=node_info->total_color.red; parent->total_color.green+=node_info->total_color.green; parent->total_color.blue+=node_info->total_color.blue; parent->total_color.opacity+=node_info->total_color.opacity; parent->child[node_info->id]=(NodeInfo *) NULL; cube_info->nodes--; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e L e v e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneLevel() deletes all nodes at the bottom level of the color tree merging % their color statistics into their parent node. % % The format of the PruneLevel method is: % % PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneLevel(cube_info,node_info->child[i]); if (node_info->level == cube_info->depth) PruneChild(cube_info,node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e T o C u b e D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneToCubeDepth() deletes any nodes at a depth greater than % cube_info->depth while merging their color statistics into their parent % node. % % The format of the PruneToCubeDepth method is: % % PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneToCubeDepth(cube_info,node_info->child[i]); if (node_info->level > cube_info->depth) PruneChild(cube_info,node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u a n t i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeImage() analyzes the colors within a reference image and chooses a % fixed number of colors to represent the image. The goal of the algorithm % is to minimize the color difference between the input and output image while % minimizing the processing time. % % The format of the QuantizeImage method is: % % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info, % Image *image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o image: the image. % */ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info, Image *image) { CubeInfo *cube_info; MagickBooleanType status; size_t depth, maximum_colors; assert(quantize_info != (const QuantizeInfo *) NULL); assert(quantize_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); maximum_colors=quantize_info->number_colors; if (maximum_colors == 0) maximum_colors=MaxColormapSize; if (maximum_colors > MaxColormapSize) maximum_colors=MaxColormapSize; if (image->matte == MagickFalse) { if (SetImageGray(image,&image->exception) != MagickFalse) (void) SetGrayscaleImage(image); } if ((image->storage_class == PseudoClass) && (image->colors <= maximum_colors)) { if ((quantize_info->colorspace != UndefinedColorspace) && (quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace(image,quantize_info->colorspace); return(MagickTrue); } depth=quantize_info->tree_depth; if (depth == 0) { size_t colors; /* Depth of color tree is: Log4(colormap size)+2. */ colors=maximum_colors; for (depth=1; colors != 0; depth++) colors>>=2; if ((quantize_info->dither != MagickFalse) && (depth > 2)) depth--; if ((image->matte != MagickFalse) && (depth > 5)) depth--; if (SetImageGray(image,&image->exception) != MagickFalse) depth=MaxTreeDepth; } /* Initialize color cube. */ cube_info=GetCubeInfo(quantize_info,depth,maximum_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,image,&image->exception); if (status != MagickFalse) { /* Reduce the number of colors in the image if it contains more than the maximum, otherwise we can disable dithering to improve the performance. */ if (cube_info->colors > cube_info->maximum_colors) ReduceImageColors(image,cube_info); else cube_info->quantize_info->dither_method=NoDitherMethod; status=AssignImageColors(image,cube_info); } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u a n t i z e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeImages() analyzes the colors within a set of reference images and % chooses a fixed number of colors to represent the set. The goal of the % algorithm is to minimize the color difference between the input and output % images while minimizing the processing time. % % The format of the QuantizeImages method is: % % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info, % Image *images) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o images: Specifies a pointer to a list of Image structures. % */ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info, Image *images) { CubeInfo *cube_info; Image *image; MagickBooleanType proceed, status; MagickProgressMonitor progress_monitor; register ssize_t i; size_t depth, maximum_colors, number_images; assert(quantize_info != (const QuantizeInfo *) NULL); assert(quantize_info->signature == MagickSignature); assert(images != (Image *) NULL); assert(images->signature == MagickSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); if (GetNextImageInList(images) == (Image *) NULL) { /* Handle a single image with QuantizeImage. */ status=QuantizeImage(quantize_info,images); return(status); } status=MagickFalse; maximum_colors=quantize_info->number_colors; if (maximum_colors == 0) maximum_colors=MaxColormapSize; if (maximum_colors > MaxColormapSize) maximum_colors=MaxColormapSize; depth=quantize_info->tree_depth; if (depth == 0) { size_t colors; /* Depth of color tree is: Log4(colormap size)+2. */ colors=maximum_colors; for (depth=1; colors != 0; depth++) colors>>=2; if (quantize_info->dither != MagickFalse) depth--; } /* Initialize color cube. */ cube_info=GetCubeInfo(quantize_info,depth,maximum_colors); if (cube_info == (CubeInfo *) NULL) { (void) ThrowMagickException(&images->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return(MagickFalse); } number_images=GetImageListLength(images); image=images; for (i=0; image != (Image *) NULL; i++) { progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL, image->client_data); status=ClassifyImageColors(cube_info,image,&image->exception); if (status == MagickFalse) break; (void) SetImageProgressMonitor(image,progress_monitor,image->client_data); proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); } if (status != MagickFalse) { /* Reduce the number of colors in an image sequence. */ ReduceImageColors(images,cube_info); image=images; for (i=0; image != (Image *) NULL; i++) { progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,image->client_data); status=AssignImageColors(image,cube_info); if (status == MagickFalse) break; (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); } } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u a n t i z e E r r o r F l a t t e n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeErrorFlatten() traverses the color cube and flattens the quantization % error into a sorted 1D array. This accelerates the color reduction process. % % Contributed by Yoya. % % The format of the QuantizeErrorFlatten method is: % % size_t QuantizeErrorFlatten(const CubeInfo *cube_info, % const NodeInfo *node_info,const ssize_t offset, % MagickRealType *quantize_error) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is current pointer. % % o offset: quantize error offset. % % o quantize_error: the quantization error vector. % */ static size_t QuantizeErrorFlatten(const CubeInfo *cube_info, const NodeInfo *node_info,const ssize_t offset, MagickRealType *quantize_error) { register ssize_t i; size_t n, number_children; if (offset >= (ssize_t) cube_info->nodes) return(0); quantize_error[offset]=node_info->quantize_error; n=1; number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children ; i++) if (node_info->child[i] != (NodeInfo *) NULL) n+=QuantizeErrorFlatten(cube_info,node_info->child[i],offset+n, quantize_error); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e d u c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Reduce() traverses the color cube tree and prunes any node whose % quantization error falls below a particular threshold. % % The format of the Reduce method is: % % Reduce(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void Reduce(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) Reduce(cube_info,node_info->child[i]); if (node_info->quantize_error <= cube_info->pruning_threshold) PruneChild(cube_info,node_info); else { /* Find minimum pruning threshold. */ if (node_info->number_unique > 0) cube_info->colors++; if (node_info->quantize_error < cube_info->next_threshold) cube_info->next_threshold=node_info->quantize_error; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e d u c e I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReduceImageColors() repeatedly prunes the tree until the number of nodes % with n2 > 0 is less than or equal to the maximum number of colors allowed % in the output image. On any given iteration over the tree, it selects % those nodes whose E value is minimal for pruning and merges their % color statistics upward. It uses a pruning threshold, Ep, to govern % node selection as follows: % % Ep = 0 % while number of nodes with (n2 > 0) > required maximum number of colors % prune all nodes such that E <= Ep % Set Ep to minimum E in remaining nodes % % This has the effect of minimizing any quantization error when merging % two nodes together. % % When a node to be pruned has offspring, the pruning procedure invokes % itself recursively in order to prune the tree from the leaves upward. % n2, Sr, Sg, and Sb in a node being pruned are always added to the % corresponding data in that node's parent. This retains the pruned % node's color characteristics for later averaging. % % For each node, n2 pixels exist for which that node represents the % smallest volume in RGB space containing those pixel's colors. When n2 % > 0 the node will uniquely define a color in the output image. At the % beginning of reduction, n2 = 0 for all nodes except a the leaves of % the tree which represent colors present in the input image. % % The other pixel count, n1, indicates the total number of colors % within the cubic volume which the node represents. This includes n1 - % n2 pixels whose colors should be defined by nodes at a lower level in % the tree. % % The format of the ReduceImageColors method is: % % ReduceImageColors(const Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static int MagickRealTypeCompare(const void *error_p,const void *error_q) { MagickRealType *p, *q; p=(MagickRealType *) error_p; q=(MagickRealType *) error_q; if (*p > *q) return(1); if (fabs((double) (*q-*p)) <= MagickEpsilon) return(0); return(-1); } static void ReduceImageColors(const Image *image,CubeInfo *cube_info) { #define ReduceImageTag "Reduce/Image" MagickBooleanType proceed; MagickOffsetType offset; size_t span; cube_info->next_threshold=0.0; if (cube_info->colors > cube_info->maximum_colors) { MagickRealType *quantize_error; /* Enable rapid reduction of the number of unique colors. */ quantize_error=(MagickRealType *) AcquireQuantumMemory(cube_info->nodes, sizeof(*quantize_error)); if (quantize_error != (MagickRealType *) NULL) { (void) QuantizeErrorFlatten(cube_info,cube_info->root,0, quantize_error); qsort(quantize_error,cube_info->nodes,sizeof(MagickRealType), MagickRealTypeCompare); if (cube_info->nodes > (110*(cube_info->maximum_colors+1)/100)) cube_info->next_threshold=quantize_error[cube_info->nodes-110* (cube_info->maximum_colors+1)/100]; quantize_error=(MagickRealType *) RelinquishMagickMemory( quantize_error); } } for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; ) { cube_info->pruning_threshold=cube_info->next_threshold; cube_info->next_threshold=cube_info->root->quantize_error-1; cube_info->colors=0; Reduce(cube_info,cube_info->root); offset=(MagickOffsetType) span-cube_info->colors; proceed=SetImageProgress(image,ReduceImageTag,offset,span- cube_info->maximum_colors+1); if (proceed == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m a p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemapImage() replaces the colors of an image with the closest color from % a reference image. % % The format of the RemapImage method is: % % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info, % Image *image,const Image *remap_image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o image: the image. % % o remap_image: the reference image. % */ MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info, Image *image,const Image *remap_image) { CubeInfo *cube_info; MagickBooleanType status; /* Initialize color cube. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(remap_image != (Image *) NULL); assert(remap_image->signature == MagickSignature); cube_info=GetCubeInfo(quantize_info,MaxTreeDepth, quantize_info->number_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,remap_image,&image->exception); if (status != MagickFalse) { /* Classify image colors from the reference image. */ cube_info->quantize_info->number_colors=cube_info->colors; status=AssignImageColors(image,cube_info); } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m a p I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemapImages() replaces the colors of a sequence of images with the % closest color from a reference image. % % The format of the RemapImage method is: % % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info, % Image *images,Image *remap_image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o images: the image sequence. % % o remap_image: the reference image. % */ MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info, Image *images,const Image *remap_image) { CubeInfo *cube_info; Image *image; MagickBooleanType status; assert(images != (Image *) NULL); assert(images->signature == MagickSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); image=images; if (remap_image == (Image *) NULL) { /* Create a global colormap for an image sequence. */ status=QuantizeImages(quantize_info,images); return(status); } /* Classify image colors from the reference image. */ cube_info=GetCubeInfo(quantize_info,MaxTreeDepth, quantize_info->number_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,remap_image,&image->exception); if (status != MagickFalse) { /* Classify image colors from the reference image. */ cube_info->quantize_info->number_colors=cube_info->colors; image=images; for ( ; image != (Image *) NULL; image=GetNextImageInList(image)) { status=AssignImageColors(image,cube_info); if (status == MagickFalse) break; } } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t G r a y s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetGrayscaleImage() converts an image to a PseudoClass grayscale image. % % The format of the SetGrayscaleImage method is: % % MagickBooleanType SetGrayscaleImage(Image *image) % % A description of each parameter follows: % % o image: The image. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { PixelPacket *color_1, *color_2; int intensity; color_1=(PixelPacket *) x; color_2=(PixelPacket *) y; intensity=PixelPacketIntensity(color_1)-(int) PixelPacketIntensity(color_2); return((int) intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickBooleanType SetGrayscaleImage(Image *image) { CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; PixelPacket *colormap; register ssize_t i; ssize_t *colormap_index, j, y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->type != GrayscaleType) (void) TransformImageColorspace(image,GRAYColorspace); colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize, sizeof(*colormap_index)); if (colormap_index == (ssize_t *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); if (image->storage_class != PseudoClass) { ExceptionInfo *exception; (void) ResetMagickMemory(colormap_index,(-1),MaxColormapSize* sizeof(*colormap_index)); if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); image->colors=0; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { register size_t intensity; intensity=ScaleQuantumToMap(GetPixelRed(q)); if (colormap_index[intensity] < 0) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SetGrayscaleImage) #endif if (colormap_index[intensity] < 0) { colormap_index[intensity]=(ssize_t) image->colors; image->colormap[image->colors].red=GetPixelRed(q); image->colormap[image->colors].green=GetPixelGreen(q); image->colormap[image->colors].blue=GetPixelBlue(q); image->colors++; } } SetPixelIndex(indexes+x,colormap_index[intensity]); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); } for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].opacity=(unsigned short) i; qsort((void *) image->colormap,image->colors,sizeof(PixelPacket), IntensityCompare); colormap=(PixelPacket *) AcquireQuantumMemory(image->colors, sizeof(*colormap)); if (colormap == (PixelPacket *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); j=0; colormap[j]=image->colormap[0]; for (i=0; i < (ssize_t) image->colors; i++) { if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse) { j++; colormap[j]=image->colormap[i]; } colormap_index[(ssize_t) image->colormap[i].opacity]=j; } image->colors=(size_t) (j+1); image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap); image->colormap=colormap; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,colormap_index[ScaleQuantumToMap(GetPixelIndex( indexes+x))]); if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); image->type=GrayscaleType; if (SetImageMonochrome(image,&image->exception) != MagickFalse) image->type=BilevelType; return(status); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2618_1
crossvul-cpp_data_good_2618_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP AAA L M M % % P P A A L MM MM % % PPPP AAAAA L M M M % % P A A L M M % % P A A LLLLL M M % % % % % % Read/Write Palm Pixmap. % % % % % % Software Design % % Christopher R. Hawks % % December 2001 % % % % Copyright 1999-2004 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Based on pnmtopalm by Bill Janssen and ppmtobmp by Ian Goldberg. % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/exception.h" #include "magick/histogram.h" #include "magick/image.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/paint.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/utility.h" /* Define declarations. */ #define PALM_IS_COMPRESSED_FLAG 0x8000 #define PALM_HAS_COLORMAP_FLAG 0x4000 #define PALM_HAS_FOUR_BYTE_FIELD 0x0200 #define PALM_HAS_TRANSPARENCY_FLAG 0x2000 #define PALM_IS_INDIRECT 0x1000 #define PALM_IS_FOR_SCREEN 0x0800 #define PALM_IS_DIRECT_COLOR 0x0400 #define PALM_COMPRESSION_SCANLINE 0x00 #define PALM_COMPRESSION_RLE 0x01 #define PALM_COMPRESSION_NONE 0xFF /* The 256 color system palette for Palm Computing Devices. */ static const unsigned char PalmPalette[256][3] = { {255, 255,255}, {255, 204,255}, {255, 153,255}, {255, 102,255}, {255, 51,255}, {255, 0,255}, {255, 255,204}, {255, 204,204}, {255, 153,204}, {255, 102,204}, {255, 51,204}, {255, 0,204}, {255, 255,153}, {255, 204,153}, {255, 153,153}, {255, 102,153}, {255, 51,153}, {255, 0,153}, {204, 255,255}, {204, 204,255}, {204, 153,255}, {204, 102,255}, {204, 51,255}, {204, 0,255}, {204, 255,204}, {204, 204,204}, {204, 153,204}, {204, 102,204}, {204, 51,204}, {204, 0,204}, {204, 255,153}, {204, 204,153}, {204, 153,153}, {204, 102,153}, {204, 51,153}, {204, 0,153}, {153, 255,255}, {153, 204,255}, {153, 153,255}, {153, 102,255}, {153, 51,255}, {153, 0,255}, {153, 255,204}, {153, 204,204}, {153, 153,204}, {153, 102,204}, {153, 51,204}, {153, 0,204}, {153, 255,153}, {153, 204,153}, {153, 153,153}, {153, 102,153}, {153, 51,153}, {153, 0,153}, {102, 255,255}, {102, 204,255}, {102, 153,255}, {102, 102,255}, {102, 51,255}, {102, 0,255}, {102, 255,204}, {102, 204,204}, {102, 153,204}, {102, 102,204}, {102, 51,204}, {102, 0,204}, {102, 255,153}, {102, 204,153}, {102, 153,153}, {102, 102,153}, {102, 51,153}, {102, 0,153}, { 51, 255,255}, { 51, 204,255}, { 51, 153,255}, { 51, 102,255}, { 51, 51,255}, { 51, 0,255}, { 51, 255,204}, { 51, 204,204}, { 51, 153,204}, { 51, 102,204}, { 51, 51,204}, { 51, 0,204}, { 51, 255,153}, { 51, 204,153}, { 51, 153,153}, { 51, 102,153}, { 51, 51,153}, { 51, 0,153}, { 0, 255,255}, { 0, 204,255}, { 0, 153,255}, { 0, 102,255}, { 0, 51,255}, { 0, 0,255}, { 0, 255,204}, { 0, 204,204}, { 0, 153,204}, { 0, 102,204}, { 0, 51,204}, { 0, 0,204}, { 0, 255,153}, { 0, 204,153}, { 0, 153,153}, { 0, 102,153}, { 0, 51,153}, { 0, 0,153}, {255, 255,102}, {255, 204,102}, {255, 153,102}, {255, 102,102}, {255, 51,102}, {255, 0,102}, {255, 255, 51}, {255, 204, 51}, {255, 153, 51}, {255, 102, 51}, {255, 51, 51}, {255, 0, 51}, {255, 255, 0}, {255, 204, 0}, {255, 153, 0}, {255, 102, 0}, {255, 51, 0}, {255, 0, 0}, {204, 255,102}, {204, 204,102}, {204, 153,102}, {204, 102,102}, {204, 51,102}, {204, 0,102}, {204, 255, 51}, {204, 204, 51}, {204, 153, 51}, {204, 102, 51}, {204, 51, 51}, {204, 0, 51}, {204, 255, 0}, {204, 204, 0}, {204, 153, 0}, {204, 102, 0}, {204, 51, 0}, {204, 0, 0}, {153, 255,102}, {153, 204,102}, {153, 153,102}, {153, 102,102}, {153, 51,102}, {153, 0,102}, {153, 255, 51}, {153, 204, 51}, {153, 153, 51}, {153, 102, 51}, {153, 51, 51}, {153, 0, 51}, {153, 255, 0}, {153, 204, 0}, {153, 153, 0}, {153, 102, 0}, {153, 51, 0}, {153, 0, 0}, {102, 255,102}, {102, 204,102}, {102, 153,102}, {102, 102,102}, {102, 51,102}, {102, 0,102}, {102, 255, 51}, {102, 204, 51}, {102, 153, 51}, {102, 102, 51}, {102, 51, 51}, {102, 0, 51}, {102, 255, 0}, {102, 204, 0}, {102, 153, 0}, {102, 102, 0}, {102, 51, 0}, {102, 0, 0}, { 51, 255,102}, { 51, 204,102}, { 51, 153,102}, { 51, 102,102}, { 51, 51,102}, { 51, 0,102}, { 51, 255, 51}, { 51, 204, 51}, { 51, 153, 51}, { 51, 102, 51}, { 51, 51, 51}, { 51, 0, 51}, { 51, 255, 0}, { 51, 204, 0}, { 51, 153, 0}, { 51, 102, 0}, { 51, 51, 0}, { 51, 0, 0}, { 0, 255,102}, { 0, 204,102}, { 0, 153,102}, { 0, 102,102}, { 0, 51,102}, { 0, 0,102}, { 0, 255, 51}, { 0, 204, 51}, { 0, 153, 51}, { 0, 102, 51}, { 0, 51, 51}, { 0, 0, 51}, { 0, 255, 0}, { 0, 204, 0}, { 0, 153, 0}, { 0, 102, 0}, { 0, 51, 0}, { 17, 17, 17}, { 34, 34, 34}, { 68, 68, 68}, { 85, 85, 85}, {119, 119,119}, {136, 136,136}, {170, 170,170}, {187, 187,187}, {221, 221,221}, {238, 238,238}, {192, 192,192}, {128, 0, 0}, {128, 0,128}, { 0, 128, 0}, { 0, 128,128}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0} }; /* Forward declarations. */ static MagickBooleanType WritePALMImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F i n d C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FindColor() returns the index of the matching entry from PalmPalette for a % given PixelPacket. % % The format of the FindColor method is: % % int FindColor(PixelPacket *pixel) % % A description of each parameter follows: % % o int: the index of the matching color or -1 if not found/ % % o pixel: a pointer to the PixelPacket to be matched. % */ static ssize_t FindColor(PixelPacket *pixel) { register ssize_t i; for (i=0; i < 256; i++) if (ScaleQuantumToChar(GetPixelRed(pixel)) == PalmPalette[i][0] && ScaleQuantumToChar(GetPixelGreen(pixel)) == PalmPalette[i][1] && ScaleQuantumToChar(GetPixelBlue(pixel)) == PalmPalette[i][2]) return(i); return(-1); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P A L M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPALMImage() reads an image of raw bites in LSB order and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPALMImage method is: % % Image *ReadPALMImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Specifies a pointer to an ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadPALMImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; IndexPacket index; MagickBooleanType status; MagickOffsetType totalOffset, seekNextDepth; MagickPixelPacket transpix; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; size_t bytes_per_row, flags, bits_per_pixel, version, nextDepthOffset, transparentIndex, compressionType, byte, mask, redbits, greenbits, bluebits, one, pad, size, bit; ssize_t count, y; unsigned char *last_row, *one_row, *ptr; unsigned short color16; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { (void) DestroyImageList(image); return((Image *) NULL); } totalOffset=0; do { image->columns=ReadBlobMSBShort(image); image->rows=ReadBlobMSBShort(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } bytes_per_row=ReadBlobMSBShort(image); flags=ReadBlobMSBShort(image); bits_per_pixel=(size_t) ReadBlobByte(image); if ((bits_per_pixel != 1) && (bits_per_pixel != 2) && (bits_per_pixel != 4) && (bits_per_pixel != 8) && (bits_per_pixel != 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); version=(size_t) ReadBlobByte(image); if ((version != 0) && (version != 1) && (version != 2)) ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch"); nextDepthOffset=(size_t) ReadBlobMSBShort(image); transparentIndex=(size_t) ReadBlobByte(image); compressionType=(size_t) ReadBlobByte(image); if ((compressionType != PALM_COMPRESSION_NONE) && (compressionType != PALM_COMPRESSION_SCANLINE ) && (compressionType != PALM_COMPRESSION_RLE)) ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); pad=ReadBlobMSBShort(image); (void) pad; /* Initialize image colormap. */ one=1; if ((bits_per_pixel < 16) && (AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetMagickPixelPacket(image,&transpix); if (bits_per_pixel == 16) /* Direct Color */ { redbits=(size_t) ReadBlobByte(image); /* # of bits of red */ (void) redbits; greenbits=(size_t) ReadBlobByte(image); /* # of bits of green */ (void) greenbits; bluebits=(size_t) ReadBlobByte(image); /* # of bits of blue */ (void) bluebits; ReadBlobByte(image); /* reserved by Palm */ ReadBlobByte(image); /* reserved by Palm */ transpix.red=(MagickRealType) (QuantumRange*ReadBlobByte(image)/31); transpix.green=(MagickRealType) (QuantumRange*ReadBlobByte(image)/63); transpix.blue=(MagickRealType) (QuantumRange*ReadBlobByte(image)/31); } if (bits_per_pixel == 8) { IndexPacket index; if (flags & PALM_HAS_COLORMAP_FLAG) { count=(ssize_t) ReadBlobMSBShort(image); for (i=0; i < (ssize_t) count; i++) { ReadBlobByte(image); index=ConstrainColormapIndex(image,(size_t) (255-i)); image->colormap[(int) index].red=ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); image->colormap[(int) index].green=ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); image->colormap[(int) index].blue=ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); } } else for (i=0; i < (ssize_t) (1L << bits_per_pixel); i++) { index=ConstrainColormapIndex(image,(size_t) (255-i)); image->colormap[(int) index].red=ScaleCharToQuantum( PalmPalette[i][0]); image->colormap[(int) index].green=ScaleCharToQuantum( PalmPalette[i][1]); image->colormap[(int) index].blue=ScaleCharToQuantum( PalmPalette[i][2]); } } if (flags & PALM_IS_COMPRESSED_FLAG) size=ReadBlobMSBShort(image); (void) size; image->storage_class=DirectClass; if (bits_per_pixel < 16) { image->storage_class=PseudoClass; image->depth=8; } if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } one_row=(unsigned char *) AcquireQuantumMemory(MagickMax(bytes_per_row, 2*image->columns),sizeof(*one_row)); if (one_row == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); last_row=(unsigned char *) NULL; if (compressionType == PALM_COMPRESSION_SCANLINE) { last_row=(unsigned char *) AcquireQuantumMemory(MagickMax(bytes_per_row, 2*image->columns),sizeof(*last_row)); if (last_row == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } mask=(size_t) (1U << bits_per_pixel)-1; for (y=0; y < (ssize_t) image->rows; y++) { if ((flags & PALM_IS_COMPRESSED_FLAG) == 0) { /* TODO move out of loop! */ image->compression=NoCompression; count=ReadBlob(image,bytes_per_row,one_row); if (count != (ssize_t) bytes_per_row) break; } else { if (compressionType == PALM_COMPRESSION_RLE) { /* TODO move out of loop! */ image->compression=RLECompression; for (i=0; i < (ssize_t) bytes_per_row; ) { count=(ssize_t) ReadBlobByte(image); if (count < 0) break; count=MagickMin(count,(ssize_t) bytes_per_row-i); byte=(size_t) ReadBlobByte(image); (void) ResetMagickMemory(one_row+i,(int) byte,(size_t) count); i+=count; } } else if (compressionType == PALM_COMPRESSION_SCANLINE) { size_t one; /* TODO move out of loop! */ one=1; image->compression=FaxCompression; for (i=0; i < (ssize_t) bytes_per_row; i+=8) { count=(ssize_t) ReadBlobByte(image); if (count < 0) break; byte=(size_t) MagickMin((ssize_t) bytes_per_row-i,8); for (bit=0; bit < byte; bit++) { if ((y == 0) || (count & (one << (7 - bit)))) one_row[i+bit]=(unsigned char) ReadBlobByte(image); else one_row[i+bit]=last_row[i+bit]; } } (void) CopyMagickMemory(last_row, one_row, bytes_per_row); } } ptr=one_row; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); if (bits_per_pixel == 16) { if (image->columns > (2*bytes_per_row)) { one_row=(unsigned char *) RelinquishMagickMemory(one_row); if (compressionType == PALM_COMPRESSION_SCANLINE) last_row=(unsigned char *) RelinquishMagickMemory(last_row); ThrowReaderException(CorruptImageError,"CorruptImage"); } for (x=0; x < (ssize_t) image->columns; x++) { color16=(*ptr++ << 8); color16|=(*ptr++); SetPixelRed(q,(QuantumRange*((color16 >> 11) & 0x1f))/0x1f); SetPixelGreen(q,(QuantumRange*((color16 >> 5) & 0x3f))/0x3f); SetPixelBlue(q,(QuantumRange*((color16 >> 0) & 0x1f))/0x1f); SetPixelOpacity(q,OpaqueOpacity); q++; } } else { bit=8-bits_per_pixel; for (x=0; x < (ssize_t) image->columns; x++) { if ((size_t) (ptr-one_row) >= bytes_per_row) { one_row=(unsigned char *) RelinquishMagickMemory(one_row); if (compressionType == PALM_COMPRESSION_SCANLINE) last_row=(unsigned char *) RelinquishMagickMemory(last_row); ThrowReaderException(CorruptImageError,"CorruptImage"); } index=(IndexPacket) (mask-(((*ptr) & (mask << bit)) >> bit)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); if (bit) bit-=bits_per_pixel; else { ptr++; bit=8-bits_per_pixel; } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (flags & PALM_HAS_TRANSPARENCY_FLAG) { IndexPacket index=ConstrainColormapIndex(image,(mask-transparentIndex)); if (bits_per_pixel != 16) SetMagickPixelPacket(image,image->colormap+(ssize_t) index, (const IndexPacket *) NULL,&transpix); (void) TransparentPaintImage(image,&transpix,(Quantum) TransparentOpacity,MagickFalse); } one_row=(unsigned char *) RelinquishMagickMemory(one_row); if (compressionType == PALM_COMPRESSION_SCANLINE) last_row=(unsigned char *) RelinquishMagickMemory(last_row); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. Copied from coders/pnm.c */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (nextDepthOffset != 0) { /* Skip to next image. */ totalOffset+=(MagickOffsetType) (nextDepthOffset*4); if (totalOffset >= (MagickOffsetType) GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader") else seekNextDepth=SeekBlob(image,totalOffset,SEEK_SET); if (seekNextDepth != totalOffset) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Allocate next image structure. Copied from coders/pnm.c */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { (void) DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (nextDepthOffset != 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P A L M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPALMImage() adds properties for the PALM image format to the list of % supported formats. The properties include the image format tag, a method to % read and/or write the format, whether the format supports the saving of more % than one frame to the same file or blob, whether the format supports native % in-memory I/O, and a brief description of the format. % % The format of the RegisterPALMImage method is: % % size_t RegisterPALMImage(void) % */ ModuleExport size_t RegisterPALMImage(void) { MagickInfo *entry; entry=SetMagickInfo("PALM"); entry->decoder=(DecodeImageHandler *) ReadPALMImage; entry->encoder=(EncodeImageHandler *) WritePALMImage; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Palm pixmap"); entry->module=ConstantString("PALM"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P A L M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPALMImage() removes format registrations made by the PALM % module from the list of supported formats. % % The format of the UnregisterPALMImage method is: % % UnregisterPALMImage(void) % */ ModuleExport void UnregisterPALMImage(void) { (void) UnregisterMagickInfo("PALM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P A L M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePALMImage() writes an image of raw bits in LSB order to a file. % % The format of the WritePALMImage method is: % % MagickBooleanType WritePALMImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows. % % o image_info: Specifies a pointer to an ImageInfo structure. % % o image: A pointer to a Image structure. % */ static MagickBooleanType WritePALMImage(const ImageInfo *image_info, Image *image) { ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType currentOffset, offset, scene; MagickSizeType cc; PixelPacket transpix; QuantizeInfo *quantize_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *p; ssize_t y; size_t count, bits_per_pixel, bytes_per_row, nextDepthOffset, one; unsigned char bit, byte, color, *last_row, *one_row, *ptr, version; unsigned int transparentIndex; unsigned short color16, flags; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=AcquireExceptionInfo(); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); quantize_info=AcquireQuantizeInfo(image_info); flags=0; currentOffset=0; transparentIndex=0; transpix.red=0; transpix.green=0; transpix.blue=0; transpix.opacity=0; one=1; version=0; scene=0; do { (void) TransformImageColorspace(image,sRGBColorspace); count=GetNumberColors(image,NULL,exception); for (bits_per_pixel=1; (one << bits_per_pixel) < count; bits_per_pixel*=2) ; if (bits_per_pixel > 16) bits_per_pixel=16; else if (bits_per_pixel < 16) (void) TransformImageColorspace(image,image->colorspace); if (bits_per_pixel < 8) { (void) TransformImageColorspace(image,GRAYColorspace); (void) SetImageType(image,PaletteType); (void) SortColormapByIntensity(image); } if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageStorageClass(image,DirectClass); if (image->storage_class == PseudoClass) flags|=PALM_HAS_COLORMAP_FLAG; else flags|=PALM_IS_DIRECT_COLOR; (void) WriteBlobMSBShort(image,(unsigned short) image->columns); /* width */ (void) WriteBlobMSBShort(image,(unsigned short) image->rows); /* height */ bytes_per_row=((image->columns+(16/bits_per_pixel-1))/(16/ bits_per_pixel))*2; (void) WriteBlobMSBShort(image,(unsigned short) bytes_per_row); if ((image_info->compression == RLECompression) || (image_info->compression == FaxCompression)) flags|=PALM_IS_COMPRESSED_FLAG; (void) WriteBlobMSBShort(image, flags); (void) WriteBlobByte(image,(unsigned char) bits_per_pixel); if (bits_per_pixel > 1) version=1; if ((image_info->compression == RLECompression) || (image_info->compression == FaxCompression)) version=2; (void) WriteBlobByte(image,version); (void) WriteBlobMSBShort(image,0); /* nextDepthOffset */ (void) WriteBlobByte(image,(unsigned char) transparentIndex); if (image_info->compression == RLECompression) (void) WriteBlobByte(image,PALM_COMPRESSION_RLE); else if (image_info->compression == FaxCompression) (void) WriteBlobByte(image,PALM_COMPRESSION_SCANLINE); else (void) WriteBlobByte(image,PALM_COMPRESSION_NONE); (void) WriteBlobMSBShort(image,0); /* reserved */ offset=16; if (bits_per_pixel == 16) { (void) WriteBlobByte(image,5); /* # of bits of red */ (void) WriteBlobByte(image,6); /* # of bits of green */ (void) WriteBlobByte(image,5); /* # of bits of blue */ (void) WriteBlobByte(image,0); /* reserved by Palm */ (void) WriteBlobMSBLong(image,0); /* no transparent color, YET */ offset+=8; } if (bits_per_pixel == 8) { if (flags & PALM_HAS_COLORMAP_FLAG) /* Write out colormap */ { quantize_info->dither=IsPaletteImage(image,&image->exception); quantize_info->number_colors=image->colors; (void) QuantizeImage(quantize_info,image); (void) WriteBlobMSBShort(image,(unsigned short) image->colors); for (count = 0; count < image->colors; count++) { (void) WriteBlobByte(image,(unsigned char) count); (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[count].red)); (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[count].green)); (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[count].blue)); } offset+=2+count*4; } else /* Map colors to Palm standard colormap */ { Image *affinity_image; affinity_image=ConstituteImage(256,1,"RGB",CharPixel,&PalmPalette, exception); (void) TransformImageColorspace(affinity_image, affinity_image->colorspace); (void) RemapImage(quantize_info,image,affinity_image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetAuthenticPixels(image,0,y,image->columns,1,exception); indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,FindColor(&image->colormap[ (ssize_t) GetPixelIndex(indexes+x)])); } affinity_image=DestroyImage(affinity_image); } } if (flags & PALM_IS_COMPRESSED_FLAG) (void) WriteBlobMSBShort(image,0); /* fill in size later */ last_row=(unsigned char *) NULL; if (image_info->compression == FaxCompression) { last_row=(unsigned char *) AcquireQuantumMemory(bytes_per_row, sizeof(*last_row)); if (last_row == (unsigned char *) NULL) { quantize_info=DestroyQuantizeInfo(quantize_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } } one_row=(unsigned char *) AcquireQuantumMemory(bytes_per_row, sizeof(*one_row)); if (one_row == (unsigned char *) NULL) { quantize_info=DestroyQuantizeInfo(quantize_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y++) { ptr=one_row; (void) ResetMagickMemory(ptr,0,bytes_per_row); p=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (p == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); if (bits_per_pixel == 16) { for (x=0; x < (ssize_t) image->columns; x++) { color16=(unsigned short) ((((31*(size_t) GetPixelRed(p))/ (size_t) QuantumRange) << 11) | (((63*(size_t) GetPixelGreen(p))/(size_t) QuantumRange) << 5) | ((31*(size_t) GetPixelBlue(p))/(size_t) QuantumRange)); if (GetPixelOpacity(p) == (Quantum) TransparentOpacity) { transpix.red=GetPixelRed(p); transpix.green=GetPixelGreen(p); transpix.blue=GetPixelBlue(p); transpix.opacity=GetPixelOpacity(p); flags|=PALM_HAS_TRANSPARENCY_FLAG; } *ptr++=(unsigned char) ((color16 >> 8) & 0xff); *ptr++=(unsigned char) (color16 & 0xff); p++; } } else { byte=0x00; bit=(unsigned char) (8-bits_per_pixel); for (x=0; x < (ssize_t) image->columns; x++) { if (bits_per_pixel >= 8) color=(unsigned char) GetPixelIndex(indexes+x); else color=(unsigned char) (GetPixelIndex(indexes+x)* ((one << bits_per_pixel)-1)/MagickMax(1*image->colors-1,1)); byte|=color << bit; if (bit != 0) bit-=(unsigned char) bits_per_pixel; else { *ptr++=byte; byte=0x00; bit=(unsigned char) (8-bits_per_pixel); } } if ((image->columns % (8/bits_per_pixel)) != 0) *ptr++=byte; } if (image_info->compression == RLECompression) { x=0; while (x < (ssize_t) bytes_per_row) { byte=one_row[x]; count=1; while ((one_row[++x] == byte) && (count < 255) && (x < (ssize_t) bytes_per_row)) count++; (void) WriteBlobByte(image,(unsigned char) count); (void) WriteBlobByte(image,(unsigned char) byte); } } else if (image_info->compression == FaxCompression) { char tmpbuf[8], *tptr; for (x = 0; x < (ssize_t) bytes_per_row; x += 8) { tptr = tmpbuf; for (bit=0, byte=0; bit < (unsigned char) MagickMin(8,(ssize_t) bytes_per_row-x); bit++) { if ((y == 0) || (last_row[x + bit] != one_row[x + bit])) { byte |= (1 << (7 - bit)); *tptr++ = (char) one_row[x + bit]; } } (void) WriteBlobByte(image, byte); (void) WriteBlob(image,tptr-tmpbuf,(unsigned char *) tmpbuf); } (void) CopyMagickMemory(last_row,one_row,bytes_per_row); } else (void) WriteBlob(image,bytes_per_row,one_row); } if (flags & PALM_HAS_TRANSPARENCY_FLAG) { offset=SeekBlob(image,currentOffset+6,SEEK_SET); (void) WriteBlobMSBShort(image,flags); offset=SeekBlob(image,currentOffset+12,SEEK_SET); (void) WriteBlobByte(image,(unsigned char) transparentIndex); /* trans index */ } if (bits_per_pixel == 16) { offset=SeekBlob(image,currentOffset+20,SEEK_SET); (void) WriteBlobByte(image,0); /* reserved by Palm */ (void) WriteBlobByte(image,(unsigned char) ((31*transpix.red)/ QuantumRange)); (void) WriteBlobByte(image,(unsigned char) ((63*transpix.green)/ QuantumRange)); (void) WriteBlobByte(image,(unsigned char) ((31*transpix.blue)/ QuantumRange)); } if (flags & PALM_IS_COMPRESSED_FLAG) /* fill in size now */ { offset=SeekBlob(image,currentOffset+offset,SEEK_SET); (void) WriteBlobMSBShort(image,(unsigned short) (GetBlobSize(image)- currentOffset-offset)); } if (one_row != (unsigned char *) NULL) one_row=(unsigned char *) RelinquishMagickMemory(one_row); if (last_row != (unsigned char *) NULL) last_row=(unsigned char *) RelinquishMagickMemory(last_row); if (GetNextImageInList(image) == (Image *) NULL) break; /* padding to 4 byte word */ for (cc=(GetBlobSize(image)) % 4; cc > 0; cc--) (void) WriteBlobByte(image,0); /* write nextDepthOffset and return to end of image */ (void) SeekBlob(image,currentOffset+10,SEEK_SET); nextDepthOffset=(size_t) ((GetBlobSize(image)-currentOffset)/4); (void) WriteBlobMSBShort(image,(unsigned short) nextDepthOffset); currentOffset=(MagickOffsetType) GetBlobSize(image); (void) SeekBlob(image,currentOffset,SEEK_SET); image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); quantize_info=DestroyQuantizeInfo(quantize_info); (void) CloseBlob(image); (void) DestroyExceptionInfo(exception); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-772/c/good_2618_0
crossvul-cpp_data_good_361_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N GGGG % % P P NN N G % % PPPP N N N G GG % % P N NN G G % % P N N GGG % % % % % % Read/Write Portable Network Graphics Image Format % % % % Software Design % % Cristy % % Glenn Randers-Pehrson % % November 1997 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ #define IM /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/MagickCore.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_PNG_DELEGATE) /* Suppress libpng pedantic warnings that were added in * libpng-1.2.41 and libpng-1.4.0. If you are working on * migration to libpng-1.5, remove these defines and then * fix any code that generates warnings. */ /* #define PNG_DEPRECATED Use of this function is deprecated */ /* #define PNG_USE_RESULT The result of this function must be checked */ /* #define PNG_NORETURN This function does not return */ /* #define PNG_ALLOCATED The result of the function is new memory */ /* #define PNG_DEPSTRUCT Access to this struct member is deprecated */ /* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */ #define PNG_PTR_NORETURN #include "png.h" #include "zlib.h" /* ImageMagick differences */ #define first_scene scene #if PNG_LIBPNG_VER > 10011 /* Optional declarations. Define or undefine them as you like. */ /* #define PNG_DEBUG -- turning this on breaks VisualC compiling */ /* Features under construction. Define these to work on them. */ #undef MNG_OBJECT_BUFFERS #undef MNG_BASI_SUPPORTED #define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */ #define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */ #if defined(MAGICKCORE_JPEG_DELEGATE) # define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */ #endif #if !defined(RGBColorMatchExact) #define IsPNGColorEqual(color,target) \ (((color).red == (target).red) && \ ((color).green == (target).green) && \ ((color).blue == (target).blue)) #endif /* Table of recognized sRGB ICC profiles */ struct sRGB_info_struct { png_uint_32 len; png_uint_32 crc; png_byte intent; }; const struct sRGB_info_struct sRGB_info[] = { /* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */ { 3048, 0x3b8772b9UL, 0}, /* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */ { 3052, 0x427ebb21UL, 1}, /* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */ {60988, 0x306fd8aeUL, 0}, /* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */ {60960, 0xbbef7812UL, 0}, /* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */ { 3024, 0x5d5129ceUL, 1}, /* HP-Microsoft sRGB v2 perceptual */ { 3144, 0x182ea552UL, 0}, /* HP-Microsoft sRGB v2 media-relative */ { 3144, 0xf29e526dUL, 1}, /* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */ { 524, 0xd4938c39UL, 0}, /* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */ { 3212, 0x034af5a1UL, 0}, /* Not recognized */ { 0, 0x00000000UL, 0}, }; /* Macros for left-bit-replication to ensure that pixels * and PixelInfos all have the same image->depth, and for use * in PNG8 quantization. */ /* LBR01: Replicate top bit */ #define LBR01PacketRed(pixelpacket) \ (pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketGreen(pixelpacket) \ (pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketBlue(pixelpacket) \ (pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketAlpha(pixelpacket) \ (pixelpacket).alpha=(ScaleQuantumToChar((pixelpacket).alpha) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketRGB(pixelpacket) \ { \ LBR01PacketRed((pixelpacket)); \ LBR01PacketGreen((pixelpacket)); \ LBR01PacketBlue((pixelpacket)); \ } #define LBR01PacketRGBA(pixelpacket) \ { \ LBR01PacketRGB((pixelpacket)); \ LBR01PacketAlpha((pixelpacket)); \ } #define LBR01PixelRed(pixel) \ (SetPixelRed(image, \ ScaleQuantumToChar(GetPixelRed(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelGreen(pixel) \ (SetPixelGreen(image, \ ScaleQuantumToChar(GetPixelGreen(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelBlue(pixel) \ (SetPixelBlue(image, \ ScaleQuantumToChar(GetPixelBlue(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelAlpha(pixel) \ (SetPixelAlpha(image, \ ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelRGB(pixel) \ { \ LBR01PixelRed((pixel)); \ LBR01PixelGreen((pixel)); \ LBR01PixelBlue((pixel)); \ } #define LBR01PixelRGBA(pixel) \ { \ LBR01PixelRGB((pixel)); \ LBR01PixelAlpha((pixel)); \ } /* LBR02: Replicate top 2 bits */ #define LBR02PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketAlpha(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).alpha) & 0xc0; \ (pixelpacket).alpha=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketRGB(pixelpacket) \ { \ LBR02PacketRed((pixelpacket)); \ LBR02PacketGreen((pixelpacket)); \ LBR02PacketBlue((pixelpacket)); \ } #define LBR02PacketRGBA(pixelpacket) \ { \ LBR02PacketRGB((pixelpacket)); \ LBR02PacketAlpha((pixelpacket)); \ } #define LBR02PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \ & 0xc0; \ SetPixelRed(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel)); \ } #define LBR02PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\ & 0xc0; \ SetPixelGreen(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel)); \ } #define LBR02PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue(image,(pixel))) & 0xc0; \ SetPixelBlue(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel)); \ } #define LBR02PixelAlpha(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) & 0xc0; \ SetPixelAlpha(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel) ); \ } #define LBR02PixelRGB(pixel) \ { \ LBR02PixelRed((pixel)); \ LBR02PixelGreen((pixel)); \ LBR02PixelBlue((pixel)); \ } #define LBR02PixelRGBA(pixel) \ { \ LBR02PixelRGB((pixel)); \ LBR02PixelAlpha((pixel)); \ } /* LBR03: Replicate top 3 bits (only used with opaque pixels during PNG8 quantization) */ #define LBR03PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketRGB(pixelpacket) \ { \ LBR03PacketRed((pixelpacket)); \ LBR03PacketGreen((pixelpacket)); \ LBR03PacketBlue((pixelpacket)); \ } #define LBR03PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \ & 0xe0; \ SetPixelRed(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \ } #define LBR03Green(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\ & 0xe0; \ SetPixelGreen(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \ } #define LBR03Blue(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue(image,(pixel))) \ & 0xe0; \ SetPixelBlue(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \ } #define LBR03RGB(pixel) \ { \ LBR03PixelRed((pixel)); \ LBR03Green((pixel)); \ LBR03Blue((pixel)); \ } /* LBR04: Replicate top 4 bits */ #define LBR04PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \ (pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \ (pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \ (pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketAlpha(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).alpha) & 0xf0; \ (pixelpacket).alpha=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketRGB(pixelpacket) \ { \ LBR04PacketRed((pixelpacket)); \ LBR04PacketGreen((pixelpacket)); \ LBR04PacketBlue((pixelpacket)); \ } #define LBR04PacketRGBA(pixelpacket) \ { \ LBR04PacketRGB((pixelpacket)); \ LBR04PacketAlpha((pixelpacket)); \ } #define LBR04PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \ & 0xf0; \ SetPixelRed(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\ & 0xf0; \ SetPixelGreen(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue(image,(pixel))) & 0xf0; \ SetPixelBlue(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelAlpha(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) & 0xf0; \ SetPixelAlpha(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelRGB(pixel) \ { \ LBR04PixelRed((pixel)); \ LBR04PixelGreen((pixel)); \ LBR04PixelBlue((pixel)); \ } #define LBR04PixelRGBA(pixel) \ { \ LBR04PixelRGB((pixel)); \ LBR04PixelAlpha((pixel)); \ } /* Establish thread safety. setjmp/longjmp is claimed to be safe on these platforms: setjmp/longjmp is alleged to be unsafe on these platforms: */ #ifdef PNG_SETJMP_SUPPORTED # ifndef IMPNG_SETJMP_IS_THREAD_SAFE # define IMPNG_SETJMP_NOT_THREAD_SAFE # endif # ifdef IMPNG_SETJMP_NOT_THREAD_SAFE static SemaphoreInfo *ping_semaphore = (SemaphoreInfo *) NULL; # endif #endif /* This temporary until I set up malloc'ed object attributes array. Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but waste more memory. */ #define MNG_MAX_OBJECTS 256 /* If this not defined, spec is interpreted strictly. If it is defined, an attempt will be made to recover from some errors, including o global PLTE too short */ #undef MNG_LOOSE /* Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8, PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here. PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and will be enabled by default in libpng-1.2.0. */ #ifdef PNG_MNG_FEATURES_SUPPORTED # ifndef PNG_READ_EMPTY_PLTE_SUPPORTED # define PNG_READ_EMPTY_PLTE_SUPPORTED # endif # ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED # define PNG_WRITE_EMPTY_PLTE_SUPPORTED # endif #endif /* Maximum valid size_t in PNG/MNG chunks is (2^31)-1 This macro is only defined in libpng-1.0.3 and later. Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6 */ #ifndef PNG_UINT_31_MAX #define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL #endif /* Constant strings for known chunk types. If you need to add a chunk, add a string holding the name here. To make the code more portable, we use ASCII numbers like this, not characters. */ static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'}; static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'}; static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'}; static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'}; static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'}; static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'}; static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'}; static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'}; static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'}; static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'}; static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'}; static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'}; static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'}; static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'}; static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'}; static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'}; static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'}; static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'}; static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'}; static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'}; static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'}; static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'}; static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'}; static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'}; static const png_byte mng_orNT[5]={111, 114, 78, 84, (png_byte) '\0'}; static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'}; static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'}; static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'}; static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'}; static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'}; static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'}; #if defined(JNG_SUPPORTED) static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'}; static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'}; static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'}; static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'}; #endif #if 0 /* Other known chunks that are not yet supported by ImageMagick: */ static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'}; static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'}; static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'}; static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'}; static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'}; static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'}; static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'}; #endif typedef struct _MngBox { long left, right, top, bottom; } MngBox; typedef struct _MngPair { volatile long a, b; } MngPair; #ifdef MNG_OBJECT_BUFFERS typedef struct _MngBuffer { size_t height, width; Image *image; png_color plte[256]; int reference_count; unsigned char alpha_sample_depth, compression_method, color_type, concrete, filter_method, frozen, image_type, interlace_method, pixel_sample_depth, plte_length, sample_depth, viewable; } MngBuffer; #endif typedef struct _MngInfo { #ifdef MNG_OBJECT_BUFFERS MngBuffer *ob[MNG_MAX_OBJECTS]; #endif Image * image; RectangleInfo page; int adjoin, #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED bytes_in_read_buffer, found_empty_plte, #endif equal_backgrounds, equal_chrms, equal_gammas, #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) equal_palettes, #endif equal_physs, equal_srgbs, framing_mode, have_global_bkgd, have_global_chrm, have_global_gama, have_global_phys, have_global_sbit, have_global_srgb, have_saved_bkgd_index, have_write_global_chrm, have_write_global_gama, have_write_global_plte, have_write_global_srgb, need_fram, object_id, old_framing_mode, saved_bkgd_index; int new_number_colors; ssize_t image_found, loop_count[256], loop_iteration[256], scenes_found, x_off[MNG_MAX_OBJECTS], y_off[MNG_MAX_OBJECTS]; MngBox clip, frame, image_box, object_clip[MNG_MAX_OBJECTS]; unsigned char /* These flags could be combined into one byte */ exists[MNG_MAX_OBJECTS], frozen[MNG_MAX_OBJECTS], loop_active[256], invisible[MNG_MAX_OBJECTS], viewable[MNG_MAX_OBJECTS]; MagickOffsetType loop_jump[256]; png_colorp global_plte; png_color_8 global_sbit; png_byte #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED read_buffer[8], #endif global_trns[256]; float global_gamma; ChromaticityInfo global_chrm; RenderingIntent global_srgb_intent; unsigned long delay, global_plte_length, global_trns_length, global_x_pixels_per_unit, global_y_pixels_per_unit, mng_width, mng_height, ticks_per_second; MagickBooleanType need_blob; unsigned int IsPalette, global_phys_unit_type, basi_warning, clon_warning, dhdr_warning, jhdr_warning, magn_warning, past_warning, phyg_warning, phys_warning, sbit_warning, show_warning, mng_type, write_mng, write_png_colortype, write_png_depth, write_png_compression_level, write_png_compression_strategy, write_png_compression_filter, write_png8, write_png24, write_png32, write_png48, write_png64; #ifdef MNG_BASI_SUPPORTED unsigned long basi_width, basi_height; unsigned int basi_depth, basi_color_type, basi_compression_method, basi_filter_type, basi_interlace_method, basi_red, basi_green, basi_blue, basi_alpha, basi_viewable; #endif png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; PixelInfo mng_global_bkgd; /* Added at version 6.6.6-7 */ MagickBooleanType ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, ping_exclude_eXIf, ping_exclude_EXIF, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tRNS, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, /* Added at version 6.8.5-7 */ ping_preserve_iCCP, /* Added at version 6.8.9-9 */ ping_exclude_tIME; } MngInfo; #endif /* VER */ /* Forward declarations. */ static MagickBooleanType WritePNGImage(const ImageInfo *,Image *,ExceptionInfo *); static MagickBooleanType WriteMNGImage(const ImageInfo *,Image *,ExceptionInfo *); #if defined(JNG_SUPPORTED) static MagickBooleanType WriteJNGImage(const ImageInfo *,Image *,ExceptionInfo *); #endif #if PNG_LIBPNG_VER > 10011 #if (MAGICKCORE_QUANTUM_DEPTH >= 16) static MagickBooleanType LosslessReduceDepthOK(Image *image,ExceptionInfo *exception) { /* Reduce bit depth if it can be reduced losslessly from 16+ to 8. * * This is true if the high byte and the next highest byte of * each sample of the image, the colormap, and the background color * are equal to each other. We check this by seeing if the samples * are unchanged when we scale them down to 8 and back up to Quantum. * * We don't use the method GetImageDepth() because it doesn't check * background and doesn't handle PseudoClass specially. */ #define QuantumToCharToQuantumEqQuantum(quantum) \ ((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum) MagickBooleanType ok_to_reduce=MagickFalse; if (image->depth >= 16) { const Quantum *p; ok_to_reduce= QuantumToCharToQuantumEqQuantum(image->background_color.red) && QuantumToCharToQuantumEqQuantum(image->background_color.green) && QuantumToCharToQuantumEqQuantum(image->background_color.blue) ? MagickTrue : MagickFalse; if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass) { int indx; for (indx=0; indx < (ssize_t) image->colors; indx++) { ok_to_reduce=( QuantumToCharToQuantumEqQuantum( image->colormap[indx].red) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].green) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].blue)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; } } if ((ok_to_reduce != MagickFalse) && (image->storage_class != PseudoClass)) { ssize_t y; register ssize_t x; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { ok_to_reduce = MagickFalse; break; } for (x=(ssize_t) image->columns-1; x >= 0; x--) { ok_to_reduce= QuantumToCharToQuantumEqQuantum(GetPixelRed(image,p)) && QuantumToCharToQuantumEqQuantum(GetPixelGreen(image,p)) && QuantumToCharToQuantumEqQuantum(GetPixelBlue(image,p)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; p+=GetPixelChannels(image); } if (x >= 0) break; } } if (ok_to_reduce != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " OK to reduce PNG bit depth to 8 without loss of info"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Not OK to reduce PNG bit depth to 8 without losing info"); } } return ok_to_reduce; } #endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */ static const char* PngColorTypeToString(const unsigned int color_type) { const char *result = "Unknown"; switch (color_type) { case PNG_COLOR_TYPE_GRAY: result = "Gray"; break; case PNG_COLOR_TYPE_GRAY_ALPHA: result = "Gray+Alpha"; break; case PNG_COLOR_TYPE_PALETTE: result = "Palette"; break; case PNG_COLOR_TYPE_RGB: result = "RGB"; break; case PNG_COLOR_TYPE_RGB_ALPHA: result = "RGB+Alpha"; break; } return result; } static int Magick_Orientation_to_Exif_Orientation(const OrientationType orientation) { switch (orientation) { /* Convert to Exif orientations as defined in "Exchangeable image file * format for digital still cameras: Exif Version 2.31", * http://www.cipa.jp/std/documents/e/DC-008-Translation-2016-E.pdf */ case TopLeftOrientation: return 1; case TopRightOrientation: return 2; case BottomRightOrientation: return 3; case BottomLeftOrientation: return 4; case LeftTopOrientation: return 5; case RightTopOrientation: return 6; case RightBottomOrientation: return 7; case LeftBottomOrientation: return 8; case UndefinedOrientation: default: return 0; } } static OrientationType Magick_Orientation_from_Exif_Orientation(const int orientation) { switch (orientation) { case 1: return TopLeftOrientation; case 2: return TopRightOrientation; case 3: return BottomRightOrientation; case 4: return BottomLeftOrientation; case 5: return LeftTopOrientation; case 6: return RightTopOrientation; case 7: return RightBottomOrientation; case 8: return LeftBottomOrientation; case 0: default: return UndefinedOrientation; } } static int Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent) { switch (intent) { case PerceptualIntent: return 0; case RelativeIntent: return 1; case SaturationIntent: return 2; case AbsoluteIntent: return 3; default: return -1; } } static RenderingIntent Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return PerceptualIntent; case 1: return RelativeIntent; case 2: return SaturationIntent; case 3: return AbsoluteIntent; default: return UndefinedIntent; } } static const char * Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return "Perceptual Intent"; case 1: return "Relative Intent"; case 2: return "Saturation Intent"; case 3: return "Absolute Intent"; default: return "Undefined Intent"; } } static const char * Magick_ColorType_from_PNG_ColorType(const int ping_colortype) { switch (ping_colortype) { case 0: return "Grayscale"; case 2: return "Truecolor"; case 3: return "Indexed"; case 4: return "GrayAlpha"; case 6: return "RGBA"; default: return "UndefinedColorType"; } } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* MAGICKCORE_PNG_DELEGATE */ /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMNG() returns MagickTrue if the image format type, identified by the % magick string, is MNG. % % The format of the IsMNG method is: % % MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJNG() returns MagickTrue if the image format type, identified by the % magick string, is JNG. % % The format of the IsJNG method is: % % MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNG() returns MagickTrue if the image format type, identified by the % magick string, is PNG. % % The format of the IsPNG method is: % % MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_PNG_DELEGATE) #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if (PNG_LIBPNG_VER > 10011) static size_t WriteBlobMSBULong(Image *image,const size_t value) { unsigned char buffer[4]; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; return((size_t) WriteBlob(image,4,buffer)); } static void PNGLong(png_bytep p,png_uint_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGsLong(png_bytep p,png_int_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGShort(png_bytep p,png_uint_16 value) { *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGType(png_bytep p,const png_byte *type) { (void) memcpy(p,type,4*sizeof(png_byte)); } static void LogPNGChunk(MagickBooleanType logging, const png_byte *type, size_t length) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing %c%c%c%c chunk, length: %.20g", type[0],type[1],type[2],type[3],(double) length); } #endif /* PNG_LIBPNG_VER > 10011 */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNGImage() reads a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image or set of images. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadPNGImage method is: % % Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % % To do, more or less in chronological order (as of version 5.5.2, % November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage): % % Get 16-bit cheap transparency working. % % (At this point, PNG decoding is supposed to be in full MNG-LC compliance) % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % (At this point, PNG encoding should be in full MNG compliance) % % Provide options for choice of background to use when the MNG BACK % chunk is not present or is not mandatory (i.e., leave transparent, % user specified, MNG BACK, PNG bKGD) % % Implement LOOP/ENDL [done, but could do discretionary loops more % efficiently by linking in the duplicate frames.]. % % Decode and act on the MHDR simplicity profile (offer option to reject % files or attempt to process them anyway when the profile isn't LC or VLC). % % Upgrade to full MNG without Delta-PNG. % % o BACK [done a while ago except for background image ID] % o MOVE [done 15 May 1999] % o CLIP [done 15 May 1999] % o DISC [done 19 May 1999] % o SAVE [partially done 19 May 1999 (marks objects frozen)] % o SEEK [partially done 19 May 1999 (discard function only)] % o SHOW % o PAST % o BASI % o MNG-level tEXt/iTXt/zTXt % o pHYg % o pHYs % o sBIT % o bKGD % o iTXt (wait for libpng implementation). % % Use the scene signature to discover when an identical scene is % being reused, and just point to the original image->exception instead % of storing another set of pixels. This not specific to MNG % but could be applied generally. % % Upgrade to full MNG with Delta-PNG. % % JNG tEXt/iTXt/zTXt % % We will not attempt to read files containing the CgBI chunk. % They are really Xcode files meant for display on the iPhone. % These are not valid PNG files and it is impossible to recover % the original PNG from files that have been converted to Xcode-PNG, % since irretrievable loss of color data has occurred due to the % use of premultiplied alpha. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* This the function that does the actual reading of data. It is the same as the one supplied in libpng, except that it receives the datastream from the ReadBlob() function instead of standard input. */ static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) ReadBlob(image,(size_t) length,data); if (check != length) { char msg[MagickPathExtent]; (void) FormatLocaleString(msg,MagickPathExtent, "Expected %.20g bytes; found %.20g bytes",(double) length, (double) check); png_warning(png_ptr,msg); png_error(png_ptr,"Read Exception"); } } } #if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \ !defined(PNG_MNG_FEATURES_SUPPORTED) /* We use mng_get_data() instead of png_get_data() if we have a libpng * older than libpng-1.0.3a, which was the first to allow the empty * PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was * ifdef'ed out. Earlier versions would crash if the bKGD chunk was * encountered after an empty PLTE, so we have to look ahead for bKGD * chunks and remove them from the datastream that is passed to libpng, * and store their contents for later use. */ static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { MngInfo *mng_info; Image *image; png_size_t check; register ssize_t i; i=0; mng_info=(MngInfo *) png_get_io_ptr(png_ptr); image=(Image *) mng_info->image; while (mng_info->bytes_in_read_buffer && length) { data[i]=mng_info->read_buffer[i]; mng_info->bytes_in_read_buffer--; length--; i++; } if (length != 0) { check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data); if (check != length) png_error(png_ptr,"Read Exception"); if (length == 4) { if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 0)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0) mng_info->found_empty_plte=MagickTrue; if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0) { mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; } } if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 1)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0) if (mng_info->found_empty_plte) { /* Skip the bKGD data byte and CRC. */ check=(png_size_t) ReadBlob(image,5,(char *) mng_info->read_buffer); check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->saved_bkgd_index=mng_info->read_buffer[0]; mng_info->have_saved_bkgd_index=MagickTrue; mng_info->bytes_in_read_buffer=0; } } } } } #endif static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) WriteBlob(image,(size_t) length,data); if (check != length) png_error(png_ptr,"WriteBlob Failed"); } } static void png_flush_data(png_structp png_ptr) { (void) png_ptr; } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED static int PalettesAreEqual(Image *a,Image *b) { ssize_t i; if ((a == (Image *) NULL) || (b == (Image *) NULL)) return((int) MagickFalse); if (a->storage_class != PseudoClass || b->storage_class != PseudoClass) return((int) MagickFalse); if (a->colors != b->colors) return((int) MagickFalse); for (i=0; i < (ssize_t) a->colors; i++) { if ((a->colormap[i].red != b->colormap[i].red) || (a->colormap[i].green != b->colormap[i].green) || (a->colormap[i].blue != b->colormap[i].blue)) return((int) MagickFalse); } return((int) MagickTrue); } #endif static void MngInfoDiscardObject(MngInfo *mng_info,int i) { if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) && mng_info->exists[i] && !mng_info->frozen[i]) { #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) { if (mng_info->ob[i]->reference_count > 0) mng_info->ob[i]->reference_count--; if (mng_info->ob[i]->reference_count == 0) { if (mng_info->ob[i]->image != (Image *) NULL) mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image); mng_info->ob[i]=DestroyString(mng_info->ob[i]); } } mng_info->ob[i]=(MngBuffer *) NULL; #endif mng_info->exists[i]=MagickFalse; mng_info->invisible[i]=MagickFalse; mng_info->viewable[i]=MagickFalse; mng_info->frozen[i]=MagickFalse; mng_info->x_off[i]=0; mng_info->y_off[i]=0; mng_info->object_clip[i].left=0; mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].top=0; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } } static MngInfo *MngInfoFreeStruct(MngInfo *mng_info) { register ssize_t i; if (mng_info == (MngInfo *) NULL) return((MngInfo *) NULL); for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); mng_info->global_plte=(png_colorp) RelinquishMagickMemory(mng_info->global_plte); return((MngInfo *) RelinquishMagickMemory(mng_info)); } static MngBox mng_minimum_box(MngBox box1,MngBox box2) { MngBox box; box=box1; if (box.left < box2.left) box.left=box2.left; if (box.top < box2.top) box.top=box2.top; if (box.right > box2.right) box.right=box2.right; if (box.bottom > box2.bottom) box.bottom=box2.bottom; return box; } static long mng_get_long(unsigned char *p) { return ((long) (((png_uint_32) p[0] << 24) | ((png_uint_32) p[1] << 16) | ((png_uint_32) p[2] << 8) | (png_uint_32) p[3])); } static MngBox mng_read_box(MngBox previous_box,char delta_type, unsigned char *p) { MngBox box; /* Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk. */ box.left=mng_get_long(p); box.right=mng_get_long(&p[4]); box.top=mng_get_long(&p[8]); box.bottom=mng_get_long(&p[12]); if (delta_type != 0) { box.left+=previous_box.left; box.right+=previous_box.right; box.top+=previous_box.top; box.bottom+=previous_box.bottom; } return(box); } static MngPair mng_read_pair(MngPair previous_pair,int delta_type, unsigned char *p) { MngPair pair; /* Read two ssize_t's from CLON, MOVE or PAST chunk */ pair.a=mng_get_long(p); pair.b=mng_get_long(&p[4]); if (delta_type != 0) { pair.a+=previous_pair.a; pair.b+=previous_pair.b; } return(pair); } typedef struct _PNGErrorInfo { Image *image; ExceptionInfo *exception; } PNGErrorInfo; static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message) { ExceptionInfo *exception; Image *image; PNGErrorInfo *error_info; error_info=(PNGErrorInfo *) png_get_error_ptr(ping); image=error_info->image; exception=error_info->exception; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s error: %s", png_get_libpng_ver(NULL),message); (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message, "`%s'",image->filename); #if (PNG_LIBPNG_VER < 10500) /* A warning about deprecated use of jmpbuf here is unavoidable if you * are building with libpng-1.4.x and can be ignored. */ longjmp(ping->jmpbuf,1); #else png_longjmp(ping,1); #endif } static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message) { ExceptionInfo *exception; Image *image; PNGErrorInfo *error_info; if (LocaleCompare(message, "Missing PLTE before tRNS") == 0) png_error(ping, message); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); image=error_info->image; exception=error_info->exception; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s warning: %s", png_get_libpng_ver(NULL),message); (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'",image->filename); } #ifdef PNG_USER_MEM_SUPPORTED #if PNG_LIBPNG_VER >= 10400 static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size) #else static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size) #endif { (void) png_ptr; return((png_voidp) AcquireMagickMemory((size_t) size)); } /* Free a pointer. It is removed from the list at the same time. */ static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr) { (void) png_ptr; ptr=RelinquishMagickMemory(ptr); return((png_free_ptr) NULL); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static int Magick_png_read_raw_profile(png_struct *ping,Image *image, const ImageInfo *image_info, png_textp text,int ii,ExceptionInfo *exception) { register ssize_t i; register unsigned char *dp; register png_charp sp; size_t extent, length, nibbles; StringInfo *profile; static const unsigned char unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12, 13,14,15}; sp=text[ii].text+1; extent=text[ii].text_length; /* look for newline */ while ((*sp != '\n') && extent--) sp++; /* look for length */ while (((*sp == '\0' || *sp == ' ' || *sp == '\n')) && extent--) sp++; if (extent == 0) { png_warning(ping,"invalid profile length"); return(MagickFalse); } length=StringToLong(sp); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu",(unsigned long) length); while ((*sp != ' ' && *sp != '\n') && extent--) sp++; if (extent == 0) { png_warning(ping,"missing profile length"); return(MagickFalse); } /* allocate space */ if (length == 0) { png_warning(ping,"invalid profile length"); return(MagickFalse); } profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { png_warning(ping, "unable to copy profile"); return(MagickFalse); } /* copy profile, skipping white space and column 1 "=" signs */ dp=GetStringInfoDatum(profile); nibbles=length*2; for (i=0; i < (ssize_t) nibbles; i++) { while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f') { if (*sp == '\0') { png_warning(ping, "ran out of profile data"); profile=DestroyStringInfo(profile); return(MagickFalse); } sp++; } if (i%2 == 0) *dp=(unsigned char) (16*unhex[(int) *sp++]); else (*dp++)+=unhex[(int) *sp++]; } /* We have already read "Raw profile type. */ (void) SetImageProfile(image,&text[ii].key[17],profile,exception); profile=DestroyStringInfo(profile); if (image_info->verbose) (void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]); return MagickTrue; } static int PNGSetExifProfile(Image *image,png_size_t size,png_byte *data, ExceptionInfo *exception) { StringInfo *profile; unsigned char *p; png_byte *s; size_t i; profile=BlobToStringInfo((const void *) NULL,size+6); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); return(-1); } p=GetStringInfoDatum(profile); /* Initialize profile with "Exif\0\0" */ *p++ ='E'; *p++ ='x'; *p++ ='i'; *p++ ='f'; *p++ ='\0'; *p++ ='\0'; s=data; i=0; if (size > 6) { /* Skip first 6 bytes if "Exif\0\0" is already present by accident */ if (s[0] == 'E' && s[1] == 'x' && s[2] == 'i' && s[3] == 'f' && s[4] == '\0' && s[5] == '\0') { s+=6; i=6; SetStringInfoLength(profile,size); p=GetStringInfoDatum(profile); } } /* copy chunk->data to profile */ for (; i<size; i++) *p++ = *s++; (void) SetImageProfile(image,"exif",profile,exception); profile=DestroyStringInfo(profile); return(1); } #if defined(PNG_READ_eXIf_SUPPORTED) static void read_eXIf_chunk(Image *image,png_struct *ping,png_info *info, ExceptionInfo *exception) { png_uint_32 size; png_bytep data; #if PNG_LIBPNG_VER > 10631 if (png_get_eXIf_1(ping,info,&size,&data)) (void) PNGSetExifProfile(image,size,data,exception); #endif } #endif #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk) { Image *image; /* The unknown chunk structure contains the chunk data: png_byte name[5]; png_byte *data; png_size_t size; Note that libpng has already taken care of the CRC handling. Returns one of the following: return(-n); chunk had an error return(0); did not recognize return(n); success */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read_user_chunk: found %c%c%c%c chunk", chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]); if (chunk->name[0] == 101 && (chunk->name[1] == 88 || chunk->name[1] == 120 ) && chunk->name[2] == 73 && chunk-> name[3] == 102) { /* process eXIf or exIf chunk */ PNGErrorInfo *error_info; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " recognized eXIf chunk"); image=(Image *) png_get_user_chunk_ptr(ping); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); return(PNGSetExifProfile(image,chunk->size,chunk->data, error_info->exception)); } /* orNT */ if (chunk->name[0] == 111 && chunk->name[1] == 114 && chunk->name[2] == 78 && chunk->name[3] == 84) { /* recognized orNT */ if (chunk->size != 1) return(-1); /* Error return */ image=(Image *) png_get_user_chunk_ptr(ping); image->orientation= Magick_Orientation_from_Exif_Orientation((int) chunk->data[0]); return(1); } /* vpAg (deprecated, replaced by caNv) */ if (chunk->name[0] == 118 && chunk->name[1] == 112 && chunk->name[2] == 65 && chunk->name[3] == 103) { /* recognized vpAg */ if (chunk->size != 9) return(-1); /* Error return */ if (chunk->data[8] != 0) return(0); /* ImageMagick requires pixel units */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t)mng_get_long(chunk->data); image->page.height=(size_t)mng_get_long(&chunk->data[4]); return(1); } /* caNv */ if (chunk->name[0] == 99 && chunk->name[1] == 97 && chunk->name[2] == 78 && chunk->name[3] == 118) { /* recognized caNv */ if (chunk->size != 16) return(-1); /* Error return */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t)mng_get_long(chunk->data); image->page.height=(size_t)mng_get_long(&chunk->data[4]); image->page.x=(size_t)mng_get_long(&chunk->data[8]); image->page.y=(size_t)mng_get_long(&chunk->data[12]); return(1); } return(0); /* Did not recognize */ } #endif /* PNG_UNKNOWN_CHUNKS_SUPPORTED */ #if defined(PNG_tIME_SUPPORTED) static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info, ExceptionInfo *exception) { png_timep time; if (png_get_tIME(ping,info,&time)) { char timestamp[21]; FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ", time->year,time->month,time->day,time->hour,time->minute,time->second); SetImageProperty(image,"png:tIME",timestamp,exception); } } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the ReadOnePNGImage method is: % % Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { /* Read one PNG image */ /* To do: Read the tEXt/Creation Time chunk into the date:create property */ Image *image; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; int intent, /* "PNG Rendering intent", which is ICC intent + 1 */ num_raw_profiles, num_text, num_text_total, num_passes, number_colors, pass, ping_bit_depth, ping_color_type, ping_file_depth, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans, unit_type; double file_gamma; MagickBooleanType logging, ping_found_cHRM, ping_found_gAMA, ping_found_iCCP, ping_found_sRGB, ping_found_sRGB_cHRM, ping_preserve_iCCP, status; MemoryInfo *volatile pixel_info; PixelInfo transparent_color; PNGErrorInfo error_info; png_bytep ping_trans_alpha; png_color_16p ping_background, ping_trans_color; png_info *end_info, *ping_info; png_struct *ping; png_textp text; png_uint_32 ping_height, ping_width, x_resolution, y_resolution; QuantumInfo *volatile quantum_info; Quantum *volatile quantum_scanline; ssize_t ping_rowbytes, y; register unsigned char *p; register ssize_t i, x; register Quantum *q; size_t length, row_offset; ssize_t j; unsigned char *ping_pixels; #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED png_byte unused_chunks[]= { 104, 73, 83, 84, (png_byte) '\0', /* hIST */ 105, 84, 88, 116, (png_byte) '\0', /* iTXt */ 112, 67, 65, 76, (png_byte) '\0', /* pCAL */ 115, 67, 65, 76, (png_byte) '\0', /* sCAL */ 115, 80, 76, 84, (png_byte) '\0', /* sPLT */ #if !defined(PNG_tIME_SUPPORTED) 116, 73, 77, 69, (png_byte) '\0', /* tIME */ #endif #ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */ /* ignore the APNG chunks */ 97, 99, 84, 76, (png_byte) '\0', /* acTL */ 102, 99, 84, 76, (png_byte) '\0', /* fcTL */ 102, 100, 65, 84, (png_byte) '\0', /* fdAT */ #endif }; #endif /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,32); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,32); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOnePNGImage()\n" " IM version = %s\n" " Libpng version = %s", im_vers, libpng_vers); if (logging != MagickFalse) { if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " running with %s", zlib_runv); } } #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif #if (PNG_LIBPNG_VER >= 10400) # ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */ if (image_info->verbose) { printf("Your PNG library (libpng-%s) is an old beta version.\n", PNG_LIBPNG_VER_STRING); printf("Please update it.\n"); } # endif #endif quantum_info = (QuantumInfo *) NULL; image=mng_info->image; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before reading:\n" " image->alpha_trait=%d\n" " image->rendering_intent=%d\n" " image->colorspace=%d\n" " image->gamma=%f", (int) image->alpha_trait, (int) image->rendering_intent, (int) image->colorspace, image->gamma); } intent= Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent); /* Set to an out-of-range color unless tRNS chunk is present */ transparent_color.red=65537; transparent_color.green=65537; transparent_color.blue=65537; transparent_color.alpha=65537; number_colors=0; num_text = 0; num_text_total = 0; num_raw_profiles = 0; ping_found_cHRM = MagickFalse; ping_found_gAMA = MagickFalse; ping_found_iCCP = MagickFalse; ping_found_sRGB = MagickFalse; ping_found_sRGB_cHRM = MagickFalse; ping_preserve_iCCP = MagickFalse; /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler, NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } end_info=png_create_info_struct(ping); if (end_info == (png_info *) NULL) { png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=(MemoryInfo *) NULL; quantum_scanline = (Quantum *) NULL; quantum_info = (QuantumInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG image is corrupt. */ png_destroy_read_struct(&ping,&ping_info,&end_info); if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() with error."); if (image != (Image *) NULL) image=DestroyImageList(image); return(image); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED { const char *option; /* Reject images with too many rows or columns */ png_set_user_limits(ping,(png_uint_32) MagickMin(PNG_UINT_31_MAX, GetMagickResourceLimit(WidthResource)),(png_uint_32) MagickMin(PNG_UINT_31_MAX,GetMagickResourceLimit(HeightResource))); #if (PNG_LIBPNG_VER >= 10400) option=GetImageOption(image_info,"png:chunk-cache-max"); if (option != (const char *) NULL) png_set_chunk_cache_max(ping,(png_uint_32) MagickMin(PNG_UINT_32_MAX, StringToLong(option))); else png_set_chunk_cache_max(ping,32767); #endif #if (PNG_LIBPNG_VER >= 10401) option=GetImageOption(image_info,"png:chunk-malloc-max"); if (option != (const char *) NULL) png_set_chunk_malloc_max(ping,(png_alloc_size_t) MagickMin(PNG_SIZE_MAX, StringToLong(option))); #endif } #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for reading. */ mng_info->image_found++; png_set_sig_bytes(ping,8); if (LocaleCompare(image_info->magick,"MNG") == 0) { #if defined(PNG_MNG_FEATURES_SUPPORTED) (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); png_set_read_fn(ping,image,png_get_data); #else #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) png_permit_empty_plte(ping,MagickTrue); png_set_read_fn(ping,image,png_get_data); #else mng_info->image=image; mng_info->bytes_in_read_buffer=0; mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; png_set_read_fn(ping,mng_info,mng_get_data); #endif #endif } else png_set_read_fn(ping,image,png_get_data); { const char *value; value=GetImageOption(image_info,"png:ignore-crc"); if (value != NULL) { /* Turn off CRC checking while reading */ png_set_crc_action(ping, PNG_CRC_QUIET_USE, PNG_CRC_QUIET_USE); #ifdef PNG_IGNORE_ADLER32 /* Turn off ADLER32 checking while reading */ png_set_option(ping, PNG_IGNORE_ADLER32, PNG_OPTION_ON); #endif } value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",value) == MagickFalse) { value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) ping_preserve_iCCP=MagickTrue; #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) /* Don't let libpng check for ICC/sRGB profile because we're going * to do that anyway. This feature was added at libpng-1.6.12. * If logging, go ahead and check and issue a warning as appropriate. */ if (logging == MagickFalse) png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) else { png_set_keep_unknown_chunks(ping, 1, (png_bytep) mng_iCCP, 1); } #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* Ignore unused chunks and all unknown chunks except for caNv and vpAg */ # if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */ png_set_keep_unknown_chunks(ping, 2, NULL, 0); # else png_set_keep_unknown_chunks(ping, 1, NULL, 0); # endif png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_caNv, 1); png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_vpAg, 1); png_set_keep_unknown_chunks(ping, 1, unused_chunks, (int)sizeof(unused_chunks)/5); /* Callback for other unknown chunks */ png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback); #endif #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature */ png_set_check_for_invalid_index (ping, 0); #endif #if (PNG_LIBPNG_VER < 10400) # if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \ (PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__) /* Disable thread-unsafe features of pnggccrd */ if (png_access_version_number() >= 10200) { png_uint_32 mmx_disable_mask=0; png_uint_32 asm_flags; mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \ | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \ | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \ | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ); asm_flags=png_get_asm_flags(ping); png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask); } # endif #endif png_read_info(ping,ping_info); png_get_IHDR(ping,ping_info,&ping_width,&ping_height, &ping_bit_depth,&ping_color_type, &ping_interlace_method,&ping_compression_method, &ping_filter_method); ping_file_depth = ping_bit_depth; /* Swap bytes if requested */ if (ping_file_depth == 16) { const char *value; value=GetImageOption(image_info,"png:swap-bytes"); if (value == NULL) value=GetImageArtifact(image,"png:swap-bytes"); if (value != NULL) png_set_swap(ping); } /* Save bit-depth and color-type in case we later want to write a PNG00 */ { char msg[MagickPathExtent]; (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) ping_color_type); (void) SetImageProperty(image,"png:IHDR.color-type-orig",msg,exception); (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) ping_bit_depth); (void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg,exception); } (void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans, &ping_trans_color); (void) png_get_bKGD(ping, ping_info, &ping_background); if (ping_bit_depth < 8) { png_set_packing(ping); ping_bit_depth = 8; } image->depth=ping_bit_depth; image->depth=GetImageQuantumDepth(image,MagickFalse); image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { image->rendering_intent=UndefinedIntent; intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent); (void) memset(&image->chromaticity,0, sizeof(image->chromaticity)); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG width: %.20g, height: %.20g\n" " PNG color_type: %d, bit_depth: %d\n" " PNG compression_method: %d\n" " PNG interlace_method: %d, filter_method: %d", (double) ping_width, (double) ping_height, ping_color_type, ping_bit_depth, ping_compression_method, ping_interlace_method,ping_filter_method); } if (png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_gAMA)) { ping_found_gAMA=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG gAMA chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { ping_found_cHRM=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG cHRM chunk."); } if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { ping_found_sRGB=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG sRGB chunk."); } #ifdef PNG_READ_iCCP_SUPPORTED if (ping_found_iCCP !=MagickTrue && ping_found_sRGB != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_iCCP)) { int compression; #if (PNG_LIBPNG_VER < 10500) png_charp info; #else png_bytep info; #endif png_charp name; png_uint_32 profile_length; (void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info, &profile_length); if (profile_length != 0) { StringInfo *profile; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG iCCP chunk."); profile=BlobToStringInfo(info,profile_length); if (profile == (StringInfo *) NULL) { png_warning(ping, "ICC profile is NULL"); profile=DestroyStringInfo(profile); } else { if (ping_preserve_iCCP == MagickFalse) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } break; } } } if (sRGB_info[icheck].len == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); (void) SetImageProfile(image,"icc",profile,exception); } } else /* Preserve-iCCP */ { (void) SetImageProfile(image,"icc",profile,exception); } profile=DestroyStringInfo(profile); } } } #endif #if defined(PNG_READ_sRGB_SUPPORTED) { if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { if (png_get_sRGB(ping,ping_info,&intent)) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (intent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG sRGB chunk: rendering_intent: %d",intent); } } else if (mng_info->have_global_srgb) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (mng_info->global_srgb_intent); } } #endif { if (!png_get_gAMA(ping,ping_info,&file_gamma)) if (mng_info->have_global_gama) png_set_gAMA(ping,ping_info,mng_info->global_gamma); if (png_get_gAMA(ping,ping_info,&file_gamma)) { image->gamma=(float) file_gamma; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG gAMA chunk: gamma: %f",file_gamma); } } if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { if (mng_info->have_global_chrm != MagickFalse) { (void) png_set_cHRM(ping,ping_info, mng_info->global_chrm.white_point.x, mng_info->global_chrm.white_point.y, mng_info->global_chrm.red_primary.x, mng_info->global_chrm.red_primary.y, mng_info->global_chrm.green_primary.x, mng_info->global_chrm.green_primary.y, mng_info->global_chrm.blue_primary.x, mng_info->global_chrm.blue_primary.y); } } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { (void) png_get_cHRM(ping,ping_info, &image->chromaticity.white_point.x, &image->chromaticity.white_point.y, &image->chromaticity.red_primary.x, &image->chromaticity.red_primary.y, &image->chromaticity.green_primary.x, &image->chromaticity.green_primary.y, &image->chromaticity.blue_primary.x, &image->chromaticity.blue_primary.y); ping_found_cHRM=MagickTrue; if (image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f) ping_found_sRGB_cHRM=MagickTrue; } if (image->rendering_intent != UndefinedIntent) { if (ping_found_sRGB != MagickTrue && (ping_found_gAMA != MagickTrue || (image->gamma > .45 && image->gamma < .46)) && (ping_found_cHRM != MagickTrue || ping_found_sRGB_cHRM != MagickFalse) && ping_found_iCCP != MagickTrue) { png_set_sRGB(ping,ping_info, Magick_RenderingIntent_to_PNG_RenderingIntent (image->rendering_intent)); file_gamma=1.000f/2.200f; ping_found_sRGB=MagickTrue; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting sRGB as if in input"); } } #if defined(PNG_oFFs_SUPPORTED) if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info); image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info); if (logging != MagickFalse) if (image->page.x || image->page.y) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double) image->page.x,(double) image->page.y); } #endif #if defined(PNG_pHYs_SUPPORTED) if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { if (mng_info->have_global_phys) { png_set_pHYs(ping,ping_info, mng_info->global_x_pixels_per_unit, mng_info->global_y_pixels_per_unit, mng_info->global_phys_unit_type); } } x_resolution=0; y_resolution=0; unit_type=0; if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { /* Set image resolution. */ (void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution, &unit_type); image->resolution.x=(double) x_resolution; image->resolution.y=(double) y_resolution; if (unit_type == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->resolution.x=(double) x_resolution/100.0; image->resolution.y=(double) y_resolution/100.0; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) x_resolution,(double) y_resolution,unit_type); } #endif if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); if ((number_colors == 0) && ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)) { if (mng_info->global_plte_length) { png_set_PLTE(ping,ping_info,mng_info->global_plte, (int) mng_info->global_plte_length); if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { if (mng_info->global_trns_length) { png_warning(ping, "global tRNS has more entries than global PLTE"); } else { png_set_tRNS(ping,ping_info,mng_info->global_trns, (int) mng_info->global_trns_length,NULL); } } #ifdef PNG_READ_bKGD_SUPPORTED if ( #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED mng_info->have_saved_bkgd_index || #endif png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { png_color_16 background; #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED if (mng_info->have_saved_bkgd_index) background.index=mng_info->saved_bkgd_index; #endif if (png_get_valid(ping, ping_info, PNG_INFO_bKGD)) background.index=ping_background->index; background.red=(png_uint_16) mng_info->global_plte[background.index].red; background.green=(png_uint_16) mng_info->global_plte[background.index].green; background.blue=(png_uint_16) mng_info->global_plte[background.index].blue; background.gray=(png_uint_16) mng_info->global_plte[background.index].green; png_set_bKGD(ping,ping_info,&background); } #endif } else png_error(ping,"No global PLTE in file"); } } #ifdef PNG_READ_bKGD_SUPPORTED if (mng_info->have_global_bkgd && (!png_get_valid(ping,ping_info,PNG_INFO_bKGD))) image->background_color=mng_info->mng_global_bkgd; if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { unsigned int bkgd_scale; /* Set image background color. * Scale background components to 16-bit, then scale * to quantum depth */ bkgd_scale = 1; if (ping_file_depth == 1) bkgd_scale = 255; else if (ping_file_depth == 2) bkgd_scale = 85; else if (ping_file_depth == 4) bkgd_scale = 17; if (ping_file_depth <= 8) bkgd_scale *= 257; ping_background->red *= bkgd_scale; ping_background->green *= bkgd_scale; ping_background->blue *= bkgd_scale; if (logging != MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d)\n" " bkgd_scale=%d. ping_background=(%d,%d,%d)", ping_background->red,ping_background->green, ping_background->blue, bkgd_scale,ping_background->red, ping_background->green,ping_background->blue); } image->background_color.red= ScaleShortToQuantum(ping_background->red); image->background_color.green= ScaleShortToQuantum(ping_background->green); image->background_color.blue= ScaleShortToQuantum(ping_background->blue); image->background_color.alpha=OpaqueAlpha; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->background_color=(%.20g,%.20g,%.20g).", (double) image->background_color.red, (double) image->background_color.green, (double) image->background_color.blue); } #endif /* PNG_READ_bKGD_SUPPORTED */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { /* Image has a tRNS chunk. */ int max_sample; size_t one = 1; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG tRNS chunk."); max_sample = (int) ((one << ping_file_depth) - 1); if ((ping_color_type == PNG_COLOR_TYPE_GRAY && (int)ping_trans_color->gray > max_sample) || (ping_color_type == PNG_COLOR_TYPE_RGB && ((int)ping_trans_color->red > max_sample || (int)ping_trans_color->green > max_sample || (int)ping_trans_color->blue > max_sample))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Ignoring PNG tRNS chunk with out-of-range sample."); png_free_data(ping, ping_info, PNG_FREE_TRNS, 0); png_set_invalid(ping,ping_info,PNG_INFO_tRNS); image->alpha_trait=UndefinedPixelTrait; } else { int scale_to_short; scale_to_short = 65535L/((1UL << ping_file_depth)-1); /* Scale transparent_color to short */ transparent_color.red= scale_to_short*ping_trans_color->red; transparent_color.green= scale_to_short*ping_trans_color->green; transparent_color.blue= scale_to_short*ping_trans_color->blue; transparent_color.alpha= scale_to_short*ping_trans_color->gray; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Raw tRNS graylevel = %d, scaled graylevel = %d.", (int) ping_trans_color->gray,(int) transparent_color.alpha); } transparent_color.red=transparent_color.alpha; transparent_color.green=transparent_color.alpha; transparent_color.blue=transparent_color.alpha; } } } #if defined(PNG_READ_sBIT_SUPPORTED) if (mng_info->have_global_sbit) { if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT)) png_set_sBIT(ping,ping_info,&mng_info->global_sbit); } #endif num_passes=png_set_interlace_handling(ping); png_read_update_info(ping,ping_info); ping_rowbytes=png_get_rowbytes(ping,ping_info); /* Initialize image structure. */ mng_info->image_box.left=0; mng_info->image_box.right=(ssize_t) ping_width; mng_info->image_box.top=0; mng_info->image_box.bottom=(ssize_t) ping_height; if (mng_info->mng_type == 0) { mng_info->mng_width=ping_width; mng_info->mng_height=ping_height; mng_info->frame=mng_info->image_box; mng_info->clip=mng_info->image_box; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } image->compression=ZipCompression; image->columns=ping_width; image->rows=ping_height; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { double image_gamma = image->gamma; (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%f",(float) image_gamma); if (image_gamma > 0.75) { /* Set image->rendering_intent to Undefined, * image->colorspace to GRAY, and reset image->chromaticity. */ image->intensity = Rec709LuminancePixelIntensityMethod; SetImageColorspace(image,LinearGRAYColorspace,exception); } else { RenderingIntent save_rendering_intent = image->rendering_intent; ChromaticityInfo save_chromaticity = image->chromaticity; SetImageColorspace(image,GRAYColorspace,exception); image->rendering_intent = save_rendering_intent; image->chromaticity = save_chromaticity; } image->gamma = image_gamma; } else { double image_gamma = image->gamma; (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%f",(float) image_gamma); if (image_gamma > 0.75) { /* Set image->rendering_intent to Undefined, * image->colorspace to GRAY, and reset image->chromaticity. */ image->intensity = Rec709LuminancePixelIntensityMethod; SetImageColorspace(image,RGBColorspace,exception); } else { RenderingIntent save_rendering_intent = image->rendering_intent; ChromaticityInfo save_chromaticity = image->chromaticity; SetImageColorspace(image,sRGBColorspace,exception); image->rendering_intent = save_rendering_intent; image->chromaticity = save_chromaticity; } image->gamma = image_gamma; } (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace=%d",(int) image->colorspace); if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || ((int) ping_bit_depth < 16 && (int) ping_color_type == PNG_COLOR_TYPE_GRAY)) { size_t one; image->storage_class=PseudoClass; one=1; image->colors=one << ping_file_depth; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->colors > 256) image->colors=256; #else if (image->colors > 65536L) image->colors=65536L; #endif if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); image->colors=(size_t) number_colors; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG PLTE chunk: number_colors: %d.",number_colors); } } if (image->storage_class == PseudoClass) { /* Initialize image colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) png_error(ping,"Memory allocation failed"); if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); for (i=0; i < (ssize_t) number_colors; i++) { image->colormap[i].red=ScaleCharToQuantum(palette[i].red); image->colormap[i].green=ScaleCharToQuantum(palette[i].green); image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue); } for ( ; i < (ssize_t) image->colors; i++) { image->colormap[i].red=0; image->colormap[i].green=0; image->colormap[i].blue=0; } } } /* Set some properties for reporting by "identify" */ { char msg[MagickPathExtent]; /* encode ping_width, ping_height, ping_file_depth, ping_color_type, ping_interlace_method in value */ (void) FormatLocaleString(msg,MagickPathExtent, "%d, %d",(int) ping_width, (int) ping_height); (void) SetImageProperty(image,"png:IHDR.width,height",msg,exception); (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) ping_file_depth); (void) SetImageProperty(image,"png:IHDR.bit_depth",msg,exception); (void) FormatLocaleString(msg,MagickPathExtent,"%d (%s)", (int) ping_color_type, Magick_ColorType_from_PNG_ColorType((int)ping_color_type)); (void) SetImageProperty(image,"png:IHDR.color_type",msg,exception); if (ping_interlace_method == 0) { (void) FormatLocaleString(msg,MagickPathExtent,"%d (Not interlaced)", (int) ping_interlace_method); } else if (ping_interlace_method == 1) { (void) FormatLocaleString(msg,MagickPathExtent,"%d (Adam7 method)", (int) ping_interlace_method); } else { (void) FormatLocaleString(msg,MagickPathExtent,"%d (Unknown method)", (int) ping_interlace_method); } (void) SetImageProperty(image,"png:IHDR.interlace_method", msg,exception); if (number_colors != 0) { (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) number_colors); (void) SetImageProperty(image,"png:PLTE.number_colors",msg, exception); } } #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,ping_info,exception); #endif #if defined(PNG_READ_eXIf_SUPPORTED) read_eXIf_chunk(image,ping,ping_info,exception); #endif /* Read image scanlines. */ if (image->delay != 0) mng_info->scenes_found++; if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || ( (image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)))) { /* This happens later in non-ping decodes */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) image->storage_class=DirectClass; image->alpha_trait= (((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? BlendPixelTrait : UndefinedPixelTrait; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping PNG image data for scene %.20g",(double) mng_info->scenes_found-1); png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()."); return(image); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG IDAT chunk(s)"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif return(DestroyImageList(image)); } if (num_passes > 1) pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes* sizeof(*ping_pixels)); else pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Memory allocation failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting PNG pixels to pixel packets"); /* Convert PNG pixels to pixel packets. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Failed to allocate quantum_info"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); { MagickBooleanType found_transparent_pixel; found_transparent_pixel=MagickFalse; if (image->storage_class == DirectClass) { for (pass=0; pass < num_passes; pass++) { /* Convert image to DirectClass pixel packets. */ image->alpha_trait= (((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? BlendPixelTrait : UndefinedPixelTrait; for (y=0; y < (ssize_t) image->rows; y++) { if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayAlphaQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBAQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, IndexQuantum,ping_pixels+row_offset,exception); else /* ping_color_type == PNG_COLOR_TYPE_RGB */ (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBQuantum,ping_pixels+row_offset,exception); if (found_transparent_pixel == MagickFalse) { /* Is there a transparent pixel in the row? */ if (y== 0 && logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Looking for cheap transparent pixel"); for (x=(ssize_t) image->columns-1; x >= 0; x--) { if ((ping_color_type == PNG_COLOR_TYPE_RGBA || ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) && (GetPixelAlpha(image,q) != OpaqueAlpha)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } if ((ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_GRAY) && (ScaleQuantumToShort(GetPixelRed(image,q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(image,q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(image,q)) == transparent_color.blue)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } q+=GetPixelChannels(image); } } if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag, (MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (y < (long) image->rows) break; if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } } } else /* image->storage_class != DirectClass */ for (pass=0; pass < num_passes; pass++) { register Quantum *r; /* Convert grayscale image to PseudoClass pixel packets. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting grayscale pixels to pixel packets"); image->alpha_trait=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ? BlendPixelTrait : UndefinedPixelTrait; quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns, (image->alpha_trait == BlendPixelTrait? 2 : 1)* sizeof(*quantum_scanline)); if (quantum_scanline == (Quantum *) NULL) png_error(ping,"Memory allocation failed"); for (y=0; y < (ssize_t) image->rows; y++) { Quantum alpha; if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=ping_pixels+row_offset; r=quantum_scanline; switch (ping_bit_depth) { case 8: { if (ping_color_type == 4) for (x=(ssize_t) image->columns-1; x >= 0; x--) { *r++=*p++; alpha=ScaleCharToQuantum((unsigned char)*p++); SetPixelAlpha(image,alpha,q); if (alpha != OpaqueAlpha) found_transparent_pixel = MagickTrue; q+=GetPixelChannels(image); } else for (x=(ssize_t) image->columns-1; x >= 0; x--) *r++=*p++; break; } case 16: { for (x=(ssize_t) image->columns-1; x >= 0; x--) { #if (MAGICKCORE_QUANTUM_DEPTH >= 16) unsigned long quantum; if (image->colors > 256) quantum=(((unsigned int) *p++) << 8); else quantum=0; quantum|=(*p++); *r=ScaleShortToQuantum(quantum); r++; if (ping_color_type == 4) { if (image->colors > 256) quantum=(((unsigned int) *p++) << 8); else quantum=0; quantum|=(*p++); alpha=ScaleShortToQuantum(quantum); SetPixelAlpha(image,alpha,q); if (alpha != OpaqueAlpha) found_transparent_pixel = MagickTrue; q+=GetPixelChannels(image); } #else /* MAGICKCORE_QUANTUM_DEPTH == 8 */ *r++=(*p++); p++; /* strip low byte */ if (ping_color_type == 4) { SetPixelAlpha(image,*p++,q); if (GetPixelAlpha(image,q) != OpaqueAlpha) found_transparent_pixel = MagickTrue; p++; q+=GetPixelChannels(image); } #endif } break; } default: break; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; /* Transfer image scanline. */ r=quantum_scanline; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*r++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline); if (y < (long) image->rows) break; if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } } image->alpha_trait=found_transparent_pixel ? BlendPixelTrait : UndefinedPixelTrait; if (logging != MagickFalse) { if (found_transparent_pixel != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found transparent pixel"); else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No transparent pixel was found"); ping_color_type&=0x03; } } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->storage_class == PseudoClass) { PixelTrait alpha_trait; alpha_trait=image->alpha_trait; image->alpha_trait=UndefinedPixelTrait; (void) SyncImage(image,exception); image->alpha_trait=alpha_trait; } png_read_end(ping,end_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=%d\n",(int) image->storage_class); } if (image_info->number_scenes != 0 && mng_info->scenes_found-1 < (ssize_t) image_info->first_scene && image->delay != 0) { png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); image->colors=2; (void) SetImageBackgroundColor(image,exception); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() early."); return(image); } if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { ClassType storage_class; /* Image has a transparent background. */ storage_class=image->storage_class; image->alpha_trait=BlendPixelTrait; /* Balfour fix from imagemagick discourse server, 5 Feb 2010 */ if (storage_class == PseudoClass) { if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { for (x=0; x < ping_num_trans; x++) { image->colormap[x].alpha_trait=BlendPixelTrait; image->colormap[x].alpha = ScaleCharToQuantum((unsigned char)ping_trans_alpha[x]); } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY) { for (x=0; x < (int) image->colors; x++) { if (ScaleQuantumToShort(image->colormap[x].red) == transparent_color.alpha) { image->colormap[x].alpha_trait=BlendPixelTrait; image->colormap[x].alpha = (Quantum) TransparentAlpha; } } } (void) SyncImage(image,exception); } #if 1 /* Should have already been done above, but glennrp problem P10 * needs this. */ else { for (y=0; y < (ssize_t) image->rows; y++) { image->storage_class=storage_class; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; /* Caution: on a Q8 build, this does not distinguish between * 16-bit colors that differ only in the low byte */ for (x=(ssize_t) image->columns-1; x >= 0; x--) { if (ScaleQuantumToShort(GetPixelRed(image,q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(image,q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(image,q)) == transparent_color.blue) { SetPixelAlpha(image,TransparentAlpha,q); } else { SetPixelAlpha(image,OpaqueAlpha,q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif image->storage_class=DirectClass; } for (j = 0; j < 2; j++) { if (j == 0) status = png_get_text(ping,ping_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; else status = png_get_text(ping,end_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) for (i=0; i < (ssize_t) num_text; i++) { /* Check for a profile */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG text chunk"); if (strlen(text[i].key) > 16 && memcmp(text[i].key, "Raw profile type ",17) == 0) { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember(text[i].key+17,value) == MagickFalse) { (void) Magick_png_read_raw_profile(ping,image,image_info,text, (int) i,exception); num_raw_profiles++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Read raw profile %s",text[i].key+17); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping raw profile %s",text[i].key+17); } } else { char *value; length=text[i].text_length; value=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*value)); if (value == (char *) NULL) { png_error(ping,"Memory allocation failed"); break; } *value='\0'; (void) ConcatenateMagickString(value,text[i].text,length+2); /* Don't save "density" or "units" property if we have a pHYs * chunk */ if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) || (LocaleCompare(text[i].key,"density") != 0 && LocaleCompare(text[i].key,"units") != 0)) (void) SetImageProperty(image,text[i].key,value,exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu\n" " Keyword: %s", (unsigned long) length, text[i].key); } value=DestroyString(value); } } num_text_total += num_text; } #ifdef MNG_OBJECT_BUFFERS /* Store the object if necessary. */ if (object_id && !mng_info->frozen[object_id]) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) { /* create a new object buffer. */ mng_info->ob[object_id]=(MngBuffer *) AcquireMagickMemory(sizeof(MngBuffer)); if (mng_info->ob[object_id] != (MngBuffer *) NULL) { mng_info->ob[object_id]->image=(Image *) NULL; mng_info->ob[object_id]->reference_count=1; } } if ((mng_info->ob[object_id] == (MngBuffer *) NULL) || mng_info->ob[object_id]->frozen) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) png_error(ping,"Memory allocation failed"); if (mng_info->ob[object_id]->frozen) png_error(ping,"Cannot overwrite frozen MNG object buffer"); } else { if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image=DestroyImage (mng_info->ob[object_id]->image); mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue, exception); if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image->file=(FILE *) NULL; else png_error(ping, "Cloning image for object buffer failed"); if (ping_width > 250000L || ping_height > 250000L) png_error(ping,"PNG Image dimensions are too large."); mng_info->ob[object_id]->width=ping_width; mng_info->ob[object_id]->height=ping_height; mng_info->ob[object_id]->color_type=ping_color_type; mng_info->ob[object_id]->sample_depth=ping_bit_depth; mng_info->ob[object_id]->interlace_method=ping_interlace_method; mng_info->ob[object_id]->compression_method= ping_compression_method; mng_info->ob[object_id]->filter_method=ping_filter_method; if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp plte; /* Copy the PLTE to the object buffer. */ png_get_PLTE(ping,ping_info,&plte,&number_colors); mng_info->ob[object_id]->plte_length=number_colors; for (i=0; i < number_colors; i++) { mng_info->ob[object_id]->plte[i]=plte[i]; } } else mng_info->ob[object_id]->plte_length=0; } } #endif /* Set image->alpha_trait to MagickTrue if the input colortype supports * alpha or if a valid tRNS chunk is present, no matter whether there * is actual transparency present. */ image->alpha_trait=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? BlendPixelTrait : UndefinedPixelTrait; if (image->alpha_trait == BlendPixelTrait) (void) SetImageStorageClass(image,DirectClass,exception); #if 0 /* I'm not sure what's wrong here but it does not work. */ if (image->alpha_trait != UndefinedPixelTrait) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) SetImageType(image,GrayscaleAlphaType,exception); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteAlphaType,exception); else (void) SetImageType(image,TrueColorAlphaType,exception); } else { if (ping_color_type == PNG_COLOR_TYPE_GRAY) (void) SetImageType(image,GrayscaleType,exception); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteType,exception); else (void) SetImageType(image,TrueColorType,exception); } #endif /* Set more properties for identify to retrieve */ { char msg[MagickPathExtent]; if (num_text_total != 0) { /* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */ (void) FormatLocaleString(msg,MagickPathExtent, "%d tEXt/zTXt/iTXt chunks were found", num_text_total); (void) SetImageProperty(image,"png:text",msg, exception); } if (num_raw_profiles != 0) { (void) FormatLocaleString(msg,MagickPathExtent, "%d were found", num_raw_profiles); (void) SetImageProperty(image,"png:text-encoded profiles",msg, exception); } /* cHRM chunk: */ if (ping_found_cHRM != MagickFalse) { (void) FormatLocaleString(msg,MagickPathExtent,"%s", "chunk was found (see Chromaticity, above)"); (void) SetImageProperty(image,"png:cHRM",msg, exception); } /* bKGD chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { (void) FormatLocaleString(msg,MagickPathExtent,"%s", "chunk was found (see Background color, above)"); (void) SetImageProperty(image,"png:bKGD",msg, exception); } (void) FormatLocaleString(msg,MagickPathExtent,"%s", "chunk was found"); #if defined(PNG_iCCP_SUPPORTED) /* iCCP chunk: */ if (ping_found_iCCP != MagickFalse) (void) SetImageProperty(image,"png:iCCP",msg, exception); #endif if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) (void) SetImageProperty(image,"png:tRNS",msg, exception); #if defined(PNG_sRGB_SUPPORTED) /* sRGB chunk: */ if (ping_found_sRGB != MagickFalse) { (void) FormatLocaleString(msg,MagickPathExtent, "intent=%d (%s)", (int) intent, Magick_RenderingIntentString_from_PNG_RenderingIntent(intent)); (void) SetImageProperty(image,"png:sRGB",msg, exception); } #endif /* gAMA chunk: */ if (ping_found_gAMA != MagickFalse) { (void) FormatLocaleString(msg,MagickPathExtent, "gamma=%.8g (See Gamma, above)", file_gamma); (void) SetImageProperty(image,"png:gAMA",msg, exception); } #if defined(PNG_pHYs_SUPPORTED) /* pHYs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { (void) FormatLocaleString(msg,MagickPathExtent, "x_res=%.10g, y_res=%.10g, units=%d", (double) x_resolution,(double) y_resolution, unit_type); (void) SetImageProperty(image,"png:pHYs",msg, exception); } #endif #if defined(PNG_oFFs_SUPPORTED) /* oFFs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { (void) FormatLocaleString(msg,MagickPathExtent, "x_off=%.20g, y_off=%.20g", (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:oFFs",msg, exception); } #endif #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,end_info,exception); #endif #if defined(PNG_READ_eXIf_SUPPORTED) read_eXIf_chunk(image,ping,end_info,exception); #endif /* caNv chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || (image->page.x != 0 || image->page.y != 0)) { (void) FormatLocaleString(msg,MagickPathExtent, "width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:caNv",msg, exception); } } /* Relinquish resources. */ png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block, revert to * Throwing an Exception when an error occurs. */ return(image); /* end of reading one PNG image */ } static Image *ReadPNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MagickPathExtent]; ssize_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()"); image=AcquireImage(image_info,exception); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Verify PNG signature. */ count=ReadBlob(image,8,(unsigned char *) magic_number); if ((count < 8) || (memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a PNG datastream. */ if (GetBlobSize(image) < 61) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) memset(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOnePNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if ((image->columns == 0) || (image->rows == 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if ((IssRGBColorspace(image->colorspace) != MagickFalse) && ((image->gamma < .45) || (image->gamma > .46)) && !(image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "SetImageColorspace to RGBColorspace"); SetImageColorspace(image,RGBColorspace,exception); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace: %d", (int) image->colorspace); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()"); return(image); } #if defined(JNG_SUPPORTED) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadOneJNGImage method is: % % Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static void DestroyJNG(unsigned char *chunk,Image **color_image, ImageInfo **color_image_info,Image **alpha_image, ImageInfo **alpha_image_info) { (void) RelinquishMagickMemory(chunk); if (color_image_info && *color_image_info) { DestroyImageInfo(*color_image_info); *color_image_info = (ImageInfo *)NULL; } if (alpha_image_info && *alpha_image_info) { DestroyImageInfo(*alpha_image_info); *alpha_image_info = (ImageInfo *)NULL; } if (color_image && *color_image) { DestroyImage(*color_image); *color_image = (Image *)NULL; } if (alpha_image && *alpha_image) { DestroyImage(*alpha_image); *alpha_image = (Image *)NULL; } } static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const Quantum *s; register ssize_t i, x; register Quantum *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MagickPathExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MagickPathExtent); length=(size_t) ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) { DestroyJNG(NULL,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (length > GetBlobSize(image)) { DestroyJNG(NULL,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) { DestroyJNG(NULL,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } for ( ; i < (ssize_t) length; i++) chunk[i]='\0'; p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(png_uint_32)mng_get_long(p); jng_height=(png_uint_32)mng_get_long(&p[4]); if ((jng_width == 0) || (jng_height == 0)) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError, "NegativeOrZeroImageSize"); } jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (jng_width > 65535 || jng_height > 65535 || (long) jng_width > GetMagickResourceLimit(WidthResource) || (long) jng_height > GetMagickResourceLimit(HeightResource)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width or height too large: (%lu x %lu)", (long) jng_width, (long) jng_height); DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info,exception); if (color_image == (Image *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); (void) AcquireUniqueFilename(color_image->filename); status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info,exception); if (alpha_image == (Image *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if ((length != 0) && (color_image != (Image *) NULL)) (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if ((alpha_image != NULL) && (image_info->ping == MagickFalse) && (length != 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->resolution.x=(double) mng_get_long(p); image->resolution.y=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->resolution.x=image->resolution.x/100.0f; image->resolution.y=image->resolution.y/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into alpha samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); if (color_image != (Image *) NULL) color_image=DestroyImageList(color_image); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MagickPathExtent, "jpeg:%s",color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) { DestroyJNG(NULL,NULL,NULL,&alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->rows=jng_height; image->columns=jng_width; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, &alpha_image_info); jng_image=DestroyImageList(jng_image); return(DestroyImageList(image)); } if ((image->columns != jng_image->columns) || (image->rows != jng_image->rows)) { DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, &alpha_image_info); jng_image=DestroyImageList(jng_image); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelRed(image,GetPixelRed(jng_image,s),q); SetPixelGreen(image,GetPixelGreen(jng_image,s),q); SetPixelBlue(image,GetPixelBlue(jng_image,s),q); q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) CloseBlob(alpha_image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading alpha from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MagickPathExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; if (image->alpha_trait != UndefinedPixelTrait) for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelAlpha(image,GetPixelRed(jng_image,s),q); q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } else for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelAlpha(image,GetPixelRed(jng_image,s),q); if (GetPixelAlpha(image,q) != OpaqueAlpha) image->alpha_trait=BlendPixelTrait; q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage()"); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJNGImage() reads a JPEG Network Graphics (JNG) image file % (including the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadJNGImage method is: % % Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo % *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MagickPathExtent]; size_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()"); image=AcquireImage(image_info,exception); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (LocaleCompare(image_info->magick,"JNG") != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify JNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if ((count < 8) || (memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a JNG datastream. */ if (GetBlobSize(image) < 147) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) memset(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneJNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (image->columns == 0 || image->rows == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); ThrowReaderException(CorruptImageError,"CorruptImage"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()"); return(image); } #endif static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MagickPathExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if ((count < 8) || (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False during convert or mogrify */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MagickPathExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if ((length > PNG_UINT_31_MAX) || (length > GetBlobSize(image)) || (count < 4)) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 9) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) { (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream","`%s'", image->filename); if (object_id >= MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS-1; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { /* Read global PLTE. */ if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) { mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (((p-chunk) < (long) length) && *p) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || (length % 2) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters <= 0) skipping_loop=loop_level; else { if (loop_iters > GetMagickResourceLimit(ListLengthResource)) loop_iters=GetMagickResourceLimit(ListLengthResource); if (loop_iters >= 2147483647L) loop_iters=2147483647L; mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=((png_uint_32) p[12] << 8) & (png_uint_32) p[13]; else basi_red=0; if (length > 13) basi_green=((png_uint_32) p[14] << 8) & (png_uint_32) p[15]; else basi_green=0; if (length > 15) basi_blue=((png_uint_32) p[16] << 8) & (png_uint_32) p[17]; else basi_blue=0; if (length > 17) basi_alpha=((png_uint_32) p[18] << 8) & (png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { if (prev != (Quantum *) NULL) prev=(Quantum *) RelinquishMagickMemory(prev); if (next != (Quantum *) NULL) next=(Quantum *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) memcpy(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) memcpy(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (Quantum *) NULL) break; q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { /* Interpolate */ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelChannel() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } /* To do: Rewrite using Get/Set***PixelChannel() */ else { /* Interpolate */ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { /* Interpolate */ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneMNGImage();"); return(image); } static Image *ReadMNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()"); image=AcquireImage(image_info,exception); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) memset(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneMNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadMNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()"); return(GetFirstImageInList(image)); } #else /* PNG_LIBPNG_VER > 10011 */ static Image *ReadPNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "PNG library is too old","`%s'",image_info->filename); return(Image *) NULL; } static Image *ReadMNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { return(ReadPNGImage(image_info,exception)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNGImage() adds properties for the PNG image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNGImage method is: % % size_t RegisterPNGImage(void) % */ ModuleExport size_t RegisterPNGImage(void) { char version[MagickPathExtent]; MagickInfo *entry; static const char *PNGNote= { "See http://www.libpng.org/ for details about the PNG format." }, *JNGNote= { "See http://www.libpng.org/pub/mng/ for details about the JNG\n" "format." }, *MNGNote= { "See http://www.libpng.org/pub/mng/ for details about the MNG\n" "format." }; *version='\0'; #if defined(PNG_LIBPNG_VER_STRING) (void) ConcatenateMagickString(version,"libpng ",MagickPathExtent); (void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING, MagickPathExtent); if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0) { (void) ConcatenateMagickString(version,",",MagickPathExtent); (void) ConcatenateMagickString(version,png_get_libpng_ver(NULL), MagickPathExtent); } #endif entry=AcquireMagickInfo("PNG","MNG","Multiple-image Network Graphics"); entry->flags|=CoderDecoderSeekableStreamFlag; #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMNGImage; entry->encoder=(EncodeImageHandler *) WriteMNGImage; #endif entry->magick=(IsImageFormatHandler *) IsMNG; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("video/x-mng"); entry->note=ConstantString(MNGNote); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG","Portable Network Graphics"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); if (*version != '\0') entry->version=ConstantString(version); entry->note=ConstantString(PNGNote); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG8", "8-bit indexed with optional binary transparency"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG24", "opaque or binary transparent 24-bit RGB"); *version='\0'; #if defined(ZLIB_VERSION) (void) ConcatenateMagickString(version,"zlib ",MagickPathExtent); (void) ConcatenateMagickString(version,ZLIB_VERSION,MagickPathExtent); if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0) { (void) ConcatenateMagickString(version,",",MagickPathExtent); (void) ConcatenateMagickString(version,zlib_version,MagickPathExtent); } #endif if (*version != '\0') entry->version=ConstantString(version); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG32","opaque or transparent 32-bit RGBA"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG48", "opaque or binary transparent 48-bit RGB"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG64","opaque or transparent 64-bit RGBA"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG00", "PNG inheriting bit-depth, color-type from original, if possible"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","JNG","JPEG Network Graphics"); #if defined(JNG_SUPPORTED) #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJNGImage; entry->encoder=(EncodeImageHandler *) WriteJNGImage; #endif #endif entry->magick=(IsImageFormatHandler *) IsJNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/x-jng"); entry->note=ConstantString(JNGNote); (void) RegisterMagickInfo(entry); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE ping_semaphore=AcquireSemaphoreInfo(); #endif return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNGImage() removes format registrations made by the % PNG module from the list of supported formats. % % The format of the UnregisterPNGImage method is: % % UnregisterPNGImage(void) % */ ModuleExport void UnregisterPNGImage(void) { (void) UnregisterMagickInfo("MNG"); (void) UnregisterMagickInfo("PNG"); (void) UnregisterMagickInfo("PNG8"); (void) UnregisterMagickInfo("PNG24"); (void) UnregisterMagickInfo("PNG32"); (void) UnregisterMagickInfo("PNG48"); (void) UnregisterMagickInfo("PNG64"); (void) UnregisterMagickInfo("PNG00"); (void) UnregisterMagickInfo("JNG"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE if (ping_semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&ping_semaphore); #endif } #if defined(MAGICKCORE_PNG_DELEGATE) #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMNGImage() writes an image in the Portable Network Graphics % Group's "Multiple-image Network Graphics" encoded image format. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteMNGImage method is: % % MagickBooleanType WriteMNGImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % % To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also % "To do" under ReadPNGImage): % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % Write the iCCP chunk at MNG level when (icc profile length > 0) % % Improve selection of color type (use indexed-colour or indexed-colour % with tRNS when 256 or fewer unique RGBA values are present). % % Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3) % This will be complicated if we limit ourselves to generating MNG-LC % files. For now we ignore disposal method 3 and simply overlay the next % image on it. % % Check for identical PLTE's or PLTE/tRNS combinations and use a % global MNG PLTE or PLTE/tRNS combination when appropriate. % [mostly done 15 June 1999 but still need to take care of tRNS] % % Check for identical sRGB and replace with a global sRGB (and remove % gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and % replace with global gAMA/cHRM (or with sRGB if appropriate; replace % local gAMA/cHRM with local sRGB if appropriate). % % Check for identical sBIT chunks and write global ones. % % Provide option to skip writing the signature tEXt chunks. % % Use signatures to detect identical objects and reuse the first % instance of such objects instead of writing duplicate objects. % % Use a smaller-than-32k value of compression window size when % appropriate. % % Encode JNG datastreams. Mostly done as of 5.5.2; need to write % ancillary text chunks and save profiles. % % Provide an option to force LC files (to ensure exact framing rate) % instead of VLC. % % Provide an option to force VLC files instead of LC, even when offsets % are present. This will involve expanding the embedded images with a % transparent region at the top and/or left. */ static void Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping, png_info *ping_info, unsigned char *profile_type, unsigned char *profile_description, unsigned char *profile_data, png_uint_32 length) { png_textp text; register ssize_t i; unsigned char *sp; png_charp dp; png_uint_32 allocated_length, description_length; unsigned char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0) return; if (image_info->verbose) { (void) printf("writing raw profile: type=%s, length=%.20g\n", (char *) profile_type, (double) length); } #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif description_length=(png_uint_32) strlen((const char *) profile_description); allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20 + description_length); #if PNG_LIBPNG_VER >= 10400 text[0].text=(png_charp) png_malloc(ping, (png_alloc_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80); #else text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80); #endif text[0].key[0]='\0'; (void) ConcatenateMagickString(text[0].key, "Raw profile type ",MagickPathExtent); (void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62); sp=profile_data; dp=text[0].text; *dp++='\n'; (void) CopyMagickString(dp,(const char *) profile_description, allocated_length); dp+=description_length; *dp++='\n'; (void) FormatLocaleString(dp,allocated_length- (png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length); dp+=8; for (i=0; i < (ssize_t) length; i++) { if (i%36 == 0) *dp++='\n'; *(dp++)=(char) hex[((*sp >> 4) & 0x0f)]; *(dp++)=(char) hex[((*sp++ ) & 0x0f)]; } *dp++='\n'; *dp='\0'; text[0].text_length=(png_size_t) (dp-text[0].text); text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? -1 : 0; if (text[0].text_length <= allocated_length) png_set_text(ping,ping_info,text,1); png_free(ping,text[0].text); png_free(ping,text[0].key); png_free(ping,text); } static inline MagickBooleanType IsColorEqual(const Image *image, const Quantum *p, const PixelInfo *q) { MagickRealType blue, green, red; red=(MagickRealType) GetPixelRed(image,p); green=(MagickRealType) GetPixelGreen(image,p); blue=(MagickRealType) GetPixelBlue(image,p); if ((AbsolutePixelValue(red-q->red) < MagickEpsilon) && (AbsolutePixelValue(green-q->green) < MagickEpsilon) && (AbsolutePixelValue(blue-q->blue) < MagickEpsilon)) return(MagickTrue); return(MagickFalse); } #if defined(PNG_tIME_SUPPORTED) static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info, const char *timestamp,ExceptionInfo *exception) { int ret; int day, hour, minute, month, second, year; int addhours=0, addminutes=0; png_time ptime; assert(timestamp != (const char *) NULL); LogMagickEvent(CoderEvent,GetMagickModule(), " Writing tIME chunk: timestamp property is %30s\n",timestamp); ret=sscanf(timestamp,"%d-%d-%dT%d:%d:%d",&year,&month,&day,&hour, &minute, &second); addhours=0; addminutes=0; ret=sscanf(timestamp,"%d-%d-%dT%d:%d:%d%d:%d",&year,&month,&day,&hour, &minute, &second, &addhours, &addminutes); LogMagickEvent(CoderEvent,GetMagickModule(), " Date format specified for png:tIME=%s" ,timestamp); LogMagickEvent(CoderEvent,GetMagickModule(), " ret=%d,y=%d, m=%d, d=%d, h=%d, m=%d, s=%d, ah=%d, as=%d", ret,year,month,day,hour,minute,second,addhours,addminutes); if (ret < 6) { LogMagickEvent(CoderEvent,GetMagickModule(), " Invalid date, ret=%d",ret); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "Invalid date format specified for png:tIME","`%s' (ret=%d)", image->filename,ret); return; } if (addhours < 0) { addhours+=24; addminutes=-addminutes; day--; } hour+=addhours; minute+=addminutes; if (day == 0) { month--; day=31; if(month == 2) day=28; else { if(month == 4 || month == 6 || month == 9 || month == 11) day=30; else day=31; } } if (month == 0) { month++; year--; } if (minute > 59) { hour++; minute-=60; } if (hour > 23) { day ++; hour -=24; } if (hour < 0) { day --; hour +=24; } /* To do: fix this for leap years */ if (day > 31 || (month == 2 && day > 28) || ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30)) { month++; day = 1; } if (month > 12) { year++; month=1; } ptime.year = year; ptime.month = month; ptime.day = day; ptime.hour = hour; ptime.minute = minute; ptime.second = second; LogMagickEvent(CoderEvent,GetMagickModule(), " png_set_tIME: y=%d, m=%d, d=%d, h=%d, m=%d, s=%d, ah=%d, am=%d", ptime.year, ptime.month, ptime.day, ptime.hour, ptime.minute, ptime.second, addhours, addminutes); png_set_tIME(ping,info,&ptime); } #endif /* Write one PNG image */ static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char s[2]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%g", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBA(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBA(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBA(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *s; register Quantum *q, *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->alpha_trait=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,q) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image, q, opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(image,q,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image, q, opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,q) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image, q, transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,q); ping_trans_color.green=(unsigned short) GetPixelGreen(image,q); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,q); ping_trans_color.gray=(unsigned short) GetPixelGray(image,q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(image,q,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,q,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,q,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(image,q,semitransparent+i) && GetPixelAlpha(image,q) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image, q, semitransparent+i); } } } q+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != GetPixelGreen(image,s) || GetPixelRed(image,s) != GetPixelBlue(image,s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != 0 && GetPixelRed(image,s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) < OpaqueAlpha/2) { SetPixelViaPixelInfo(image,&image->background_color,r); SetPixelAlpha(image,TransparentAlpha,r); } else SetPixelAlpha(image,OpaqueAlpha,r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha/2 ? TransparentAlpha : OpaqueAlpha); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR04PixelRGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR03RGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR02PixelBlue(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 && GetPixelAlpha(image,r) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),r); } r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",IMimage->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } else if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; else { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates "-define png:compression-strategy", etc. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { /* Add an opaque matte channel */ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { /* Do not write hex-encoded ICC chunk */ name=GetNextImageProfile(image); continue; } } #endif /* WRITE_iCCP */ if (LocaleCompare(name,"exif") == 0) { /* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk */ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXt chunk with uuencoded %s profile", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); /* write orNT if image->orientation is defined */ if (image->orientation != UndefinedOrientation) { unsigned char chunk[6]; (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_orNT); LogPNGChunk(logging,mng_orNT,1L); /* PNG uses Exif orientation values */ chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const Quantum *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write eXIf profile */ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; /* otherwise crashes */ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\0' && *(data+5) == '\0') { /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNGImage() writes a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WritePNGImage method is: % % MagickBooleanType WritePNGImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % % Returns MagickTrue on success, MagickFalse on failure. % % Communicating with the PNG encoder: % % While the datastream written is always in PNG format and normally would % be given the "png" file extension, this method also writes the following % pseudo-formats which are subsets of png: % % o PNG8: An 8-bit indexed PNG datastream is written. If the image has % a depth greater than 8, the depth is reduced. If transparency % is present, the tRNS chunk must only have values 0 and 255 % (i.e., transparency is binary: fully opaque or fully % transparent). If other values are present they will be % 50%-thresholded to binary transparency. If more than 256 % colors are present, they will be quantized to the 4-4-4-1, % 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color % of any resulting fully-transparent pixels is changed to % the image's background color. % % If you want better quantization or dithering of the colors % or alpha than that, you need to do it before calling the % PNG encoder. The pixels contain 8-bit indices even if % they could be represented with 1, 2, or 4 bits. Grayscale % images will be written as indexed PNG files even though the % PNG grayscale type might be slightly more efficient. Please % note that writing to the PNG8 format may result in loss % of color and alpha data. % % o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. The only loss incurred % is reduction of sample depth to 8. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG32: An 8-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 255. The alpha % channel is present even if the image is fully opaque. % The only loss in data is the reduction of the sample depth % to 8. % % o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG64: A 16-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 65535. The alpha % channel is present even if the image is fully opaque. % % o PNG00: A PNG that inherits its colortype and bit-depth from the input % image, if the input was a PNG, is written. If these values % cannot be found, or if the pixels have been changed in a way % that makes this impossible, then "PNG00" falls back to the % regular "PNG" format. % % o -define: For more precise control of the PNG output, you can use the % Image options "png:bit-depth" and "png:color-type". These % can be set from the commandline with "-define" and also % from the application programming interfaces. The options % are case-independent and are converted to lowercase before % being passed to this encoder. % % png:color-type can be 0, 2, 3, 4, or 6. % % When png:color-type is 0 (Grayscale), png:bit-depth can % be 1, 2, 4, 8, or 16. % % When png:color-type is 2 (RGB), png:bit-depth can % be 8 or 16. % % When png:color-type is 3 (Indexed), png:bit-depth can % be 1, 2, 4, or 8. This refers to the number of bits % used to store the index. The color samples always have % bit-depth 8 in indexed PNG files. % % When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte), % png:bit-depth can be 8 or 16. % % If the image cannot be written without loss with the % requested bit-depth and color-type, a PNG file will not % be written, a warning will be issued, and the encoder will % return MagickFalse. % % Since image encoders should not be responsible for the "heavy lifting", % the user should make sure that ImageMagick has already reduced the % image depth and number of colors and limit transparency to binary % transparency prior to attempting to write the image with depth, color, % or transparency limitations. % % Note that another definition, "png:bit-depth-written" exists, but it % is not intended for external use. It is only used internally by the % PNG encoder to inform the JNG encoder of the depth of the alpha channel. % % As of version 6.6.6 the following optimizations are always done: % % o 32-bit depth is reduced to 16. % o 16-bit depth is reduced to 8 if all pixels contain samples whose % high byte and low byte are identical. % o Palette is sorted to remove unused entries and to put a % transparent color first, if BUILD_PNG_PALETTE is defined. % o Opaque matte channel is removed when writing an indexed PNG. % o Grayscale images are reduced to 1, 2, or 4 bit depth if % this can be done without loss and a larger bit depth N was not % requested via the "-define png:bit-depth=N" option. % o If matte channel is present but only one transparent color is % present, RGB+tRNS is written instead of RGBA % o Opaque matte channel is removed (or added, if color-type 4 or 6 % was requested when converting an opaque image). % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { MagickBooleanType excluding, logging, status; MngInfo *mng_info; const char *value; int source; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) memset(mng_info,0,sizeof(MngInfo)); mng_info->image=image; mng_info->equal_backgrounds=MagickTrue; /* See if user has requested a specific PNG subformat */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0; mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0; value=GetImageOption(image_info,"png:format"); if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",value); mng_info->write_png8 = MagickFalse; mng_info->write_png24 = MagickFalse; mng_info->write_png32 = MagickFalse; mng_info->write_png48 = MagickFalse; mng_info->write_png64 = MagickFalse; if (LocaleCompare(value,"png8") == 0) mng_info->write_png8 = MagickTrue; else if (LocaleCompare(value,"png24") == 0) mng_info->write_png24 = MagickTrue; else if (LocaleCompare(value,"png32") == 0) mng_info->write_png32 = MagickTrue; else if (LocaleCompare(value,"png48") == 0) mng_info->write_png48 = MagickTrue; else if (LocaleCompare(value,"png64") == 0) mng_info->write_png64 = MagickTrue; else if ((LocaleCompare(value,"png00") == 0) || LocaleCompare(image_info->magick,"PNG00") == 0) { /* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig. */ value=GetImageProperty(image,"png:IHDR.bit-depth-orig",exception); if (value != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited bit depth=%s",value); if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; } value=GetImageProperty(image,"png:IHDR.color-type-orig",exception); if (value != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited color type=%s",value); if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; } } } if (mng_info->write_png8) { mng_info->write_png_colortype = /* 3 */ 4; mng_info->write_png_depth = 8; image->depth = 8; } if (mng_info->write_png24) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 8; image->depth = 8; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageType(image,TrueColorAlphaType,exception); else (void) SetImageType(image,TrueColorType,exception); (void) SyncImage(image,exception); } if (mng_info->write_png32) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 8; image->depth = 8; image->alpha_trait = BlendPixelTrait; (void) SetImageType(image,TrueColorAlphaType,exception); (void) SyncImage(image,exception); } if (mng_info->write_png48) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 16; image->depth = 16; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageType(image,TrueColorAlphaType,exception); else (void) SetImageType(image,TrueColorType,exception); (void) SyncImage(image,exception); } if (mng_info->write_png64) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 16; image->depth = 16; image->alpha_trait = BlendPixelTrait; (void) SetImageType(image,TrueColorAlphaType,exception); (void) SyncImage(image,exception); } value=GetImageOption(image_info,"png:bit-depth"); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:bit-depth", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:bit-depth=%d was defined.\n",mng_info->write_png_depth); } value=GetImageOption(image_info,"png:color-type"); if (value != (char *) NULL) { /* We must store colortype+1 because 0 is a valid colortype */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_colortype = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:color-type", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:color-type=%d was defined.\n", mng_info->write_png_colortype-1); } /* Check for chunks to be excluded: * * The default is to not exclude any known chunks except for any * listed in the "unused_chunks" array, above. * * Chunks can be listed for exclusion via a "png:exclude-chunk" * define (in the image properties or in the image artifacts) * or via a mng_info member. For convenience, in addition * to or instead of a comma-separated list of chunks, the * "exclude-chunk" string can be simply "all" or "none". * * Note that the "-strip" option provides a convenient way of * doing the equivalent of * * -define png:exclude-chunk="bKGD,caNv,cHRM,eXIf,gAMA,iCCP, * iTXt,pHYs,sRGB,tEXt,zCCP,zTXt,date" * * The exclude-chunk define takes priority over the mng_info. * * A "png:include-chunk" define takes priority over both the * mng_info and the "png:exclude-chunk" define. Like the * "exclude-chunk" string, it can define "all" or "none" as * well as a comma-separated list. Chunks that are unknown to * ImageMagick are always excluded, regardless of their "copy-safe" * status according to the PNG specification, and even if they * appear in the "include-chunk" list. Such defines appearing among * the image options take priority over those found among the image * artifacts. * * Finally, all chunks listed in the "unused_chunks" array are * automatically excluded, regardless of the other instructions * or lack thereof. * * if you exclude sRGB but not gAMA (recommended), then sRGB chunk * will not be written and the gAMA chunk will only be written if it * is not between .45 and .46, or approximately (1.0/2.2). * * If you exclude tRNS and the image has transparency, the colortype * is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA). * * The -strip option causes StripImage() to set the png:include-chunk * artifact to "none,trns,gama". */ mng_info->ping_exclude_bKGD=MagickFalse; mng_info->ping_exclude_caNv=MagickFalse; mng_info->ping_exclude_cHRM=MagickFalse; mng_info->ping_exclude_date=MagickFalse; mng_info->ping_exclude_eXIf=MagickFalse; mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */ mng_info->ping_exclude_gAMA=MagickFalse; mng_info->ping_exclude_iCCP=MagickFalse; /* mng_info->ping_exclude_iTXt=MagickFalse; */ mng_info->ping_exclude_oFFs=MagickFalse; mng_info->ping_exclude_pHYs=MagickFalse; mng_info->ping_exclude_sRGB=MagickFalse; mng_info->ping_exclude_tEXt=MagickFalse; mng_info->ping_exclude_tIME=MagickFalse; mng_info->ping_exclude_tRNS=MagickFalse; mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */ mng_info->ping_exclude_zTXt=MagickFalse; mng_info->ping_preserve_colormap=MagickFalse; value=GetImageOption(image_info,"png:preserve-colormap"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-colormap"); if (value != NULL) mng_info->ping_preserve_colormap=MagickTrue; mng_info->ping_preserve_iCCP=MagickFalse; value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) mng_info->ping_preserve_iCCP=MagickTrue; /* These compression-level, compression-strategy, and compression-filter * defines take precedence over values from the -quality option. */ value=GetImageOption(image_info,"png:compression-level"); if (value == NULL) value=GetImageArtifact(image,"png:compression-level"); if (value != NULL) { /* We have to add 1 to everything because 0 is a valid input, * and we want to use 0 (the default) to mean undefined. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_level = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_level = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_level = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_level = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_level = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_level = 6; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_compression_level = 7; else if (LocaleCompare(value,"7") == 0) mng_info->write_png_compression_level = 8; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_compression_level = 9; else if (LocaleCompare(value,"9") == 0) mng_info->write_png_compression_level = 10; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-level", "=%s",value); } value=GetImageOption(image_info,"png:compression-strategy"); if (value == NULL) value=GetImageArtifact(image,"png:compression-strategy"); if (value != NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_strategy = Z_FILTERED+1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; else if (LocaleCompare(value,"3") == 0) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy = Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else if (LocaleCompare(value,"4") == 0) #ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */ mng_info->write_png_compression_strategy = Z_FIXED+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-strategy", "=%s",value); } value=GetImageOption(image_info,"png:compression-filter"); if (value == NULL) value=GetImageArtifact(image,"png:compression-filter"); if (value != NULL) { /* To do: combinations of filters allowed by libpng * masks 0x08 through 0xf8 * * Implement this as a comma-separated list of 0,1,2,3,4,5 * where 5 is a special case meaning PNG_ALL_FILTERS. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_filter = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_filter = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_filter = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_filter = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_filter = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_filter = 6; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-filter", "=%s",value); } for (source=0; source<8; source++) { value = NULL; if (source == 0) value=GetImageOption(image_info,"png:exclude-chunks"); if (source == 1) value=GetImageArtifact(image,"png:exclude-chunks"); if (source == 2) value=GetImageOption(image_info,"png:exclude-chunk"); if (source == 3) value=GetImageArtifact(image,"png:exclude-chunk"); if (source == 4) value=GetImageOption(image_info,"png:include-chunks"); if (source == 5) value=GetImageArtifact(image,"png:include-chunks"); if (source == 6) value=GetImageOption(image_info,"png:include-chunk"); if (source == 7) value=GetImageArtifact(image,"png:include-chunk"); if (value == NULL) continue; if (source < 4) excluding = MagickTrue; else excluding = MagickFalse; if (logging != MagickFalse) { if (source == 0 || source == 2) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image options.\n", value); else if (source == 1 || source == 3) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image artifacts.\n", value); else if (source == 4 || source == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image options.\n", value); else /* if (source == 5 || source == 7) */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image artifacts.\n", value); } if (IsOptionMember("all",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding; mng_info->ping_exclude_caNv=excluding; mng_info->ping_exclude_cHRM=excluding; mng_info->ping_exclude_date=excluding; mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; mng_info->ping_exclude_gAMA=excluding; mng_info->ping_exclude_iCCP=excluding; /* mng_info->ping_exclude_iTXt=excluding; */ mng_info->ping_exclude_oFFs=excluding; mng_info->ping_exclude_pHYs=excluding; mng_info->ping_exclude_sRGB=excluding; mng_info->ping_exclude_tEXt=excluding; mng_info->ping_exclude_tIME=excluding; mng_info->ping_exclude_tRNS=excluding; mng_info->ping_exclude_zCCP=excluding; mng_info->ping_exclude_zTXt=excluding; } if (IsOptionMember("none",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; /* mng_info->ping_exclude_iTXt=!excluding; */ mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse : MagickTrue; } if (IsOptionMember("bkgd",value) != MagickFalse) mng_info->ping_exclude_bKGD=excluding; if (IsOptionMember("caNv",value) != MagickFalse) mng_info->ping_exclude_caNv=excluding; if (IsOptionMember("chrm",value) != MagickFalse) mng_info->ping_exclude_cHRM=excluding; if (IsOptionMember("date",value) != MagickFalse) mng_info->ping_exclude_date=excluding; if (IsOptionMember("exif",value) != MagickFalse) { mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; } if (IsOptionMember("gama",value) != MagickFalse) mng_info->ping_exclude_gAMA=excluding; if (IsOptionMember("iccp",value) != MagickFalse) mng_info->ping_exclude_iCCP=excluding; #if 0 if (IsOptionMember("itxt",value) != MagickFalse) mng_info->ping_exclude_iTXt=excluding; #endif if (IsOptionMember("offs",value) != MagickFalse) mng_info->ping_exclude_oFFs=excluding; if (IsOptionMember("phys",value) != MagickFalse) mng_info->ping_exclude_pHYs=excluding; if (IsOptionMember("srgb",value) != MagickFalse) mng_info->ping_exclude_sRGB=excluding; if (IsOptionMember("text",value) != MagickFalse) mng_info->ping_exclude_tEXt=excluding; if (IsOptionMember("time",value) != MagickFalse) mng_info->ping_exclude_tIME=excluding; if (IsOptionMember("trns",value) != MagickFalse) mng_info->ping_exclude_tRNS=excluding; if (IsOptionMember("zccp",value) != MagickFalse) mng_info->ping_exclude_zCCP=excluding; if (IsOptionMember("ztxt",value) != MagickFalse) mng_info->ping_exclude_zTXt=excluding; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Chunks to be excluded from the output png:"); if (mng_info->ping_exclude_bKGD != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bKGD"); if (mng_info->ping_exclude_caNv != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " caNv"); if (mng_info->ping_exclude_cHRM != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " cHRM"); if (mng_info->ping_exclude_date != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " date"); if (mng_info->ping_exclude_EXIF != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " EXIF"); if (mng_info->ping_exclude_eXIf != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " eXIf"); if (mng_info->ping_exclude_gAMA != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " gAMA"); if (mng_info->ping_exclude_iCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iCCP"); #if 0 if (mng_info->ping_exclude_iTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iTXt"); #endif if (mng_info->ping_exclude_oFFs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " oFFs"); if (mng_info->ping_exclude_pHYs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pHYs"); if (mng_info->ping_exclude_sRGB != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " sRGB"); if (mng_info->ping_exclude_tEXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tEXt"); if (mng_info->ping_exclude_tIME != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tIME"); if (mng_info->ping_exclude_tRNS != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS"); if (mng_info->ping_exclude_zCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zCCP"); if (mng_info->ping_exclude_zTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zTXt"); } mng_info->need_blob = MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image,exception); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()"); return(status); } #if defined(JNG_SUPPORTED) /* Write one JNG image */ static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image,ExceptionInfo *exception) { Image *jpeg_image; ImageInfo *jpeg_image_info; MagickBooleanType logging, status; size_t length; unsigned char *blob, chunk[80], *p; unsigned int jng_alpha_compression_method, jng_alpha_sample_depth, jng_color_type, transparent; size_t jng_alpha_quality, jng_quality; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOneJNGImage()"); blob=(unsigned char *) NULL; jpeg_image=(Image *) NULL; jpeg_image_info=(ImageInfo *) NULL; length=0; status=MagickTrue; transparent=image_info->type==GrayscaleAlphaType || image_info->type==TrueColorAlphaType || image->alpha_trait != UndefinedPixelTrait; jng_alpha_sample_depth = 0; jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000; jng_alpha_compression_method=(image->compression==JPEGCompression || image_info->compression==JPEGCompression) ? 8 : 0; jng_alpha_quality=image_info->quality == 0UL ? 75UL : image_info->quality; if (jng_alpha_quality >= 1000) jng_alpha_quality /= 1000; length=0; if (transparent != 0) { jng_color_type=14; /* Create JPEG blob, image, and image_info */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info for alpha."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) { jpeg_image_info=DestroyImageInfo(jpeg_image_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=SeparateImage(image,AlphaChannel,exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); jpeg_image->alpha_trait=UndefinedPixelTrait; jpeg_image->quality=jng_alpha_quality; jpeg_image_info->type=GrayscaleType; (void) SetImageType(jpeg_image,GrayscaleType,exception); (void) AcquireUniqueFilename(jpeg_image->filename); (void) FormatLocaleString(jpeg_image_info->filename,MagickPathExtent, "%s",jpeg_image->filename); } else { jng_alpha_compression_method=0; jng_color_type=10; jng_alpha_sample_depth=0; } /* To do: check bit depth of PNG alpha channel */ /* Check if image is grayscale. */ if (image_info->type != TrueColorAlphaType && image_info->type != TrueColorType && SetImageGray(image,exception)) jng_color_type-=2; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Quality = %d",(int) jng_quality); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Color Type = %d",jng_color_type); if (transparent != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Compression = %d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Depth = %d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Quality = %d",(int) jng_alpha_quality); } } if (transparent != 0) { if (jng_alpha_compression_method==0) { const char *value; /* Encode alpha as a grayscale PNG blob */ status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating PNG blob."); (void) CopyMagickString(jpeg_image_info->magick,"PNG", MagickPathExtent); (void) CopyMagickString(jpeg_image->magick,"PNG",MagickPathExtent); jpeg_image_info->interlace=NoInterlace; /* Exclude all ancillary chunks */ (void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all"); blob=(unsigned char *) ImageToBlob(jpeg_image_info,jpeg_image, &length,exception); /* Retrieve sample depth used */ value=GetImageProperty(jpeg_image,"png:bit-depth-written",exception); if (value != (char *) NULL) jng_alpha_sample_depth= (unsigned int) value[0]; } else { /* Encode alpha as a grayscale JPEG blob */ status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image_info->magick,"JPEG", MagickPathExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); jpeg_image_info->interlace=NoInterlace; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=(unsigned char *) ImageToBlob(jpeg_image_info, jpeg_image,&length, exception); jng_alpha_sample_depth=8; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); } /* Destroy JPEG image and image_info */ jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); jpeg_image_info=DestroyImageInfo(jpeg_image_info); } /* Write JHDR chunk */ (void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */ PNGType(chunk,mng_JHDR); LogPNGChunk(logging,mng_JHDR,16L); PNGLong(chunk+4,(png_uint_32) image->columns); PNGLong(chunk+8,(png_uint_32) image->rows); chunk[12]=jng_color_type; chunk[13]=8; /* sample depth */ chunk[14]=8; /*jng_image_compression_method */ chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8); chunk[16]=jng_alpha_sample_depth; chunk[17]=jng_alpha_compression_method; chunk[18]=0; /*jng_alpha_filter_method */ chunk[19]=0; /*jng_alpha_interlace_method */ (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width:%15lu",(unsigned long) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG height:%14lu",(unsigned long) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG color type:%10d",jng_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG sample depth:%8d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG compression:%9d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG interlace:%11d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha depth:%9d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha compression:%3d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha filter:%8d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha interlace:%5d",0); } /* Write leading ancillary chunks */ if (transparent != 0) { /* Write JNG bKGD chunk */ unsigned char blue, green, red; ssize_t num_bytes; if (jng_color_type == 8 || jng_color_type == 12) num_bytes=6L; else num_bytes=10L; (void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L)); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L)); red=ScaleQuantumToChar(image->background_color.red); green=ScaleQuantumToChar(image->background_color.green); blue=ScaleQuantumToChar(image->background_color.blue); *(chunk+4)=0; *(chunk+5)=red; *(chunk+6)=0; *(chunk+7)=green; *(chunk+8)=0; *(chunk+9)=blue; (void) WriteBlob(image,(size_t) num_bytes,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes)); } if ((image->colorspace == sRGBColorspace || image->rendering_intent)) { /* Write JNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { if (image->gamma != 0.0) { /* Write JNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); } if ((mng_info->equal_chrms == MagickFalse) && (image->chromaticity.red_primary.x != 0.0)) { PrimaryInfo primary; /* Write JNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); } } if (image->resolution.x && image->resolution.y && !mng_info->equal_physs) { /* Write JNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->resolution.x+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.x || image->page.y)) { /* Write JNG oFFs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_oFFs); LogPNGChunk(logging,mng_oFFs,9L); PNGsLong(chunk+4,(ssize_t) (image->page.x)); PNGsLong(chunk+8,(ssize_t) (image->page.y)); chunk[12]=0; (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (transparent != 0) { if (jng_alpha_compression_method==0) { register ssize_t i; size_t len; /* Write IDAT chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write IDAT chunks from blob, length=%.20g.",(double) length); /* Copy IDAT chunks */ len=0; p=blob+8; for (i=8; i<(ssize_t) length; i+=len+12) { len=(((unsigned int) *(p ) & 0xff) << 24) + (((unsigned int) *(p + 1) & 0xff) << 16) + (((unsigned int) *(p + 2) & 0xff) << 8) + (((unsigned int) *(p + 3) & 0xff) ) ; p+=4; if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */ { /* Found an IDAT chunk. */ (void) WriteBlobMSBULong(image,len); LogPNGChunk(logging,mng_IDAT,len); (void) WriteBlob(image,len+4,p); (void) WriteBlobMSBULong(image, crc32(0,p,(uInt) len+4)); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping %c%c%c%c chunk, length=%.20g.", *(p),*(p+1),*(p+2),*(p+3),(double) len); } p+=(8+len); } } else if (length != 0) { /* Write JDAA chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAA chunk, length=%.20g.",(double) length); (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAA); LogPNGChunk(logging,mng_JDAA,length); /* Write JDAT chunk(s) data */ (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob, (uInt) length)); } blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Encode image as a JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,exception); if (jpeg_image == (Image *) NULL) { jpeg_image_info=DestroyImageInfo(jpeg_image_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); (void) AcquireUniqueFilename(jpeg_image->filename); (void) FormatLocaleString(jpeg_image_info->filename,MagickPathExtent,"%s", jpeg_image->filename); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns, (double) jpeg_image->rows); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (jng_color_type == 8 || jng_color_type == 12) jpeg_image_info->type=GrayscaleType; jpeg_image_info->quality=jng_quality; jpeg_image->quality=jng_quality; (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MagickPathExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=(unsigned char *) ImageToBlob(jpeg_image_info,jpeg_image,&length, exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAT chunk, length=%.20g.",(double) length); } /* Write JDAT chunk(s) */ (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAT); LogPNGChunk(logging,mng_JDAT,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length)); jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); jpeg_image_info=DestroyImageInfo(jpeg_image_info); blob=(unsigned char *) RelinquishMagickMemory(blob); /* Write IEND chunk */ (void) WriteBlobMSBULong(image,0L); PNGType(chunk,mng_IEND); LogPNGChunk(logging,mng_IEND,0); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOneJNGImage()"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJNGImage() writes a JPEG Network Graphics (JNG) image file. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteJNGImage method is: % % MagickBooleanType WriteJNGImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WriteJNGImage(const ImageInfo *image_info, Image *image, ExceptionInfo *exception) { MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) memset(mng_info,0,sizeof(MngInfo)); mng_info->image=image; (void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n"); status=WriteOneJNGImage(mng_info,image_info,image,exception); mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); (void) CatchImageException(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteJNGImage()"); return(status); } #endif static MagickBooleanType WriteMNGImage(const ImageInfo *image_info, Image *image, ExceptionInfo *exception) { Image *next_image; MagickBooleanType status; volatile MagickBooleanType logging; MngInfo *mng_info; int image_count, need_iterations, need_matte; volatile int #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) need_local_plte, #endif all_images_are_gray, need_defi, use_global_plte; register ssize_t i; unsigned char chunk[800]; volatile unsigned int write_jng, write_mng; volatile size_t scene; size_t final_delay=0, imageListLength, initial_delay; #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) memset(mng_info,0,sizeof(MngInfo)); mng_info->image=image; write_mng=LocaleCompare(image_info->magick,"MNG") == 0; /* * See if user has requested a specific PNG subformat to be used * for all of the PNGs in the MNG being written, e.g., * * convert *.png png8:animation.mng * * To do: check -define png:bit_depth and png:color_type as well, * or perhaps use mng:bit_depth and mng:color_type instead for * global settings. */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; write_jng=MagickFalse; if (image_info->compression == JPEGCompression) write_jng=MagickTrue; mng_info->adjoin=image_info->adjoin && (GetNextImageInList(image) != (Image *) NULL) && write_mng; if (logging != MagickFalse) { /* Log some info about the input */ Image *p; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Checking input image(s)\n" " Image_info depth: %.20g, Type: %d", (double) image_info->depth, image_info->type); scene=0; for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scene: %.20g\n, Image depth: %.20g", (double) scene++, (double) p->depth); if (p->alpha_trait != UndefinedPixelTrait) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: False"); if (p->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: PseudoClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: DirectClass"); if (p->colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) p->colors); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: unspecified"); if (mng_info->adjoin == MagickFalse) break; } } use_global_plte=MagickFalse; all_images_are_gray=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_defi=MagickFalse; need_matte=MagickFalse; mng_info->framing_mode=1; mng_info->old_framing_mode=1; if (write_mng) if (image_info->page != (char *) NULL) { /* Determine image bounding box. */ SetGeometry(image,&mng_info->page); (void) ParseMetaGeometry(image_info->page,&mng_info->page.x, &mng_info->page.y,&mng_info->page.width,&mng_info->page.height); } if (write_mng) { unsigned int need_geom; unsigned short red, green, blue; const char * option; mng_info->page=image->page; need_geom=MagickTrue; if (mng_info->page.width || mng_info->page.height) need_geom=MagickFalse; /* Check all the scenes. */ initial_delay=image->delay; need_iterations=MagickFalse; mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0; mng_info->equal_physs=MagickTrue, mng_info->equal_gammas=MagickTrue; mng_info->equal_srgbs=MagickTrue; mng_info->equal_backgrounds=MagickTrue; image_count=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) all_images_are_gray=MagickTrue; mng_info->equal_palettes=MagickFalse; need_local_plte=MagickFalse; #endif for (next_image=image; next_image != (Image *) NULL; ) { if (need_geom) { if ((next_image->columns+next_image->page.x) > mng_info->page.width) mng_info->page.width=next_image->columns+next_image->page.x; if ((next_image->rows+next_image->page.y) > mng_info->page.height) mng_info->page.height=next_image->rows+next_image->page.y; } if (next_image->page.x || next_image->page.y) need_defi=MagickTrue; if (next_image->alpha_trait != UndefinedPixelTrait) need_matte=MagickTrue; if ((int) next_image->dispose >= BackgroundDispose) if ((next_image->alpha_trait != UndefinedPixelTrait) || next_image->page.x || next_image->page.y || ((next_image->columns < mng_info->page.width) && (next_image->rows < mng_info->page.height))) mng_info->need_fram=MagickTrue; if (next_image->iterations) need_iterations=MagickTrue; final_delay=next_image->delay; if (final_delay != initial_delay || final_delay > 1UL* next_image->ticks_per_second) mng_info->need_fram=1; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* check for global palette possibility. */ if (image->alpha_trait != UndefinedPixelTrait) need_local_plte=MagickTrue; if (need_local_plte == 0) { if (SetImageGray(image,exception) == MagickFalse) all_images_are_gray=MagickFalse; mng_info->equal_palettes=PalettesAreEqual(image,next_image); if (use_global_plte == 0) use_global_plte=mng_info->equal_palettes; need_local_plte=!mng_info->equal_palettes; } #endif if (GetNextImageInList(next_image) != (Image *) NULL) { if (next_image->background_color.red != next_image->next->background_color.red || next_image->background_color.green != next_image->next->background_color.green || next_image->background_color.blue != next_image->next->background_color.blue) mng_info->equal_backgrounds=MagickFalse; if (next_image->gamma != next_image->next->gamma) mng_info->equal_gammas=MagickFalse; if (next_image->rendering_intent != next_image->next->rendering_intent) mng_info->equal_srgbs=MagickFalse; if ((next_image->units != next_image->next->units) || (next_image->resolution.x != next_image->next->resolution.x) || (next_image->resolution.y != next_image->next->resolution.y)) mng_info->equal_physs=MagickFalse; if (mng_info->equal_chrms) { if (next_image->chromaticity.red_primary.x != next_image->next->chromaticity.red_primary.x || next_image->chromaticity.red_primary.y != next_image->next->chromaticity.red_primary.y || next_image->chromaticity.green_primary.x != next_image->next->chromaticity.green_primary.x || next_image->chromaticity.green_primary.y != next_image->next->chromaticity.green_primary.y || next_image->chromaticity.blue_primary.x != next_image->next->chromaticity.blue_primary.x || next_image->chromaticity.blue_primary.y != next_image->next->chromaticity.blue_primary.y || next_image->chromaticity.white_point.x != next_image->next->chromaticity.white_point.x || next_image->chromaticity.white_point.y != next_image->next->chromaticity.white_point.y) mng_info->equal_chrms=MagickFalse; } } image_count++; next_image=GetNextImageInList(next_image); } if (image_count < 2) { mng_info->equal_backgrounds=MagickFalse; mng_info->equal_chrms=MagickFalse; mng_info->equal_gammas=MagickFalse; mng_info->equal_srgbs=MagickFalse; mng_info->equal_physs=MagickFalse; use_global_plte=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_iterations=MagickFalse; } if (mng_info->need_fram == MagickFalse) { /* Only certain framing rates 100/n are exactly representable without the FRAM chunk but we'll allow some slop in VLC files */ if (final_delay == 0) { if (need_iterations != MagickFalse) { /* It's probably a GIF with loop; don't run it *too* fast. */ if (mng_info->adjoin) { final_delay=10; (void) ThrowMagickException(exception,GetMagickModule(), CoderWarning, "input has zero delay between all frames; assuming", " 10 cs `%s'",""); } } else mng_info->ticks_per_second=0; } if (final_delay != 0) mng_info->ticks_per_second=(png_uint_32) (image->ticks_per_second/final_delay); if (final_delay > 50) mng_info->ticks_per_second=2; if (final_delay > 75) mng_info->ticks_per_second=1; if (final_delay > 125) mng_info->need_fram=MagickTrue; if (need_defi && final_delay > 2 && (final_delay != 4) && (final_delay != 5) && (final_delay != 10) && (final_delay != 20) && (final_delay != 25) && (final_delay != 50) && (final_delay != (size_t) image->ticks_per_second)) mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */ } if (mng_info->need_fram != MagickFalse) mng_info->ticks_per_second=image->ticks_per_second; /* If pseudocolor, we should also check to see if all the palettes are identical and write a global PLTE if they are. ../glennrp Feb 99. */ /* Write the MNG version 1.0 signature and MHDR chunk. */ (void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n"); (void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */ PNGType(chunk,mng_MHDR); LogPNGChunk(logging,mng_MHDR,28L); PNGLong(chunk+4,(png_uint_32) mng_info->page.width); PNGLong(chunk+8,(png_uint_32) mng_info->page.height); PNGLong(chunk+12,mng_info->ticks_per_second); PNGLong(chunk+16,0L); /* layer count=unknown */ PNGLong(chunk+20,0L); /* frame count=unknown */ PNGLong(chunk+24,0L); /* play time=unknown */ if (write_jng) { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,27L); /* simplicity=LC+JNG */ else PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */ else PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */ } } else { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,11L); /* simplicity=LC */ else PNGLong(chunk+28,9L); /* simplicity=VLC */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */ else PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */ } } (void) WriteBlob(image,32,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,32)); option=GetImageOption(image_info,"mng:need-cacheoff"); if (option != (const char *) NULL) { size_t length; /* Write "nEED CACHEOFF" to turn playback caching off for streaming MNG. */ PNGType(chunk,mng_nEED); length=CopyMagickString((char *) chunk+4,"CACHEOFF",20); (void) WriteBlobMSBULong(image,(size_t) length); LogPNGChunk(logging,mng_nEED,(size_t) length); length+=4; (void) WriteBlob(image,length,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length)); } if ((GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) != (Image *) NULL) && (image->iterations != 1)) { /* Write MNG TERM chunk */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_TERM); LogPNGChunk(logging,mng_TERM,10L); chunk[4]=3; /* repeat animation */ chunk[5]=0; /* show last frame when done */ PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) PNGLong(chunk+10,PNG_UINT_31_MAX); else PNGLong(chunk+10,(png_uint_32) image->iterations); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM delay: %.20g",(double) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM iterations: %.20g",(double) PNG_UINT_31_MAX); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image iterations: %.20g",(double) image->iterations); } (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); } /* To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if ((image->colorspace == sRGBColorspace || image->rendering_intent) && mng_info->equal_srgbs) { /* Write MNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); mng_info->have_write_global_srgb=MagickTrue; } else { if (image->gamma && mng_info->equal_gammas) { /* Write MNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); mng_info->have_write_global_gama=MagickTrue; } if (mng_info->equal_chrms) { PrimaryInfo primary; /* Write MNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); mng_info->have_write_global_chrm=MagickTrue; } } if (image->resolution.x && image->resolution.y && mng_info->equal_physs) { /* Write MNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->resolution.x+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } /* Write MNG BACK chunk and global bKGD chunk, if the image is transparent or does not cover the entire frame. */ if (write_mng && ((image->alpha_trait != UndefinedPixelTrait) || image->page.x > 0 || image->page.y > 0 || (image->page.width && (image->page.width+image->page.x < mng_info->page.width)) || (image->page.height && (image->page.height+image->page.y < mng_info->page.height)))) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_BACK); LogPNGChunk(logging,mng_BACK,6L); red=ScaleQuantumToShort(image->background_color.red); green=ScaleQuantumToShort(image->background_color.green); blue=ScaleQuantumToShort(image->background_color.blue); PNGShort(chunk+4,red); PNGShort(chunk+6,green); PNGShort(chunk+8,blue); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); if (mng_info->equal_backgrounds) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,6L); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); } } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if ((need_local_plte == MagickFalse) && (image->storage_class == PseudoClass) && (all_images_are_gray == MagickFalse)) { size_t data_length; /* Write MNG PLTE chunk */ data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=(unsigned char) (ScaleQuantumToChar( image->colormap[i].red) & 0xff); chunk[5+i*3]=(unsigned char) (ScaleQuantumToChar( image->colormap[i].green) & 0xff); chunk[6+i*3]=(unsigned char) (ScaleQuantumToChar( image->colormap[i].blue) & 0xff); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } #endif } scene=0; mng_info->delay=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) mng_info->equal_palettes=MagickFalse; #endif imageListLength=GetImageListLength(image); do { if (mng_info->adjoin) { #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* If we aren't using a global palette for the entire MNG, check to see if we can use one for two or more consecutive images. */ if (need_local_plte && use_global_plte && !all_images_are_gray) { if (mng_info->IsPalette) { /* When equal_palettes is true, this image has the same palette as the previous PseudoClass image */ mng_info->have_write_global_plte=mng_info->equal_palettes; mng_info->equal_palettes=PalettesAreEqual(image,image->next); if (mng_info->equal_palettes && !mng_info->have_write_global_plte) { /* Write MNG PLTE chunk */ size_t data_length; data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red); chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green); chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk, (uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } } else mng_info->have_write_global_plte=MagickFalse; } #endif if (need_defi) { ssize_t previous_x, previous_y; if (scene != 0) { previous_x=mng_info->page.x; previous_y=mng_info->page.y; } else { previous_x=0; previous_y=0; } mng_info->page=image->page; if ((mng_info->page.x != previous_x) || (mng_info->page.y != previous_y)) { (void) WriteBlobMSBULong(image,12L); /* data length=12 */ PNGType(chunk,mng_DEFI); LogPNGChunk(logging,mng_DEFI,12L); chunk[4]=0; /* object 0 MSB */ chunk[5]=0; /* object 0 LSB */ chunk[6]=0; /* visible */ chunk[7]=0; /* abstract */ PNGLong(chunk+8,(png_uint_32) mng_info->page.x); PNGLong(chunk+12,(png_uint_32) mng_info->page.y); (void) WriteBlob(image,16,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,16)); } } } mng_info->write_mng=write_mng; if ((int) image->dispose >= 3) mng_info->framing_mode=3; if (mng_info->need_fram && mng_info->adjoin && ((image->delay != mng_info->delay) || (mng_info->framing_mode != mng_info->old_framing_mode))) { if (image->delay == mng_info->delay) { /* Write a MNG FRAM chunk with the new framing mode. */ (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,1L); chunk[4]=(unsigned char) mng_info->framing_mode; (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { /* Write a MNG FRAM chunk with the delay. */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,10L); chunk[4]=(unsigned char) mng_info->framing_mode; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=2; /* flag for changing default delay */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=0; /* flag for changing frame clipping */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) ((mng_info->ticks_per_second* image->delay)/MagickMax(image->ticks_per_second,1))); (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); mng_info->delay=(png_uint_32) image->delay; } mng_info->old_framing_mode=mng_info->framing_mode; } #if defined(JNG_SUPPORTED) if (image_info->compression == JPEGCompression) { ImageInfo *write_info; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing JNG object."); /* To do: specify the desired alpha compression method. */ write_info=CloneImageInfo(image_info); write_info->compression=UndefinedCompression; status=WriteOneJNGImage(mng_info,write_info,image,exception); write_info=DestroyImageInfo(write_info); } else #endif { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG object."); mng_info->need_blob = MagickFalse; mng_info->ping_preserve_colormap = MagickFalse; /* We don't want any ancillary chunks written */ mng_info->ping_exclude_bKGD=MagickTrue; mng_info->ping_exclude_caNv=MagickTrue; mng_info->ping_exclude_cHRM=MagickTrue; mng_info->ping_exclude_date=MagickTrue; mng_info->ping_exclude_EXIF=MagickTrue; mng_info->ping_exclude_gAMA=MagickTrue; mng_info->ping_exclude_iCCP=MagickTrue; /* mng_info->ping_exclude_iTXt=MagickTrue; */ mng_info->ping_exclude_oFFs=MagickTrue; mng_info->ping_exclude_pHYs=MagickTrue; mng_info->ping_exclude_sRGB=MagickTrue; mng_info->ping_exclude_tEXt=MagickTrue; mng_info->ping_exclude_tRNS=MagickTrue; mng_info->ping_exclude_zCCP=MagickTrue; mng_info->ping_exclude_zTXt=MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image,exception); } if (status == MagickFalse) { mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); return(MagickFalse); } (void) CatchImageException(image); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (mng_info->adjoin); if (write_mng) { while (GetPreviousImageInList(image) != (Image *) NULL) image=GetPreviousImageInList(image); /* Write the MEND chunk. */ (void) WriteBlobMSBULong(image,0x00000000L); PNGType(chunk,mng_MEND); LogPNGChunk(logging,mng_MEND,0L); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); } /* Relinquish resources. */ (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()"); return(MagickTrue); } #else /* PNG_LIBPNG_VER > 10011 */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info, Image *image) { (void) image; printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); ThrowBinaryException(CoderError,"PNG library is too old", image_info->filename); } static MagickBooleanType WriteMNGImage(const ImageInfo *image_info, Image *image) { return(WritePNGImage(image_info,image)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif
./CrossVul/dataset_final_sorted/CWE-772/c/good_361_0
crossvul-cpp_data_bad_1168_2
404: Not Found
./CrossVul/dataset_final_sorted/CWE-772/c/bad_1168_2
crossvul-cpp_data_good_2617_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M AAA PPPP % % MM MM A A P P % % M M M AAAAA PPPP % % M M A A P % % M M A A P % % % % % % Read/Write Image Colormaps As An Image File. % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/histogram.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/module.h" /* Forward declarations. */ static MagickBooleanType WriteMAPImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d M A P I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMAPImage() reads an image of raw RGB colormap and colormap index % bytes and returns it. It allocates the memory necessary for the new Image % structure and returns a pointer to the new image. % % The format of the ReadMAPImage method is: % % Image *ReadMAPImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMAPImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; IndexPacket index; MagickBooleanType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t depth, packet_size, quantum; ssize_t count, y; unsigned char *colormap, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image structure. */ image->storage_class=PseudoClass; status=AcquireImageColormap(image,(size_t) (image->offset != 0 ? image->offset : 256)); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); depth=GetImageQuantumDepth(image,MagickTrue); packet_size=(size_t) (depth/8); pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*pixels)); packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size* sizeof(*colormap)); if ((pixels == (unsigned char *) NULL) || (colormap == (unsigned char *) NULL)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read image colormap. */ count=ReadBlob(image,packet_size*image->colors,colormap); if (count != (ssize_t) (packet_size*image->colors)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); p=colormap; if (image->depth <= 8) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].blue=ScaleCharToQuantum(*p++); } else for (i=0; i < (ssize_t) image->colors; i++) { quantum=(*p++ << 8); quantum|=(*p++); image->colormap[i].red=(Quantum) quantum; quantum=(*p++ << 8); quantum|=(*p++); image->colormap[i].green=(Quantum) quantum; quantum=(*p++ << 8); quantum|=(*p++); image->colormap[i].blue=(Quantum) quantum; } colormap=(unsigned char *) RelinquishMagickMemory(colormap); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Read image pixels. */ packet_size=(size_t) (depth/8); for (y=0; y < (ssize_t) image->rows; y++) { p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); count=ReadBlob(image,(size_t) packet_size*image->columns,pixels); if (count != (ssize_t) (packet_size*image->columns)) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p); p++; if (image->colors > 256) { index=ConstrainColormapIndex(image,((size_t) index << 8)+(*p)); p++; } SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (y < (ssize_t) image->rows) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M A P I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterMAPImage() adds attributes for the MAP image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterMAPImage method is: % % size_t RegisterMAPImage(void) % */ ModuleExport size_t RegisterMAPImage(void) { MagickInfo *entry; entry=SetMagickInfo("MAP"); entry->decoder=(DecodeImageHandler *) ReadMAPImage; entry->encoder=(EncodeImageHandler *) WriteMAPImage; entry->adjoin=MagickFalse; entry->format_type=ExplicitFormatType; entry->raw=MagickTrue; entry->endian_support=MagickTrue; entry->description=ConstantString("Colormap intensities and indices"); entry->module=ConstantString("MAP"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M A P I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterMAPImage() removes format registrations made by the % MAP module from the list of supported formats. % % The format of the UnregisterMAPImage method is: % % UnregisterMAPImage(void) % */ ModuleExport void UnregisterMAPImage(void) { (void) UnregisterMagickInfo("MAP"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M A P I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMAPImage() writes an image to a file as red, green, and blue % colormap bytes followed by the colormap indexes. % % The format of the WriteMAPImage method is: % % MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % */ static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image) { MagickBooleanType status; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; size_t depth, packet_size; ssize_t y; unsigned char *colormap, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); /* Allocate colormap. */ if (IsPaletteImage(image,&image->exception) == MagickFalse) (void) SetImageType(image,PaletteType); depth=GetImageQuantumDepth(image,MagickTrue); packet_size=(size_t) (depth/8); pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*pixels)); packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size* sizeof(*colormap)); if ((pixels == (unsigned char *) NULL) || (colormap == (unsigned char *) NULL)) { if (colormap != (unsigned char *) NULL) colormap=(unsigned char *) RelinquishMagickMemory(colormap); if (pixels != (unsigned char *) NULL) pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } /* Write colormap to file. */ q=colormap; if (image->colors <= 256) for (i=0; i < (ssize_t) image->colors; i++) { *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red); *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green); *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue); } else for (i=0; i < (ssize_t) image->colors; i++) { *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) & 0xff); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & 0xff); } (void) WriteBlob(image,packet_size*image->colors,colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); /* Write image pixels to file. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels; for (x=0; x < (ssize_t) image->columns; x++) { if (image->colors > 256) *q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8); *q++=(unsigned char) GetPixelIndex(indexes+x); } (void) WriteBlob(image,(size_t) (q-pixels),pixels); } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-772/c/good_2617_0
crossvul-cpp_data_bad_2621_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % M M AAA TTTTT L AAA BBBB % % MM MM A A T L A A B B % % M M M AAAAA T L AAAAA BBBB % % M M A A T L A A B B % % M M A A T LLLLL A A BBBB % % % % % % Read MATLAB Image Format % % % % Software Design % % Jaroslav Fojtik % % 2001-2008 % % % % % % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick is furnished to do so, subject to the following conditions: % % % % The above copyright notice and this permission notice shall be included in % % all copies or substantial portions of ImageMagick. % % % % The software is provided "as is", without warranty of any kind, express or % % implied, including but not limited to the warranties of merchantability, % % fitness for a particular purpose and noninfringement. In no event shall % % ImageMagick Studio be liable for any claim, damages or other liability, % % whether in an action of contract, tort or otherwise, arising from, out of % % or in connection with ImageMagick or the use or other dealings in % % ImageMagick. % % % % Except as contained in this notice, the name of the ImageMagick Studio % % shall not be used in advertising or otherwise to promote the sale, use or % % other dealings in ImageMagick without prior written authorization from the % % ImageMagick Studio. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace-private.h" #include "magick/distort.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/transform.h" #include "magick/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Forward declaration. */ static MagickBooleanType WriteMATImage(const ImageInfo *,Image *); /* Auto coloring method, sorry this creates some artefact inside data MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black MinReal+j*0 = white MaxReal+j*0 = black MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black */ typedef struct { char identific[124]; unsigned short Version; char EndianIndicator[2]; unsigned long DataType; unsigned int ObjectSize; unsigned long unknown1; unsigned long unknown2; unsigned short unknown5; unsigned char StructureFlag; unsigned char StructureClass; unsigned long unknown3; unsigned long unknown4; unsigned long DimFlag; unsigned long SizeX; unsigned long SizeY; unsigned short Flag1; unsigned short NameFlag; } MATHeader; static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; static const char *OsDesc= #if defined(MAGICKCORE_WINDOWS_SUPPORT) "PCWIN"; #else #ifdef __APPLE__ "MAC"; #else "LNX86"; #endif #endif typedef enum { miINT8 = 1, /* 8 bit signed */ miUINT8, /* 8 bit unsigned */ miINT16, /* 16 bit signed */ miUINT16, /* 16 bit unsigned */ miINT32, /* 32 bit signed */ miUINT32, /* 32 bit unsigned */ miSINGLE, /* IEEE 754 single precision float */ miRESERVE1, miDOUBLE, /* IEEE 754 double precision float */ miRESERVE2, miRESERVE3, miINT64, /* 64 bit signed */ miUINT64, /* 64 bit unsigned */ miMATRIX, /* MATLAB array */ miCOMPRESSED, /* Compressed Data */ miUTF8, /* Unicode UTF-8 Encoded Character Data */ miUTF16, /* Unicode UTF-16 Encoded Character Data */ miUTF32 /* Unicode UTF-32 Encoded Character Data */ } mat5_data_type; typedef enum { mxCELL_CLASS=1, /* cell array */ mxSTRUCT_CLASS, /* structure */ mxOBJECT_CLASS, /* object */ mxCHAR_CLASS, /* character array */ mxSPARSE_CLASS, /* sparse array */ mxDOUBLE_CLASS, /* double precision array */ mxSINGLE_CLASS, /* single precision floating point */ mxINT8_CLASS, /* 8 bit signed integer */ mxUINT8_CLASS, /* 8 bit unsigned integer */ mxINT16_CLASS, /* 16 bit signed integer */ mxUINT16_CLASS, /* 16 bit unsigned integer */ mxINT32_CLASS, /* 32 bit signed integer */ mxUINT32_CLASS, /* 32 bit unsigned integer */ mxINT64_CLASS, /* 64 bit signed integer */ mxUINT64_CLASS, /* 64 bit unsigned integer */ mxFUNCTION_CLASS /* Function handle */ } arrayclasstype; #define FLAG_COMPLEX 0x8 #define FLAG_GLOBAL 0x4 #define FLAG_LOGICAL 0x2 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum}; static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal, double MaxVal) { ExceptionInfo *exception; double f; int x; register PixelPacket *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; exception=(&image->exception); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q)); if (f + GetPixelRed(q) > QuantumRange) SetPixelRed(q,QuantumRange); else SetPixelRed(q,GetPixelRed(q)+(int) f); if ((int) f / 2.0 > GetPixelGreen(q)) { SetPixelGreen(q,0); SetPixelBlue(q,0); } else { SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelBlue(q)); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q)); if (f + GetPixelBlue(q) > QuantumRange) SetPixelBlue(q,QuantumRange); else SetPixelBlue(q,GetPixelBlue(q)+(int) f); if ((int) f / 2.0 > q->green) { SetPixelRed(q,0); SetPixelGreen(q,0); } else { SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelRed(q)); } } p++; q++; } if (!SyncAuthenticPixels(image,exception)) return; return; } static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal, double MaxVal) { ExceptionInfo *exception; double f; int x; register PixelPacket *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; exception=(&image->exception); q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception); if (q == (PixelPacket *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q)); if (f + GetPixelRed(q) > QuantumRange) SetPixelRed(q,QuantumRange); else SetPixelRed(q,GetPixelRed(q)+(int) f); if ((int) f / 2.0 > GetPixelGreen(q)) { SetPixelGreen(q,0); SetPixelBlue(q,0); } else { SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelBlue(q)); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q)); if (f + GetPixelBlue(q) > QuantumRange) SetPixelBlue(q,QuantumRange); else SetPixelBlue(q,GetPixelBlue(q)+(int) f); if ((int) f / 2.0 > q->green) { SetPixelGreen(q,0); SetPixelRed(q,0); } else { SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelRed(q)); } } p++; q++; } if (!SyncAuthenticPixels(image,exception)) return; return; } /************** READERS ******************/ /* This function reads one block of floats*/ static void ReadBlobFloatsLSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobFloatsMSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* This function reads one block of doubles*/ static void ReadBlobDoublesLSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobDoublesMSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* Calculate minimum and maximum from a given block of data */ static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max) { MagickOffsetType filepos; int i, x; void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); double *dblrow; float *fltrow; if (endian_indicator == LSBEndian) { ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; } else /* MI */ { ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; } filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */ for (i = 0; i < SizeY; i++) { if (CellType==miDOUBLE) { ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff); dblrow = (double *)BImgBuff; if (i == 0) { *Min = *Max = *dblrow; } for (x = 0; x < SizeX; x++) { if (*Min > *dblrow) *Min = *dblrow; if (*Max < *dblrow) *Max = *dblrow; dblrow++; } } if (CellType==miSINGLE) { ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff); fltrow = (float *)BImgBuff; if (i == 0) { *Min = *Max = *fltrow; } for (x = 0; x < (ssize_t) SizeX; x++) { if (*Min > *fltrow) *Min = *fltrow; if (*Max < *fltrow) *Max = *fltrow; fltrow++; } } } (void) SeekBlob(image, filepos, SEEK_SET); } static void FixSignedValues(PixelPacket *q, int y) { while(y-->0) { /* Please note that negative values will overflow Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255> <-1;-128> + 127+1 = <0; 127> */ SetPixelRed(q,GetPixelRed(q)+QuantumRange/2+1); SetPixelGreen(q,GetPixelGreen(q)+QuantumRange/2+1); SetPixelBlue(q,GetPixelBlue(q)+QuantumRange/2+1); q++; } } /** Fix whole row of logical/binary data. It means pack it. */ static void FixLogical(unsigned char *Buff,int ldblk) { unsigned char mask=128; unsigned char *BuffL = Buff; unsigned char val = 0; while(ldblk-->0) { if(*Buff++ != 0) val |= mask; mask >>= 1; if(mask==0) { *BuffL++ = val; val = 0; mask = 128; } } *BuffL = val; } #if defined(MAGICKCORE_ZLIB_DELEGATE) static voidpf AcquireZIPMemory(voidpf context,unsigned int items, unsigned int size) { (void) context; return((voidpf) AcquireQuantumMemory(items,size)); } static void RelinquishZIPMemory(voidpf context,voidpf memory) { (void) context; memory=RelinquishMagickMemory(memory); } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) /** This procedure decompreses an image block for a new MATLAB format. */ static Image *decompress_block(Image *orig, unsigned int *Size, ImageInfo *clone_info, ExceptionInfo *exception) { Image *image2; void *cache_block, *decompress_block; z_stream zip_info; FILE *mat_file; size_t magick_size; size_t extent; int file; int status; int zip_status; ssize_t TotalSize = 0; if(clone_info==NULL) return NULL; if(clone_info->file) /* Close file opened from previous transaction. */ { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } cache_block = AcquireQuantumMemory((size_t)(*Size< 16384) ? *Size: 16384,sizeof(unsigned char *)); if(cache_block==NULL) return NULL; decompress_block = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *)); if(decompress_block==NULL) { RelinquishMagickMemory(cache_block); return NULL; } mat_file=0; file = AcquireUniqueFileResource(clone_info->filename); if (file != -1) mat_file = fdopen(file,"w"); if(!mat_file) { RelinquishMagickMemory(cache_block); RelinquishMagickMemory(decompress_block); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Cannot create file stream for decompressed image"); return NULL; } zip_info.zalloc=AcquireZIPMemory; zip_info.zfree=RelinquishZIPMemory; zip_info.opaque = (voidpf) NULL; zip_status = inflateInit(&zip_info); if (zip_status != Z_OK) { RelinquishMagickMemory(cache_block); RelinquishMagickMemory(decompress_block); (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "UnableToUncompressImage","`%s'",clone_info->filename); (void) fclose(mat_file); RelinquishUniqueFileResource(clone_info->filename); return NULL; } /* zip_info.next_out = 8*4;*/ zip_info.avail_in = 0; zip_info.total_out = 0; while(*Size>0 && !EOFBlob(orig)) { magick_size = ReadBlob(orig, (*Size < 16384) ? *Size : 16384, (unsigned char *) cache_block); zip_info.next_in = (Bytef *) cache_block; zip_info.avail_in = (uInt) magick_size; while(zip_info.avail_in>0) { zip_info.avail_out = 4096; zip_info.next_out = (Bytef *) decompress_block; zip_status = inflate(&zip_info,Z_NO_FLUSH); if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END)) break; extent=fwrite(decompress_block, 4096-zip_info.avail_out, 1, mat_file); (void) extent; TotalSize += 4096-zip_info.avail_out; if(zip_status == Z_STREAM_END) goto DblBreak; } if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END)) break; *Size -= magick_size; } DblBreak: inflateEnd(&zip_info); (void)fclose(mat_file); RelinquishMagickMemory(cache_block); RelinquishMagickMemory(decompress_block); *Size = TotalSize; if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile; if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile; status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception); if (status == MagickFalse) { DeleteImageFromList(&image2); EraseFile: fclose(clone_info->file); clone_info->file = NULL; UnlinkFile: RelinquishUniqueFileResource(clone_info->filename); return NULL; } return image2; } #endif static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { typedef struct { unsigned char Type[4]; unsigned int nRows; unsigned int nCols; unsigned int imagf; unsigned int nameLen; } MAT4_HDR; long ldblk; EndianType endian; Image *rotate_image; MagickBooleanType status; MAT4_HDR HDR; QuantumInfo *quantum_info; QuantumFormatType format_type; register ssize_t i; ssize_t count, y; unsigned char *pixels; unsigned int depth; (void) SeekBlob(image,0,SEEK_SET); while (EOFBlob(image) != MagickFalse) { /* Object parser. */ ldblk=ReadBlobLSBLong(image); if (EOFBlob(image) != MagickFalse) break; if ((ldblk > 9999) || (ldblk < 0)) break; HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */ HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */ HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */ HDR.Type[0]=ldblk; /* M digit */ if (HDR.Type[3] != 0) break; /* Data format */ if (HDR.Type[2] != 0) break; /* Always 0 */ if (HDR.Type[0] == 0) { HDR.nRows=ReadBlobLSBLong(image); HDR.nCols=ReadBlobLSBLong(image); HDR.imagf=ReadBlobLSBLong(image); HDR.nameLen=ReadBlobLSBLong(image); endian=LSBEndian; } else { HDR.nRows=ReadBlobMSBLong(image); HDR.nCols=ReadBlobMSBLong(image); HDR.imagf=ReadBlobMSBLong(image); HDR.nameLen=ReadBlobMSBLong(image); endian=MSBEndian; } if ((HDR.imagf !=0) && (HDR.imagf !=1)) break; if (HDR.nameLen > 0xFFFF) break; for (i=0; i < (ssize_t) HDR.nameLen; i++) { int byte; /* Skip matrix name. */ byte=ReadBlobByte(image); if (byte == EOF) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } image->columns=(size_t) HDR.nRows; image->rows=(size_t) HDR.nCols; SetImageColorspace(image,GRAYColorspace); if (image_info->ping != MagickFalse) { Swap(image->columns,image->rows); return(image); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) return((Image *) NULL); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return((Image *) NULL); switch(HDR.Type[1]) { case 0: format_type=FloatingPointQuantumFormat; depth=64; break; case 1: format_type=FloatingPointQuantumFormat; depth=32; break; case 2: format_type=UnsignedQuantumFormat; depth=16; break; case 3: format_type=SignedQuantumFormat; depth=16; break; case 4: format_type=UnsignedQuantumFormat; depth=8; break; default: format_type=UnsignedQuantumFormat; depth=8; break; } image->depth=depth; if (HDR.Type[0] != 0) SetQuantumEndian(image,quantum_info,MSBEndian); status=SetQuantumFormat(image,quantum_info,format_type); status=SetQuantumDepth(image,quantum_info,depth); status=SetQuantumEndian(image,quantum_info,endian); SetQuantumScale(quantum_info,1.0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; count=ReadBlob(image,depth/8*image->columns,(unsigned char *) pixels); if (count == -1) break; q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3)) FixSignedValues(q,image->columns); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (HDR.imagf == 1) for (y=0; y < (ssize_t) image->rows; y++) { /* Read complex pixels. */ count=ReadBlob(image,depth/8*image->columns,(unsigned char *) pixels); if (count == -1) break; if (HDR.Type[1] == 0) InsertComplexDoubleRow((double *) pixels,y,image,0,0); else InsertComplexFloatRow((float *) pixels,y,image,0,0); } quantum_info=DestroyQuantumInfo(quantum_info); rotate_image=RotateImage(image,90.0,exception); if (rotate_image != (Image *) NULL) { image=DestroyImage(image); image=rotate_image; } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d M A T L A B i m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMATImage() reads an MAT X image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadMATImage method is: % % Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadMATImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; PixelPacket *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; size_t Unknown6; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ quantum_info=(QuantumInfo *) NULL; image = AcquireImage(image_info); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=(ImageInfo *) NULL; if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0) { image2=ReadMATImageV4(image_info,image,exception); if (image2 == NULL) goto MATLAB_KO; image=image2; goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; if(MATLAB_HDR.ObjectSize+filepos > GetBlobSize(image)) goto MATLAB_KO; filepos += MATLAB_HDR.ObjectSize + 4 + 4; clone_info=CloneImageInfo(image_info); image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ Unknown6 = ReadBlobXXXLong(image2); (void) Unknown6; if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); if (Frames == 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { SetImageColorspace(image,GRAYColorspace); image->type=GrayscaleType; } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double)); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (PixelPacket *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if(image2!=NULL) if(image2!=image) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) unlink(clone_info->filename); } } } } RelinquishMagickMemory(BImgBuff); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); END_OF_READING: if (clone_info) clone_info=DestroyImageInfo(clone_info); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method RegisterMATImage adds attributes for the MAT image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterMATImage method is: % % size_t RegisterMATImage(void) % */ ModuleExport size_t RegisterMATImage(void) { MagickInfo *entry; entry=SetMagickInfo("MAT"); entry->decoder=(DecodeImageHandler *) ReadMATImage; entry->encoder=(EncodeImageHandler *) WriteMATImage; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=AcquireString("MATLAB level 5 image format"); entry->module=AcquireString("MAT"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method UnregisterMATImage removes format registrations made by the % MAT module from the list of supported formats. % % The format of the UnregisterMATImage method is: % % UnregisterMATImage(void) % */ ModuleExport void UnregisterMATImage(void) { (void) UnregisterMagickInfo("MAT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M A T L A B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function WriteMATImage writes an Matlab matrix to a file. % % The format of the WriteMATImage method is: % % unsigned int WriteMATImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o status: Function WriteMATImage return True if the image is written. % False is returned is there is a memory shortage or if the image file % fails to write. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o image: A pointer to an Image structure. % */ static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image) { char MATLAB_HDR[0x80]; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType scene; struct tm local_time; time_t current_time; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(MagickFalse); image->depth=8; current_time=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&current_time,&local_time); #else (void) memcpy(&local_time,localtime(&current_time),sizeof(local_time)); #endif (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124)); FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR), "MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d", OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon], local_time.tm_mday,local_time.tm_hour,local_time.tm_min, local_time.tm_sec,local_time.tm_year+1900); MATLAB_HDR[0x7C]=0; MATLAB_HDR[0x7D]=1; MATLAB_HDR[0x7E]='I'; MATLAB_HDR[0x7F]='M'; (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR); scene=0; do { char padding; MagickBooleanType is_gray; QuantumInfo *quantum_info; size_t data_size; unsigned char *pixels; unsigned int z; (void) TransformImageColorspace(image,sRGBColorspace); is_gray=SetImageGray(image,&image->exception); z=(is_gray != MagickFalse) ? 0 : 3; /* Store MAT header. */ data_size=image->rows*image->columns; if (is_gray == MagickFalse) data_size*=3; padding=((unsigned char)(data_size-1) & 0x7) ^ 0x7; (void) WriteBlobLSBLong(image,miMATRIX); (void) WriteBlobLSBLong(image,(unsigned int) data_size+padding+ ((is_gray != MagickFalse) ? 48 : 56)); (void) WriteBlobLSBLong(image,0x6); /* 0x88 */ (void) WriteBlobLSBLong(image,0x8); /* 0x8C */ (void) WriteBlobLSBLong(image,0x6); /* 0x90 */ (void) WriteBlobLSBLong(image,0); (void) WriteBlobLSBLong(image,0x5); /* 0x98 */ (void) WriteBlobLSBLong(image,(is_gray != MagickFalse) ? 0x8 : 0xC); /* 0x9C - DimFlag */ (void) WriteBlobLSBLong(image,(unsigned int) image->rows); /* x: 0xA0 */ (void) WriteBlobLSBLong(image,(unsigned int) image->columns); /* y: 0xA4 */ if (is_gray == MagickFalse) { (void) WriteBlobLSBLong(image,3); /* z: 0xA8 */ (void) WriteBlobLSBLong(image,0); } (void) WriteBlobLSBShort(image,1); /* 0xB0 */ (void) WriteBlobLSBShort(image,1); /* 0xB2 */ (void) WriteBlobLSBLong(image,'M'); /* 0xB4 */ (void) WriteBlobLSBLong(image,0x2); /* 0xB8 */ (void) WriteBlobLSBLong(image,(unsigned int) data_size); /* 0xBC */ /* Store image data. */ exception=(&image->exception); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); do { const PixelPacket *p; ssize_t y; for (y=0; y < (ssize_t)image->columns; y++) { p=GetVirtualPixels(image,y,0,1,image->rows,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, z2qtype[z],pixels,exception); (void) WriteBlob(image,image->rows,pixels); } if (!SyncAuthenticPixels(image,exception)) break; } while (z-- >= 2); while (padding-- > 0) (void) WriteBlobByte(image,0); quantum_info=DestroyQuantumInfo(quantum_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2621_0
crossvul-cpp_data_good_3364_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % AAA RRRR TTTTT % % A A R R T % % AAAAA RRRR T % % A A R R T % % A A R R T % % % % % % Support PFS: 1st Publisher Clip Art Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" /* Forward declarations. */ static MagickBooleanType WriteARTImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d A R T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadARTImage() reads an image of raw bits in LSB order and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadARTImage method is: % % Image *ReadARTImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception) { const unsigned char *pixels; Image *image; QuantumInfo *quantum_info; QuantumType quantum_type; MagickBooleanType status; size_t length; ssize_t count, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=1; image->endian=MSBEndian; (void) ReadBlobLSBShort(image); image->columns=(size_t) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); image->rows=(size_t) ReadBlobLSBShort(image); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image colormap. */ if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Convert bi-level image to pixel packets. */ SetImageColorspace(image,GRAYColorspace); quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) { quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) ReadBlobStream(image,(size_t) (-(ssize_t) length) & 0x01, GetQuantumPixels(quantum_info),&count); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r A R T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterARTImage() adds attributes for the ART image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterARTImage method is: % % size_t RegisterARTImage(void) % */ ModuleExport size_t RegisterARTImage(void) { MagickInfo *entry; entry=SetMagickInfo("ART"); entry->decoder=(DecodeImageHandler *) ReadARTImage; entry->encoder=(EncodeImageHandler *) WriteARTImage; entry->raw=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("PFS: 1st Publisher Clip Art"); entry->module=ConstantString("ART"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r A R T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterARTImage() removes format registrations made by the % ART module from the list of supported formats. % % The format of the UnregisterARTImage method is: % % UnregisterARTImage(void) % */ ModuleExport void UnregisterARTImage(void) { (void) UnregisterMagickInfo("ART"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e A R T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteARTImage() writes an image of raw bits in LSB order to a file. % % The format of the WriteARTImage method is: % % MagickBooleanType WriteARTImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteARTImage(const ImageInfo *image_info,Image *image) { MagickBooleanType status; QuantumInfo *quantum_info; register const PixelPacket *p; size_t length; ssize_t count, y; unsigned char *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); image->endian=MSBEndian; image->depth=1; (void) WriteBlobLSBShort(image,0); (void) WriteBlobLSBShort(image,(unsigned short) image->columns); (void) WriteBlobLSBShort(image,0); (void) WriteBlobLSBShort(image,(unsigned short) image->rows); (void) TransformImageColorspace(image,sRGBColorspace); length=(image->columns+7)/8; pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert image to a bi-level image. */ (void) SetImageType(image,BilevelType); quantum_info=AcquireQuantumInfo(image_info,image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, GrayQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) ThrowWriterException(CorruptImageError,"UnableToWriteImageData"); (void) WriteBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-772/c/good_3364_0
crossvul-cpp_data_bad_1039_0
/* * rfbserver.c - deal with server-side of the RFB protocol. */ /* * Copyright (C) 2011-2012 D. R. Commander * Copyright (C) 2005 Rohit Kumar, Johannes E. Schindelin * Copyright (C) 2002 RealVNC Ltd. * OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>. * Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge. * All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #ifdef __STRICT_ANSI__ #define _BSD_SOURCE #define _POSIX_SOURCE #define _XOPEN_SOURCE 600 #endif #include <stdio.h> #include <string.h> #include <rfb/rfb.h> #include <rfb/rfbregion.h> #include "private.h" #include "rfb/rfbconfig.h" #ifdef LIBVNCSERVER_HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #include <io.h> #define write(sock,buf,len) send(sock,buf,len,0) #else #ifdef LIBVNCSERVER_HAVE_UNISTD_H #include <unistd.h> #endif #include <pwd.h> #ifdef LIBVNCSERVER_HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef LIBVNCSERVER_HAVE_NETINET_IN_H #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <arpa/inet.h> #endif #endif #ifdef DEBUGPROTO #undef DEBUGPROTO #define DEBUGPROTO(x) x #else #define DEBUGPROTO(x) #endif #include <stdarg.h> #include <scale.h> /* stst() */ #include <sys/types.h> #include <sys/stat.h> #if LIBVNCSERVER_HAVE_UNISTD_H #include <unistd.h> #endif #ifndef WIN32 /* readdir() */ #include <dirent.h> #endif /* errno */ #include <errno.h> /* strftime() */ #include <time.h> /* INT_MAX */ #include <limits.h> #ifdef LIBVNCSERVER_WITH_WEBSOCKETS #include "rfbssl.h" #endif #ifdef _MSC_VER #define snprintf _snprintf /* Missing in MSVC */ /* Prevent POSIX deprecation warnings */ #define close _close #define strdup _strdup #endif #ifdef WIN32 #include <direct.h> #ifdef __MINGW32__ #define mkdir(path, perms) mkdir(path) /* Omit the perms argument to match POSIX signature */ #else /* MSVC and other windows compilers */ #define mkdir(path, perms) _mkdir(path) /* Omit the perms argument to match POSIX signature */ #endif /* __MINGW32__ else... */ #ifndef S_ISDIR #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR) #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* * Map of quality levels to provide compatibility with TightVNC/TigerVNC * clients. This emulates the behavior of the TigerVNC Server. */ static const int tight2turbo_qual[10] = { 15, 29, 41, 42, 62, 77, 79, 86, 92, 100 }; static const int tight2turbo_subsamp[10] = { 1, 1, 1, 2, 2, 2, 0, 0, 0, 0 }; #endif static void rfbProcessClientProtocolVersion(rfbClientPtr cl); static void rfbProcessClientNormalMessage(rfbClientPtr cl); static void rfbProcessClientInitMessage(rfbClientPtr cl); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD void rfbIncrClientRef(rfbClientPtr cl) { LOCK(cl->refCountMutex); cl->refCount++; UNLOCK(cl->refCountMutex); } void rfbDecrClientRef(rfbClientPtr cl) { LOCK(cl->refCountMutex); cl->refCount--; if(cl->refCount<=0) /* just to be sure also < 0 */ TSIGNAL(cl->deleteCond); UNLOCK(cl->refCountMutex); } #else void rfbIncrClientRef(rfbClientPtr cl) {} void rfbDecrClientRef(rfbClientPtr cl) {} #endif #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD static MUTEX(rfbClientListMutex); #endif struct rfbClientIterator { rfbClientPtr next; rfbScreenInfoPtr screen; rfbBool closedToo; }; void rfbClientListInit(rfbScreenInfoPtr rfbScreen) { if(sizeof(rfbBool)!=1) { /* a sanity check */ fprintf(stderr,"rfbBool's size is not 1 (%d)!\n",(int)sizeof(rfbBool)); /* we cannot continue, because rfbBool is supposed to be char everywhere */ exit(1); } rfbScreen->clientHead = NULL; INIT_MUTEX(rfbClientListMutex); } rfbClientIteratorPtr rfbGetClientIterator(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i = (rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator)); i->next = NULL; i->screen = rfbScreen; i->closedToo = FALSE; return i; } rfbClientIteratorPtr rfbGetClientIteratorWithClosed(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i = (rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator)); i->next = NULL; i->screen = rfbScreen; i->closedToo = TRUE; return i; } rfbClientPtr rfbClientIteratorHead(rfbClientIteratorPtr i) { #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(i->next != 0) { rfbDecrClientRef(i->next); rfbIncrClientRef(i->screen->clientHead); } #endif LOCK(rfbClientListMutex); i->next = i->screen->clientHead; UNLOCK(rfbClientListMutex); return i->next; } rfbClientPtr rfbClientIteratorNext(rfbClientIteratorPtr i) { if(i->next == 0) { LOCK(rfbClientListMutex); i->next = i->screen->clientHead; UNLOCK(rfbClientListMutex); } else { IF_PTHREADS(rfbClientPtr cl = i->next); i->next = i->next->next; IF_PTHREADS(rfbDecrClientRef(cl)); } #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(!i->closedToo) while(i->next && i->next->sock<0) i->next = i->next->next; if(i->next) rfbIncrClientRef(i->next); #endif return i->next; } void rfbReleaseClientIterator(rfbClientIteratorPtr iterator) { IF_PTHREADS(if(iterator->next) rfbDecrClientRef(iterator->next)); free(iterator); } /* * rfbNewClientConnection is called from sockets.c when a new connection * comes in. */ void rfbNewClientConnection(rfbScreenInfoPtr rfbScreen, int sock) { rfbNewClient(rfbScreen,sock); } /* * rfbReverseConnection is called to make an outward * connection to a "listening" RFB client. */ rfbClientPtr rfbReverseConnection(rfbScreenInfoPtr rfbScreen, char *host, int port) { int sock; rfbClientPtr cl; if ((sock = rfbConnect(rfbScreen, host, port)) < 0) return (rfbClientPtr)NULL; cl = rfbNewClient(rfbScreen, sock); if (cl) { cl->reverseConnection = TRUE; } return cl; } void rfbSetProtocolVersion(rfbScreenInfoPtr rfbScreen, int major_, int minor_) { /* Permit the server to set the version to report */ /* TODO: sanity checking */ if ((major_==3) && (minor_ > 2 && minor_ < 9)) { rfbScreen->protocolMajorVersion = major_; rfbScreen->protocolMinorVersion = minor_; } else rfbLog("rfbSetProtocolVersion(%d,%d) set to invalid values\n", major_, minor_); } /* * rfbNewClient is called when a new connection has been made by whatever * means. */ static rfbClientPtr rfbNewTCPOrUDPClient(rfbScreenInfoPtr rfbScreen, int sock, rfbBool isUDP) { rfbProtocolVersionMsg pv; rfbClientIteratorPtr iterator; rfbClientPtr cl,cl_; #ifdef LIBVNCSERVER_IPv6 struct sockaddr_storage addr; #else struct sockaddr_in addr; #endif socklen_t addrlen = sizeof(addr); rfbProtocolExtension* extension; cl = (rfbClientPtr)calloc(sizeof(rfbClientRec),1); cl->screen = rfbScreen; cl->sock = sock; cl->viewOnly = FALSE; /* setup pseudo scaling */ cl->scaledScreen = rfbScreen; cl->scaledScreen->scaledScreenRefCount++; rfbResetStats(cl); cl->clientData = NULL; cl->clientGoneHook = rfbDoNothingWithClient; if(isUDP) { rfbLog(" accepted UDP client\n"); } else { #ifdef LIBVNCSERVER_IPv6 char host[1024]; #endif int one=1; size_t otherClientsCount = 0; getpeername(sock, (struct sockaddr *)&addr, &addrlen); #ifdef LIBVNCSERVER_IPv6 if(getnameinfo((struct sockaddr*)&addr, addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST) != 0) { rfbLogPerror("rfbNewClient: error in getnameinfo"); cl->host = strdup(""); } else cl->host = strdup(host); #else cl->host = strdup(inet_ntoa(addr.sin_addr)); #endif iterator = rfbGetClientIterator(rfbScreen); while ((cl_ = rfbClientIteratorNext(iterator)) != NULL) ++otherClientsCount; rfbReleaseClientIterator(iterator); rfbLog(" %lu other clients\n", (unsigned long) otherClientsCount); if(!rfbSetNonBlocking(sock)) { close(sock); return NULL; } if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&one, sizeof(one)) < 0) { rfbLogPerror("setsockopt failed: can't set TCP_NODELAY flag, non TCP socket?"); } FD_SET(sock,&(rfbScreen->allFds)); rfbScreen->maxFd = rfbMax(sock,rfbScreen->maxFd); INIT_MUTEX(cl->outputMutex); INIT_MUTEX(cl->refCountMutex); INIT_MUTEX(cl->sendMutex); INIT_COND(cl->deleteCond); cl->state = RFB_PROTOCOL_VERSION; cl->reverseConnection = FALSE; cl->readyForSetColourMapEntries = FALSE; cl->useCopyRect = FALSE; cl->preferredEncoding = -1; cl->correMaxWidth = 48; cl->correMaxHeight = 48; #ifdef LIBVNCSERVER_HAVE_LIBZ cl->zrleData = NULL; #endif cl->copyRegion = sraRgnCreate(); cl->copyDX = 0; cl->copyDY = 0; cl->modifiedRegion = sraRgnCreateRect(0,0,rfbScreen->width,rfbScreen->height); INIT_MUTEX(cl->updateMutex); INIT_COND(cl->updateCond); cl->requestedRegion = sraRgnCreate(); cl->format = cl->screen->serverFormat; cl->translateFn = rfbTranslateNone; cl->translateLookupTable = NULL; LOCK(rfbClientListMutex); IF_PTHREADS(cl->refCount = 0); cl->next = rfbScreen->clientHead; cl->prev = NULL; if (rfbScreen->clientHead) rfbScreen->clientHead->prev = cl; rfbScreen->clientHead = cl; UNLOCK(rfbClientListMutex); #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) cl->tightQualityLevel = -1; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP; { int i; for (i = 0; i < 4; i++) cl->zsActive[i] = FALSE; } #endif #endif cl->fileTransfer.fd = -1; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorPosUpdates = FALSE; cl->useRichCursorEncoding = FALSE; cl->enableLastRectEncoding = FALSE; cl->enableKeyboardLedState = FALSE; cl->enableSupportedMessages = FALSE; cl->enableSupportedEncodings = FALSE; cl->enableServerIdentity = FALSE; cl->lastKeyboardLedState = -1; cl->cursorX = rfbScreen->cursorX; cl->cursorY = rfbScreen->cursorY; cl->useNewFBSize = FALSE; cl->useExtDesktopSize = FALSE; cl->requestedDesktopSizeChange = 0; cl->lastDesktopSizeChangeError = 0; #ifdef LIBVNCSERVER_HAVE_LIBZ cl->compStreamInited = FALSE; cl->compStream.total_in = 0; cl->compStream.total_out = 0; cl->compStream.zalloc = Z_NULL; cl->compStream.zfree = Z_NULL; cl->compStream.opaque = Z_NULL; cl->zlibCompressLevel = 5; #endif cl->progressiveSliceY = 0; cl->extensions = NULL; cl->lastPtrX = -1; #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD cl->pipe_notify_client_thread[0] = -1; cl->pipe_notify_client_thread[1] = -1; #endif #ifdef LIBVNCSERVER_WITH_WEBSOCKETS /* * Wait a few ms for the client to send WebSockets connection (TLS/SSL or plain) */ if (!webSocketsCheck(cl)) { /* Error reporting handled in webSocketsHandshake */ rfbCloseClient(cl); rfbClientConnectionGone(cl); return NULL; } #endif sprintf(pv,rfbProtocolVersionFormat,rfbScreen->protocolMajorVersion, rfbScreen->protocolMinorVersion); if (rfbWriteExact(cl, pv, sz_rfbProtocolVersionMsg) < 0) { rfbLogPerror("rfbNewClient: write"); rfbCloseClient(cl); rfbClientConnectionGone(cl); return NULL; } } for(extension = rfbGetExtensionIterator(); extension; extension=extension->next) { void* data = NULL; /* if the extension does not have a newClient method, it wants * to be initialized later. */ if(extension->newClient && extension->newClient(cl, &data)) rfbEnableExtension(cl, extension, data); } rfbReleaseExtensionIterator(); switch (cl->screen->newClientHook(cl)) { case RFB_CLIENT_ON_HOLD: cl->onHold = TRUE; break; case RFB_CLIENT_ACCEPT: cl->onHold = FALSE; break; case RFB_CLIENT_REFUSE: rfbCloseClient(cl); rfbClientConnectionGone(cl); cl = NULL; break; } return cl; } rfbClientPtr rfbNewClient(rfbScreenInfoPtr rfbScreen, int sock) { return(rfbNewTCPOrUDPClient(rfbScreen,sock,FALSE)); } rfbClientPtr rfbNewUDPClient(rfbScreenInfoPtr rfbScreen) { return((rfbScreen->udpClient= rfbNewTCPOrUDPClient(rfbScreen,rfbScreen->udpSock,TRUE))); } /* * rfbClientConnectionGone is called from sockets.c just after a connection * has gone away. */ void rfbClientConnectionGone(rfbClientPtr cl) { #if defined(LIBVNCSERVER_HAVE_LIBZ) && defined(LIBVNCSERVER_HAVE_LIBJPEG) int i; #endif LOCK(rfbClientListMutex); if (cl->prev) cl->prev->next = cl->next; else cl->screen->clientHead = cl->next; if (cl->next) cl->next->prev = cl->prev; UNLOCK(rfbClientListMutex); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(cl->screen->backgroundLoop != FALSE) { int i; do { LOCK(cl->refCountMutex); i=cl->refCount; if(i>0) WAIT(cl->deleteCond,cl->refCountMutex); UNLOCK(cl->refCountMutex); } while(i>0); } #endif if(cl->sock>=0) close(cl->sock); if (cl->scaledScreen!=NULL) cl->scaledScreen->scaledScreenRefCount--; #ifdef LIBVNCSERVER_HAVE_LIBZ rfbFreeZrleData(cl); #endif rfbFreeUltraData(cl); /* free buffers holding pixel data before and after encoding */ free(cl->beforeEncBuf); free(cl->afterEncBuf); if(cl->sock>=0) FD_CLR(cl->sock,&(cl->screen->allFds)); cl->clientGoneHook(cl); rfbLog("Client %s gone\n",cl->host); free(cl->host); #ifdef LIBVNCSERVER_HAVE_LIBZ /* Release the compression state structures if any. */ if ( cl->compStreamInited ) { deflateEnd( &(cl->compStream) ); } #ifdef LIBVNCSERVER_HAVE_LIBJPEG for (i = 0; i < 4; i++) { if (cl->zsActive[i]) deflateEnd(&cl->zsStruct[i]); } #endif #endif if (cl->screen->pointerClient == cl) cl->screen->pointerClient = NULL; sraRgnDestroy(cl->modifiedRegion); sraRgnDestroy(cl->requestedRegion); sraRgnDestroy(cl->copyRegion); if (cl->translateLookupTable) free(cl->translateLookupTable); TINI_COND(cl->updateCond); TINI_MUTEX(cl->updateMutex); /* make sure outputMutex is unlocked before destroying */ LOCK(cl->outputMutex); UNLOCK(cl->outputMutex); TINI_MUTEX(cl->outputMutex); LOCK(cl->sendMutex); UNLOCK(cl->sendMutex); TINI_MUTEX(cl->sendMutex); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD close(cl->pipe_notify_client_thread[0]); close(cl->pipe_notify_client_thread[1]); #endif rfbPrintStats(cl); rfbResetStats(cl); free(cl); } /* * rfbProcessClientMessage is called when there is data to read from a client. */ void rfbProcessClientMessage(rfbClientPtr cl) { switch (cl->state) { case RFB_PROTOCOL_VERSION: rfbProcessClientProtocolVersion(cl); return; case RFB_SECURITY_TYPE: rfbProcessClientSecurityType(cl); return; case RFB_AUTHENTICATION: rfbAuthProcessClientMessage(cl); return; case RFB_INITIALISATION: case RFB_INITIALISATION_SHARED: rfbProcessClientInitMessage(cl); return; default: rfbProcessClientNormalMessage(cl); return; } } /* * rfbProcessClientProtocolVersion is called when the client sends its * protocol version. */ static void rfbProcessClientProtocolVersion(rfbClientPtr cl) { rfbProtocolVersionMsg pv; int n, major_, minor_; if ((n = rfbReadExact(cl, pv, sz_rfbProtocolVersionMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientProtocolVersion: client gone\n"); else rfbLogPerror("rfbProcessClientProtocolVersion: read"); rfbCloseClient(cl); return; } pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv,rfbProtocolVersionFormat,&major_,&minor_) != 2) { rfbErr("rfbProcessClientProtocolVersion: not a valid RFB client: %s\n", pv); rfbCloseClient(cl); return; } rfbLog("Client Protocol Version %d.%d\n", major_, minor_); if (major_ != rfbProtocolMajorVersion) { rfbErr("RFB protocol version mismatch - server %d.%d, client %d.%d", cl->screen->protocolMajorVersion, cl->screen->protocolMinorVersion, major_,minor_); rfbCloseClient(cl); return; } /* Check for the minor version use either of the two standard version of RFB */ /* * UltraVNC Viewer detects FileTransfer compatible servers via rfb versions * 3.4, 3.6, 3.14, 3.16 * It's a bad method, but it is what they use to enable features... * maintaining RFB version compatibility across multiple servers is a pain * Should use something like ServerIdentity encoding */ cl->protocolMajorVersion = major_; cl->protocolMinorVersion = minor_; rfbLog("Protocol version sent %d.%d, using %d.%d\n", major_, minor_, rfbProtocolMajorVersion, cl->protocolMinorVersion); rfbAuthNewClient(cl); } void rfbClientSendString(rfbClientPtr cl, const char *reason) { char *buf; int len = strlen(reason); rfbLog("rfbClientSendString(\"%s\")\n", reason); buf = (char *)malloc(4 + len); ((uint32_t *)buf)[0] = Swap32IfLE(len); memcpy(buf + 4, reason, len); if (rfbWriteExact(cl, buf, 4 + len) < 0) rfbLogPerror("rfbClientSendString: write"); free(buf); rfbCloseClient(cl); } /* * rfbClientConnFailed is called when a client connection has failed either * because it talks the wrong protocol or it has failed authentication. */ void rfbClientConnFailed(rfbClientPtr cl, const char *reason) { char *buf; int len = strlen(reason); rfbLog("rfbClientConnFailed(\"%s\")\n", reason); buf = (char *)malloc(8 + len); ((uint32_t *)buf)[0] = Swap32IfLE(rfbConnFailed); ((uint32_t *)buf)[1] = Swap32IfLE(len); memcpy(buf + 8, reason, len); if (rfbWriteExact(cl, buf, 8 + len) < 0) rfbLogPerror("rfbClientConnFailed: write"); free(buf); rfbCloseClient(cl); } /* * rfbProcessClientInitMessage is called when the client sends its * initialisation message. */ static void rfbProcessClientInitMessage(rfbClientPtr cl) { rfbClientInitMsg ci; union { char buf[256]; rfbServerInitMsg si; } u; int len, n; rfbClientIteratorPtr iterator; rfbClientPtr otherCl; rfbExtensionData* extension; if (cl->state == RFB_INITIALISATION_SHARED) { /* In this case behave as though an implicit ClientInit message has * already been received with a shared-flag of true. */ ci.shared = 1; /* Avoid the possibility of exposing the RFB_INITIALISATION_SHARED * state to calling software. */ cl->state = RFB_INITIALISATION; } else { if ((n = rfbReadExact(cl, (char *)&ci,sz_rfbClientInitMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientInitMessage: client gone\n"); else rfbLogPerror("rfbProcessClientInitMessage: read"); rfbCloseClient(cl); return; } } memset(u.buf,0,sizeof(u.buf)); u.si.framebufferWidth = Swap16IfLE(cl->screen->width); u.si.framebufferHeight = Swap16IfLE(cl->screen->height); u.si.format = cl->screen->serverFormat; u.si.format.redMax = Swap16IfLE(u.si.format.redMax); u.si.format.greenMax = Swap16IfLE(u.si.format.greenMax); u.si.format.blueMax = Swap16IfLE(u.si.format.blueMax); strncpy(u.buf + sz_rfbServerInitMsg, cl->screen->desktopName, 127); len = strlen(u.buf + sz_rfbServerInitMsg); u.si.nameLength = Swap32IfLE(len); if (rfbWriteExact(cl, u.buf, sz_rfbServerInitMsg + len) < 0) { rfbLogPerror("rfbProcessClientInitMessage: write"); rfbCloseClient(cl); return; } for(extension = cl->extensions; extension;) { rfbExtensionData* next = extension->next; if(extension->extension->init && !extension->extension->init(cl, extension->data)) /* extension requested that it be removed */ rfbDisableExtension(cl, extension->extension); extension = next; } cl->state = RFB_NORMAL; if (!cl->reverseConnection && (cl->screen->neverShared || (!cl->screen->alwaysShared && !ci.shared))) { if (cl->screen->dontDisconnect) { iterator = rfbGetClientIterator(cl->screen); while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("-dontdisconnect: Not shared & existing client\n"); rfbLog(" refusing new client %s\n", cl->host); rfbCloseClient(cl); rfbReleaseClientIterator(iterator); return; } } rfbReleaseClientIterator(iterator); } else { iterator = rfbGetClientIterator(cl->screen); while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("Not shared - closing connection to client %s\n", otherCl->host); rfbCloseClient(otherCl); } } rfbReleaseClientIterator(iterator); } } } /* The values come in based on the scaled screen, we need to convert them to * values based on the man screen's coordinate system */ static rfbBool rectSwapIfLEAndClip(uint16_t* x,uint16_t* y,uint16_t* w,uint16_t* h, rfbClientPtr cl) { int x1=Swap16IfLE(*x); int y1=Swap16IfLE(*y); int w1=Swap16IfLE(*w); int h1=Swap16IfLE(*h); rfbScaledCorrection(cl->scaledScreen, cl->screen, &x1, &y1, &w1, &h1, "rectSwapIfLEAndClip"); *x = x1; *y = y1; *w = w1; *h = h1; if(*w>cl->screen->width-*x) *w=cl->screen->width-*x; /* possible underflow */ if(*w>cl->screen->width-*x) return FALSE; if(*h>cl->screen->height-*y) *h=cl->screen->height-*y; if(*h>cl->screen->height-*y) return FALSE; return TRUE; } /* * Send keyboard state (PointerPos pseudo-encoding). */ rfbBool rfbSendKeyboardLedState(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingKeyboardLedState); rect.r.x = Swap16IfLE(cl->lastKeyboardLedState); rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingKeyboardLedState, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } #define rfbSetBit(buffer, position) (buffer[(position & 255) / 8] |= (1 << (position % 8))) /* * Send rfbEncodingSupportedMessages. */ rfbBool rfbSendSupportedMessages(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; rfbSupportedMessages msgs; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbSupportedMessages > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingSupportedMessages); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(sz_rfbSupportedMessages); rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; memset((char *)&msgs, 0, sz_rfbSupportedMessages); rfbSetBit(msgs.client2server, rfbSetPixelFormat); rfbSetBit(msgs.client2server, rfbFixColourMapEntries); rfbSetBit(msgs.client2server, rfbSetEncodings); rfbSetBit(msgs.client2server, rfbFramebufferUpdateRequest); rfbSetBit(msgs.client2server, rfbKeyEvent); rfbSetBit(msgs.client2server, rfbPointerEvent); rfbSetBit(msgs.client2server, rfbClientCutText); rfbSetBit(msgs.client2server, rfbFileTransfer); rfbSetBit(msgs.client2server, rfbSetScale); /*rfbSetBit(msgs.client2server, rfbSetServerInput); */ /*rfbSetBit(msgs.client2server, rfbSetSW); */ /*rfbSetBit(msgs.client2server, rfbTextChat); */ rfbSetBit(msgs.client2server, rfbPalmVNCSetScaleFactor); rfbSetBit(msgs.server2client, rfbFramebufferUpdate); rfbSetBit(msgs.server2client, rfbSetColourMapEntries); rfbSetBit(msgs.server2client, rfbBell); rfbSetBit(msgs.server2client, rfbServerCutText); rfbSetBit(msgs.server2client, rfbResizeFrameBuffer); rfbSetBit(msgs.server2client, rfbPalmVNCReSizeFrameBuffer); rfbSetBit(msgs.client2server, rfbSetDesktopSize); if (cl->screen->xvpHook) { rfbSetBit(msgs.client2server, rfbXvp); rfbSetBit(msgs.server2client, rfbXvp); } memcpy(&cl->updateBuf[cl->ublen], (char *)&msgs, sz_rfbSupportedMessages); cl->ublen += sz_rfbSupportedMessages; rfbStatRecordEncodingSent(cl, rfbEncodingSupportedMessages, sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages, sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } /* * Send rfbEncodingSupportedEncodings. */ rfbBool rfbSendSupportedEncodings(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; static uint32_t supported[] = { rfbEncodingRaw, rfbEncodingCopyRect, rfbEncodingRRE, rfbEncodingCoRRE, rfbEncodingHextile, #ifdef LIBVNCSERVER_HAVE_LIBZ rfbEncodingZlib, rfbEncodingZRLE, rfbEncodingZYWRLE, #endif #ifdef LIBVNCSERVER_HAVE_LIBJPEG rfbEncodingTight, #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG rfbEncodingTightPng, #endif rfbEncodingUltra, rfbEncodingUltraZip, rfbEncodingXCursor, rfbEncodingRichCursor, rfbEncodingPointerPos, rfbEncodingLastRect, rfbEncodingNewFBSize, rfbEncodingExtDesktopSize, rfbEncodingKeyboardLedState, rfbEncodingSupportedMessages, rfbEncodingSupportedEncodings, rfbEncodingServerIdentity, }; uint32_t nEncodings = sizeof(supported) / sizeof(supported[0]), i; /* think rfbSetEncodingsMsg */ if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + (nEncodings * sizeof(uint32_t)) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingSupportedEncodings); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(nEncodings * sizeof(uint32_t)); rect.r.h = Swap16IfLE(nEncodings); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; for (i = 0; i < nEncodings; i++) { uint32_t encoding = Swap32IfLE(supported[i]); memcpy(&cl->updateBuf[cl->ublen], (char *)&encoding, sizeof(encoding)); cl->ublen += sizeof(encoding); } rfbStatRecordEncodingSent(cl, rfbEncodingSupportedEncodings, sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t)), sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t))); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } void rfbSetServerVersionIdentity(rfbScreenInfoPtr screen, char *fmt, ...) { char buffer[256]; va_list ap; va_start(ap, fmt); vsnprintf(buffer, sizeof(buffer)-1, fmt, ap); va_end(ap); if (screen->versionString!=NULL) free(screen->versionString); screen->versionString = strdup(buffer); } /* * Send rfbEncodingServerIdentity. */ rfbBool rfbSendServerIdentity(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; char buffer[512]; /* tack on our library version */ snprintf(buffer,sizeof(buffer)-1, "%s (%s)", (cl->screen->versionString==NULL ? "unknown" : cl->screen->versionString), LIBVNCSERVER_PACKAGE_STRING); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + (strlen(buffer)+1) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingServerIdentity); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(strlen(buffer)+1); rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; memcpy(&cl->updateBuf[cl->ublen], buffer, strlen(buffer)+1); cl->ublen += strlen(buffer)+1; rfbStatRecordEncodingSent(cl, rfbEncodingServerIdentity, sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1, sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } /* * Send an xvp server message */ rfbBool rfbSendXvp(rfbClientPtr cl, uint8_t version, uint8_t code) { rfbXvpMsg xvp; xvp.type = rfbXvp; xvp.pad = 0; xvp.version = version; xvp.code = code; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&xvp, sz_rfbXvpMsg) < 0) { rfbLogPerror("rfbSendXvp: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbXvp, sz_rfbXvpMsg, sz_rfbXvpMsg); return TRUE; } rfbBool rfbSendTextChatMessage(rfbClientPtr cl, uint32_t length, char *buffer) { rfbTextChatMsg tc; int bytesToSend=0; memset((char *)&tc, 0, sizeof(tc)); tc.type = rfbTextChat; tc.length = Swap32IfLE(length); switch(length) { case rfbTextChatOpen: case rfbTextChatClose: case rfbTextChatFinished: bytesToSend=0; break; default: bytesToSend=length; if (bytesToSend>rfbTextMaxSize) bytesToSend=rfbTextMaxSize; } if (cl->ublen + sz_rfbTextChatMsg + bytesToSend > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } memcpy(&cl->updateBuf[cl->ublen], (char *)&tc, sz_rfbTextChatMsg); cl->ublen += sz_rfbTextChatMsg; if (bytesToSend>0) { memcpy(&cl->updateBuf[cl->ublen], buffer, bytesToSend); cl->ublen += bytesToSend; } rfbStatRecordMessageSent(cl, rfbTextChat, sz_rfbTextChatMsg+bytesToSend, sz_rfbTextChatMsg+bytesToSend); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } #define FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(msg, cl, ret) \ if ((cl->screen->getFileTransferPermission != NULL \ && cl->screen->getFileTransferPermission(cl) != TRUE) \ || cl->screen->permitFileTransfer != TRUE) { \ rfbLog("%sUltra File Transfer is disabled, dropping client: %s\n", msg, cl->host); \ rfbCloseClient(cl); \ return ret; \ } int DB = 1; rfbBool rfbSendFileTransferMessage(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length, const char *buffer) { rfbFileTransferMsg ft; ft.type = rfbFileTransfer; ft.contentType = contentType; ft.contentParam = contentParam; ft.pad = 0; /* UltraVNC did not Swap16LE(ft.contentParam) (Looks like it might be BigEndian) */ ft.size = Swap32IfLE(size); ft.length = Swap32IfLE(length); FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* rfbLog("rfbSendFileTransferMessage( %dtype, %dparam, %dsize, %dlen, %p)\n", contentType, contentParam, size, length, buffer); */ LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&ft, sz_rfbFileTransferMsg) < 0) { rfbLogPerror("rfbSendFileTransferMessage: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); return FALSE; } if (length>0) { if (rfbWriteExact(cl, buffer, length) < 0) { rfbLogPerror("rfbSendFileTransferMessage: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); return FALSE; } } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbFileTransfer, sz_rfbFileTransferMsg+length, sz_rfbFileTransferMsg+length); return TRUE; } /* * UltraVNC uses Windows Structures */ #define MAX_PATH 260 typedef struct { uint32_t dwLowDateTime; uint32_t dwHighDateTime; } RFB_FILETIME; typedef struct { uint32_t dwFileAttributes; RFB_FILETIME ftCreationTime; RFB_FILETIME ftLastAccessTime; RFB_FILETIME ftLastWriteTime; uint32_t nFileSizeHigh; uint32_t nFileSizeLow; uint32_t dwReserved0; uint32_t dwReserved1; uint8_t cFileName[ MAX_PATH ]; uint8_t cAlternateFileName[ 14 ]; } RFB_FIND_DATA; #define RFB_FILE_ATTRIBUTE_READONLY 0x1 #define RFB_FILE_ATTRIBUTE_HIDDEN 0x2 #define RFB_FILE_ATTRIBUTE_SYSTEM 0x4 #define RFB_FILE_ATTRIBUTE_DIRECTORY 0x10 #define RFB_FILE_ATTRIBUTE_ARCHIVE 0x20 #define RFB_FILE_ATTRIBUTE_NORMAL 0x80 #define RFB_FILE_ATTRIBUTE_TEMPORARY 0x100 #define RFB_FILE_ATTRIBUTE_COMPRESSED 0x800 rfbBool rfbFilenameTranslate2UNIX(rfbClientPtr cl, /* in */ char *path, /* out */ char *unixPath, size_t unixPathMaxLen) { int x; char *home=NULL; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* * Do not use strncpy() - truncating the file name would probably have undesirable side effects * Instead check if destination buffer is big enough */ if (strlen(path) >= unixPathMaxLen) return FALSE; /* C: */ if (path[0]=='C' && path[1]==':') strcpy(unixPath, &path[2]); else { home = getenv("HOME"); if (home!=NULL) { /* Re-check buffer size */ if ((strlen(path) + strlen(home) + 1) >= unixPathMaxLen) return FALSE; strcpy(unixPath, home); strcat(unixPath,"/"); strcat(unixPath, path); } else strcpy(unixPath, path); } for (x=0;x<strlen(unixPath);x++) if (unixPath[x]=='\\') unixPath[x]='/'; return TRUE; } rfbBool rfbFilenameTranslate2DOS(rfbClientPtr cl, char *unixPath, char *path) { int x; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); sprintf(path,"C:%s", unixPath); for (x=2;x<strlen(path);x++) if (path[x]=='/') path[x]='\\'; return TRUE; } rfbBool rfbSendDirContent(rfbClientPtr cl, int length, char *buffer) { char retfilename[MAX_PATH]; char path[MAX_PATH]; struct stat statbuf; RFB_FIND_DATA win32filename; int nOptLen = 0, retval=0; #ifdef WIN32 WIN32_FIND_DATAA winFindData; HANDLE findHandle; int pathLen, basePathLength; char *basePath; #else DIR *dirp=NULL; struct dirent *direntp=NULL; #endif FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* Client thinks we are Winblows */ if (!rfbFilenameTranslate2UNIX(cl, buffer, path, sizeof(path))) return FALSE; if (DB) rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: \"%s\"->\"%s\"\n",buffer, path); #ifdef WIN32 // Create a search string, like C:\folder\* pathLen = strlen(path); basePath = malloc(pathLen + 3); memcpy(basePath, path, pathLen); basePathLength = pathLen; basePath[basePathLength] = '\\'; basePath[basePathLength + 1] = '*'; basePath[basePathLength + 2] = '\0'; // Start a search memset(&winFindData, 0, sizeof(winFindData)); findHandle = FindFirstFileA(path, &winFindData); free(basePath); if (findHandle == INVALID_HANDLE_VALUE) #else dirp=opendir(path); if (dirp==NULL) #endif return rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, 0, NULL); /* send back the path name (necessary for links) */ if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, length, buffer)==FALSE) return FALSE; #ifdef WIN32 while (findHandle != INVALID_HANDLE_VALUE) #else for (direntp=readdir(dirp); direntp!=NULL; direntp=readdir(dirp)) #endif { /* get stats */ #ifdef WIN32 snprintf(retfilename,sizeof(retfilename),"%s/%s", path, winFindData.cFileName); #else snprintf(retfilename,sizeof(retfilename),"%s/%s", path, direntp->d_name); #endif retval = stat(retfilename, &statbuf); if (retval==0) { memset((char *)&win32filename, 0, sizeof(win32filename)); #ifdef WIN32 win32filename.dwFileAttributes = winFindData.dwFileAttributes; win32filename.ftCreationTime.dwLowDateTime = winFindData.ftCreationTime.dwLowDateTime; win32filename.ftCreationTime.dwHighDateTime = winFindData.ftCreationTime.dwHighDateTime; win32filename.ftLastAccessTime.dwLowDateTime = winFindData.ftLastAccessTime.dwLowDateTime; win32filename.ftLastAccessTime.dwHighDateTime = winFindData.ftLastAccessTime.dwHighDateTime; win32filename.ftLastWriteTime.dwLowDateTime = winFindData.ftLastWriteTime.dwLowDateTime; win32filename.ftLastWriteTime.dwHighDateTime = winFindData.ftLastWriteTime.dwHighDateTime; win32filename.nFileSizeLow = winFindData.nFileSizeLow; win32filename.nFileSizeHigh = winFindData.nFileSizeHigh; win32filename.dwReserved0 = winFindData.dwReserved0; win32filename.dwReserved1 = winFindData.dwReserved1; strcpy((char *)win32filename.cFileName, winFindData.cFileName); strcpy((char *)win32filename.cAlternateFileName, winFindData.cAlternateFileName); #else win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_NORMAL); if (S_ISDIR(statbuf.st_mode)) win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_DIRECTORY); win32filename.ftCreationTime.dwLowDateTime = Swap32IfBE(statbuf.st_ctime); /* Intel Order */ win32filename.ftCreationTime.dwHighDateTime = 0; win32filename.ftLastAccessTime.dwLowDateTime = Swap32IfBE(statbuf.st_atime); /* Intel Order */ win32filename.ftLastAccessTime.dwHighDateTime = 0; win32filename.ftLastWriteTime.dwLowDateTime = Swap32IfBE(statbuf.st_mtime); /* Intel Order */ win32filename.ftLastWriteTime.dwHighDateTime = 0; win32filename.nFileSizeLow = Swap32IfBE(statbuf.st_size); /* Intel Order */ win32filename.nFileSizeHigh = 0; win32filename.dwReserved0 = 0; win32filename.dwReserved1 = 0; /* If this had the full path, we would need to translate to DOS format ("C:\") */ /* rfbFilenameTranslate2DOS(cl, retfilename, win32filename.cFileName); */ strcpy((char *)win32filename.cFileName, direntp->d_name); #endif /* Do not show hidden files (but show how to move up the tree) */ if ((strcmp((char *)win32filename.cFileName, "..")==0) || (win32filename.cFileName[0]!='.')) { nOptLen = sizeof(RFB_FIND_DATA) - MAX_PATH - 14 + strlen((char *)win32filename.cFileName); /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: Sending \"%s\"\n", (char *)win32filename.cFileName); */ if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, nOptLen, (char *)&win32filename)==FALSE) { #ifdef WIN32 FindClose(findHandle); #else closedir(dirp); #endif return FALSE; } } } #ifdef WIN32 if (FindNextFileA(findHandle, &winFindData) == 0) { FindClose(findHandle); findHandle = INVALID_HANDLE_VALUE; } #endif } #ifdef WIN32 if (findHandle != INVALID_HANDLE_VALUE) { FindClose(findHandle); } #else closedir(dirp); #endif /* End of the transfer */ return rfbSendFileTransferMessage(cl, rfbDirPacket, 0, 0, 0, NULL); } char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length) { char *buffer=NULL; int n=0; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, NULL); /* We later alloc length+1, which might wrap around on 32-bit systems if length equals 0XFFFFFFFF, i.e. SIZE_MAX for 32-bit systems. On 64-bit systems, a length of 0XFFFFFFFF will safely be allocated since this check will never trigger and malloc() can digest length+1 without problems as length is a uint32_t. We also later pass length to rfbReadExact() that expects a signed int type and that might wrap on platforms with a 32-bit int type if length is bigger than 0X7FFFFFFF. */ if(length == SIZE_MAX || length > INT_MAX) { rfbErr("rfbProcessFileTransferReadBuffer: too big file transfer length requested: %u", (unsigned int)length); rfbCloseClient(cl); return NULL; } if (length>0) { buffer=malloc((size_t)length+1); if (buffer!=NULL) { if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransferReadBuffer: read"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return NULL; } /* Null Terminate */ buffer[length]=0; } } return buffer; } rfbBool rfbSendFileTransferChunk(rfbClientPtr cl) { /* Allocate buffer for compression */ unsigned char readBuf[sz_rfbBlockSize]; int bytesRead=0; int retval=0; fd_set wfds; struct timeval tv; int n; #ifdef LIBVNCSERVER_HAVE_LIBZ unsigned char compBuf[sz_rfbBlockSize + 1024]; unsigned long nMaxCompSize = sizeof(compBuf); int nRetC = 0; #endif /* * Don't close the client if we get into this one because * it is called from many places to service file transfers. * Note that permitFileTransfer is checked first. */ if (cl->screen->permitFileTransfer != TRUE || (cl->screen->getFileTransferPermission != NULL && cl->screen->getFileTransferPermission(cl) != TRUE)) { return TRUE; } /* If not sending, or no file open... Return as if we sent something! */ if ((cl->fileTransfer.fd!=-1) && (cl->fileTransfer.sending==1)) { FD_ZERO(&wfds); FD_SET(cl->sock, &wfds); /* return immediately */ tv.tv_sec = 0; tv.tv_usec = 0; n = select(cl->sock + 1, NULL, &wfds, NULL, &tv); if (n<0) { #ifdef WIN32 errno=WSAGetLastError(); #endif rfbLog("rfbSendFileTransferChunk() select failed: %s\n", strerror(errno)); } /* We have space on the transmit queue */ if (n > 0) { bytesRead = read(cl->fileTransfer.fd, readBuf, sz_rfbBlockSize); switch (bytesRead) { case 0: /* rfbLog("rfbSendFileTransferChunk(): End-Of-File Encountered\n"); */ retval = rfbSendFileTransferMessage(cl, rfbEndOfFile, 0, 0, 0, NULL); close(cl->fileTransfer.fd); cl->fileTransfer.fd = -1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; return retval; case -1: /* TODO : send an error msg to the client... */ #ifdef WIN32 errno=WSAGetLastError(); #endif rfbLog("rfbSendFileTransferChunk(): %s\n",strerror(errno)); retval = rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, 0, 0, NULL); close(cl->fileTransfer.fd); cl->fileTransfer.fd = -1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; return retval; default: /* rfbLog("rfbSendFileTransferChunk(): Read %d bytes\n", bytesRead); */ if (!cl->fileTransfer.compressionEnabled) return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); else { #ifdef LIBVNCSERVER_HAVE_LIBZ nRetC = compress(compBuf, &nMaxCompSize, readBuf, bytesRead); /* rfbLog("Compressed the packet from %d -> %d bytes\n", nMaxCompSize, bytesRead); */ if ((nRetC==0) && (nMaxCompSize<bytesRead)) return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 1, nMaxCompSize, (char *)compBuf); else return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); #else /* We do not support compression of the data stream */ return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); #endif } } } } return TRUE; } rfbBool rfbProcessFileTransfer(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length) { char *buffer=NULL, *p=NULL; int retval=0; char filename1[MAX_PATH]; char filename2[MAX_PATH]; char szFileTime[MAX_PATH]; struct stat statbuf; uint32_t sizeHtmp=0; int n=0; char timespec[64]; #ifdef LIBVNCSERVER_HAVE_LIBZ unsigned char compBuff[sz_rfbBlockSize]; unsigned long nRawBytes = sz_rfbBlockSize; int nRet = 0; #endif FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* rfbLog("rfbProcessFileTransfer(%dtype, %dparam, %dsize, %dlen)\n", contentType, contentParam, size, length); */ switch (contentType) { case rfbDirContentRequest: switch (contentParam) { case rfbRDrivesList: /* Client requests the List of Local Drives */ /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDrivesList:\n"); */ /* Format when filled : "C:\<NULL>D:\<NULL>....Z:\<NULL><NULL> * * We replace the "\" char following the drive letter and ":" * with a char corresponding to the type of drive * We obtain something like "C:l<NULL>D:c<NULL>....Z:n\<NULL><NULL>" * Isn't it ugly ? * DRIVE_FIXED = 'l' (local?) * DRIVE_REMOVABLE = 'f' (floppy?) * DRIVE_CDROM = 'c' * DRIVE_REMOTE = 'n' */ /* in unix, there are no 'drives' (We could list mount points though) * We fake the root as a "C:" for the Winblows users */ filename2[0]='C'; filename2[1]=':'; filename2[2]='l'; filename2[3]=0; filename2[4]=0; retval = rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADrivesList, 0, 5, filename2); if (buffer!=NULL) free(buffer); return retval; break; case rfbRDirContent: /* Client requests the content of a directory */ /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; retval = rfbSendDirContent(cl, length, buffer); if (buffer!=NULL) free(buffer); return retval; } break; case rfbDirPacket: rfbLog("rfbProcessFileTransfer() rfbDirPacket\n"); break; case rfbFileAcceptHeader: rfbLog("rfbProcessFileTransfer() rfbFileAcceptHeader\n"); break; case rfbCommandReturn: rfbLog("rfbProcessFileTransfer() rfbCommandReturn\n"); break; case rfbFileChecksums: /* Destination file already exists - the viewer sends the checksums */ rfbLog("rfbProcessFileTransfer() rfbFileChecksums\n"); break; case rfbFileTransferAccess: rfbLog("rfbProcessFileTransfer() rfbFileTransferAccess\n"); break; /* * sending from the server to the viewer */ case rfbFileTransferRequest: /* rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest:\n"); */ /* add some space to the end of the buffer as we will be adding a timespec to it */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; /* The client requests a File */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; cl->fileTransfer.fd=open(filename1, O_RDONLY, 0744); /* */ if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\") Open: %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), cl->fileTransfer.fd); if (cl->fileTransfer.fd!=-1) { if (fstat(cl->fileTransfer.fd, &statbuf)!=0) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; } else { /* Add the File Time Stamp to the filename */ strftime(timespec, sizeof(timespec), "%m/%d/%Y %H:%M",gmtime(&statbuf.st_ctime)); buffer=realloc(buffer, length + strlen(timespec) + 2); /* comma, and Null term */ if (buffer==NULL) { rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest: Failed to malloc %d bytes\n", length + strlen(timespec) + 2); return FALSE; } strcat(buffer,","); strcat(buffer, timespec); length = strlen(buffer); if (DB) rfbLog("rfbProcessFileTransfer() buffer is now: \"%s\"\n", buffer); } } /* The viewer supports compression if size==1 */ cl->fileTransfer.compressionEnabled = (size==1); /* rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\")%s\n", buffer, filename1, (size==1?" <Compression Enabled>":"")); */ /* File Size in bytes, 0xFFFFFFFF (-1) means error */ retval = rfbSendFileTransferMessage(cl, rfbFileHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : statbuf.st_size), length, buffer); if (cl->fileTransfer.fd==-1) { if (buffer!=NULL) free(buffer); return retval; } /* setup filetransfer stuff */ cl->fileTransfer.fileSize = statbuf.st_size; cl->fileTransfer.numPackets = statbuf.st_size / sz_rfbBlockSize; cl->fileTransfer.receiving = 0; cl->fileTransfer.sending = 0; /* set when we receive a rfbFileHeader: */ /* TODO: finish 64-bit file size support */ sizeHtmp = 0; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&sizeHtmp, 4) < 0) { rfbLogPerror("rfbProcessFileTransfer: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); if (buffer!=NULL) free(buffer); return FALSE; } UNLOCK(cl->sendMutex); break; case rfbFileHeader: /* Destination file (viewer side) is ready for reception (size > 0) or not (size = -1) */ if (size==-1) { rfbLog("rfbProcessFileTransfer() rfbFileHeader (error, aborting)\n"); close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; return TRUE; } /* rfbLog("rfbProcessFileTransfer() rfbFileHeader (%d bytes of a file)\n", size); */ /* Starts the transfer! */ cl->fileTransfer.sending=1; return rfbSendFileTransferChunk(cl); break; /* * sending from the viewer to the server */ case rfbFileTransferOffer: /* client is sending a file to us */ /* buffer contains full path name (plus FileTime) */ /* size contains size of the file */ /* rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; /* Parse the FileTime */ p = strrchr(buffer, ','); if (p!=NULL) { *p = '\0'; strncpy(szFileTime, p+1, sizeof(szFileTime)); szFileTime[sizeof(szFileTime)-1] = '\x00'; /* ensure NULL terminating byte is present, even if copy overflowed */ } else szFileTime[0]=0; /* Need to read in sizeHtmp */ if ((n = rfbReadExact(cl, (char *)&sizeHtmp, 4)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransfer: read sizeHtmp"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return FALSE; } sizeHtmp = Swap32IfLE(sizeHtmp); if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; /* If the file exists... We can send a rfbFileChecksums back to the client before we send an rfbFileAcceptHeader */ /* TODO: Delta Transfer */ cl->fileTransfer.fd=open(filename1, O_CREAT|O_WRONLY|O_TRUNC, 0744); if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer(\"%s\"->\"%s\") %s %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), (cl->fileTransfer.fd==-1?strerror(errno):""), cl->fileTransfer.fd); /* */ /* File Size in bytes, 0xFFFFFFFF (-1) means error */ retval = rfbSendFileTransferMessage(cl, rfbFileAcceptHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : 0), length, buffer); if (cl->fileTransfer.fd==-1) { free(buffer); return retval; } /* setup filetransfer stuff */ cl->fileTransfer.fileSize = size; cl->fileTransfer.numPackets = size / sz_rfbBlockSize; cl->fileTransfer.receiving = 1; cl->fileTransfer.sending = 0; break; case rfbFilePacket: /* rfbLog("rfbProcessFileTransfer() rfbFilePacket:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; if (cl->fileTransfer.fd!=-1) { /* buffer contains the contents of the file */ if (size==0) retval=write(cl->fileTransfer.fd, buffer, length); else { #ifdef LIBVNCSERVER_HAVE_LIBZ /* compressed packet */ nRet = uncompress(compBuff,&nRawBytes,(const unsigned char*)buffer, length); if(nRet == Z_OK) retval=write(cl->fileTransfer.fd, (char*)compBuff, nRawBytes); else retval = -1; #else /* Write the file out as received... */ retval=write(cl->fileTransfer.fd, buffer, length); #endif } if (retval==-1) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; } } break; case rfbEndOfFile: if (DB) rfbLog("rfbProcessFileTransfer() rfbEndOfFile\n"); /* */ if (cl->fileTransfer.fd!=-1) close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; break; case rfbAbortFileTransfer: if (DB) rfbLog("rfbProcessFileTransfer() rfbAbortFileTransfer\n"); /* */ if (cl->fileTransfer.fd!=-1) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; } else { /* We use this message for FileTransfer rights (<=RC18 versions) * The client asks for FileTransfer permission */ if (contentParam == 0) { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED! (Client Version <=RC18)\n"); /* Old method for FileTransfer handshake perimssion (<=RC18) (Deny it)*/ return rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, -1, 0, ""); } /* New method is allowed */ if (cl->screen->getFileTransferPermission!=NULL) { if (cl->screen->getFileTransferPermission(cl)==TRUE) { rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */ } else { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* Deny */ } } else { if (cl->screen->permitFileTransfer) { rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */ } else { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED by default!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* DEFAULT: DENY (for security) */ } } } break; case rfbCommand: /* rfbLog("rfbProcessFileTransfer() rfbCommand:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; switch (contentParam) { case rfbCDirCreate: /* Client requests the creation of a directory */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; retval = mkdir(filename1, 0755); if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCDirCreate(\"%s\"->\"%s\") %s\n", buffer, filename1, (retval==-1?"Failed":"Success")); /* */ retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbADirCreate, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; case rfbCFileDelete: /* Client requests the deletion of a file */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; if (stat(filename1,&statbuf)==0) { if (S_ISDIR(statbuf.st_mode)) retval = rmdir(filename1); else retval = unlink(filename1); } else retval=-1; retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileDelete, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; case rfbCFileRename: /* Client requests the Renaming of a file/directory */ p = strrchr(buffer, '*'); if (p != NULL) { /* Split into 2 filenames ('*' is a seperator) */ *p = '\0'; if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; if (!rfbFilenameTranslate2UNIX(cl, p+1, filename2, sizeof(filename2))) goto fail; retval = rename(filename1,filename2); if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCFileRename(\"%s\"->\"%s\" -->> \"%s\"->\"%s\") %s\n", buffer, filename1, p+1, filename2, (retval==-1?"Failed":"Success")); /* */ /* Restore the buffer so the reply is good */ *p = '*'; retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileRename, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; } break; } break; } /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return TRUE; fail: if (buffer!=NULL) free(buffer); return FALSE; } /* * rfbProcessClientNormalMessage is called when the client has sent a normal * protocol message. */ static void rfbProcessClientNormalMessage(rfbClientPtr cl) { int n=0; rfbClientToServerMsg msg; char *str; int i; uint32_t enc=0; uint32_t lastPreferredEncoding = -1; char encBuf[64]; char encBuf2[64]; rfbExtDesktopScreen *extDesktopScreens; rfbClientIteratorPtr iterator; rfbClientPtr clp; if ((n = rfbReadExact(cl, (char *)&msg, 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } switch (msg.type) { case rfbSetPixelFormat: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetPixelFormatMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } cl->format.bitsPerPixel = msg.spf.format.bitsPerPixel; cl->format.depth = msg.spf.format.depth; cl->format.bigEndian = (msg.spf.format.bigEndian ? TRUE : FALSE); cl->format.trueColour = (msg.spf.format.trueColour ? TRUE : FALSE); cl->format.redMax = Swap16IfLE(msg.spf.format.redMax); cl->format.greenMax = Swap16IfLE(msg.spf.format.greenMax); cl->format.blueMax = Swap16IfLE(msg.spf.format.blueMax); cl->format.redShift = msg.spf.format.redShift; cl->format.greenShift = msg.spf.format.greenShift; cl->format.blueShift = msg.spf.format.blueShift; cl->readyForSetColourMapEntries = TRUE; cl->screen->setTranslateFunction(cl); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg); return; case rfbFixColourMapEntries: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFixColourMapEntriesMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg); rfbLog("rfbProcessClientNormalMessage: %s", "FixColourMapEntries unsupported\n"); rfbCloseClient(cl); return; /* NOTE: Some clients send us a set of encodings (ie: PointerPos) designed to enable/disable features... * We may want to look into this... * Example: * case rfbEncodingXCursor: * cl->enableCursorShapeUpdates = TRUE; * * Currently: cl->enableCursorShapeUpdates can *never* be turned off... */ case rfbSetEncodings: { if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetEncodingsMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.se.nEncodings = Swap16IfLE(msg.se.nEncodings); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4),sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4)); /* * UltraVNC Client has the ability to adapt to changing network environments * So, let's give it a change to tell us what it wants now! */ if (cl->preferredEncoding!=-1) lastPreferredEncoding = cl->preferredEncoding; /* Reset all flags to defaults (allows us to switch between PointerPos and Server Drawn Cursors) */ cl->preferredEncoding=-1; cl->useCopyRect = FALSE; cl->useNewFBSize = FALSE; cl->useExtDesktopSize = FALSE; cl->cursorWasChanged = FALSE; cl->useRichCursorEncoding = FALSE; cl->enableCursorPosUpdates = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableLastRectEncoding = FALSE; cl->enableKeyboardLedState = FALSE; cl->enableSupportedMessages = FALSE; cl->enableSupportedEncodings = FALSE; cl->enableServerIdentity = FALSE; #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) cl->tightQualityLevel = -1; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP; cl->turboQualityLevel = -1; #endif #endif for (i = 0; i < msg.se.nEncodings; i++) { if ((n = rfbReadExact(cl, (char *)&enc, 4)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } enc = Swap32IfLE(enc); switch (enc) { case rfbEncodingCopyRect: cl->useCopyRect = TRUE; break; case rfbEncodingRaw: case rfbEncodingRRE: case rfbEncodingCoRRE: case rfbEncodingHextile: case rfbEncodingUltra: #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: case rfbEncodingZRLE: case rfbEncodingZYWRLE: #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG case rfbEncodingTightPng: #endif /* The first supported encoding is the 'preferred' encoding */ if (cl->preferredEncoding == -1) cl->preferredEncoding = enc; break; case rfbEncodingXCursor: if(!cl->screen->dontConvertRichCursorToXCursor) { rfbLog("Enabling X-style cursor updates for client %s\n", cl->host); /* if cursor was drawn, hide the cursor */ if(!cl->enableCursorShapeUpdates) rfbRedrawAfterHideCursor(cl,NULL); cl->enableCursorShapeUpdates = TRUE; cl->cursorWasChanged = TRUE; } break; case rfbEncodingRichCursor: rfbLog("Enabling full-color cursor updates for client %s\n", cl->host); /* if cursor was drawn, hide the cursor */ if(!cl->enableCursorShapeUpdates) rfbRedrawAfterHideCursor(cl,NULL); cl->enableCursorShapeUpdates = TRUE; cl->useRichCursorEncoding = TRUE; cl->cursorWasChanged = TRUE; break; case rfbEncodingPointerPos: if (!cl->enableCursorPosUpdates) { rfbLog("Enabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = TRUE; cl->cursorWasMoved = TRUE; } break; case rfbEncodingLastRect: if (!cl->enableLastRectEncoding) { rfbLog("Enabling LastRect protocol extension for client " "%s\n", cl->host); cl->enableLastRectEncoding = TRUE; } break; case rfbEncodingNewFBSize: if (!cl->useNewFBSize) { rfbLog("Enabling NewFBSize protocol extension for client " "%s\n", cl->host); cl->useNewFBSize = TRUE; } break; case rfbEncodingExtDesktopSize: if (!cl->useExtDesktopSize) { rfbLog("Enabling ExtDesktopSize protocol extension for client " "%s\n", cl->host); cl->useExtDesktopSize = TRUE; cl->useNewFBSize = TRUE; } break; case rfbEncodingKeyboardLedState: if (!cl->enableKeyboardLedState) { rfbLog("Enabling KeyboardLedState protocol extension for client " "%s\n", cl->host); cl->enableKeyboardLedState = TRUE; } break; case rfbEncodingSupportedMessages: if (!cl->enableSupportedMessages) { rfbLog("Enabling SupportedMessages protocol extension for client " "%s\n", cl->host); cl->enableSupportedMessages = TRUE; } break; case rfbEncodingSupportedEncodings: if (!cl->enableSupportedEncodings) { rfbLog("Enabling SupportedEncodings protocol extension for client " "%s\n", cl->host); cl->enableSupportedEncodings = TRUE; } break; case rfbEncodingServerIdentity: if (!cl->enableServerIdentity) { rfbLog("Enabling ServerIdentity protocol extension for client " "%s\n", cl->host); cl->enableServerIdentity = TRUE; } break; case rfbEncodingXvp: if (cl->screen->xvpHook) { rfbLog("Enabling Xvp protocol extension for client " "%s\n", cl->host); if (!rfbSendXvp(cl, 1, rfbXvp_Init)) { rfbCloseClient(cl); return; } } break; default: #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) if ( enc >= (uint32_t)rfbEncodingCompressLevel0 && enc <= (uint32_t)rfbEncodingCompressLevel9 ) { cl->zlibCompressLevel = enc & 0x0F; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = enc & 0x0F; rfbLog("Using compression level %d for client %s\n", cl->tightCompressLevel, cl->host); #endif } else if ( enc >= (uint32_t)rfbEncodingQualityLevel0 && enc <= (uint32_t)rfbEncodingQualityLevel9 ) { cl->tightQualityLevel = enc & 0x0F; rfbLog("Using image quality level %d for client %s\n", cl->tightQualityLevel, cl->host); #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->turboQualityLevel = tight2turbo_qual[enc & 0x0F]; cl->turboSubsampLevel = tight2turbo_subsamp[enc & 0x0F]; rfbLog("Using JPEG subsampling %d, Q%d for client %s\n", cl->turboSubsampLevel, cl->turboQualityLevel, cl->host); } else if ( enc >= (uint32_t)rfbEncodingFineQualityLevel0 + 1 && enc <= (uint32_t)rfbEncodingFineQualityLevel100 ) { cl->turboQualityLevel = enc & 0xFF; rfbLog("Using fine quality level %d for client %s\n", cl->turboQualityLevel, cl->host); } else if ( enc >= (uint32_t)rfbEncodingSubsamp1X && enc <= (uint32_t)rfbEncodingSubsampGray ) { cl->turboSubsampLevel = enc & 0xFF; rfbLog("Using subsampling level %d for client %s\n", cl->turboSubsampLevel, cl->host); #endif } else #endif { rfbExtensionData* e; for(e = cl->extensions; e;) { rfbExtensionData* next = e->next; if(e->extension->enablePseudoEncoding && e->extension->enablePseudoEncoding(cl, &e->data, (int)enc)) /* ext handles this encoding */ break; e = next; } if(e == NULL) { rfbBool handled = FALSE; /* if the pseudo encoding is not handled by the enabled extensions, search through all extensions. */ rfbProtocolExtension* e; for(e = rfbGetExtensionIterator(); e;) { int* encs = e->pseudoEncodings; while(encs && *encs!=0) { if(*encs==(int)enc) { void* data = NULL; if(!e->enablePseudoEncoding(cl, &data, (int)enc)) { rfbLog("Installed extension pretends to handle pseudo encoding 0x%x, but does not!\n",(int)enc); } else { rfbEnableExtension(cl, e, data); handled = TRUE; e = NULL; break; } } encs++; } if(e) e = e->next; } rfbReleaseExtensionIterator(); if(!handled) rfbLog("rfbProcessClientNormalMessage: " "ignoring unsupported encoding type %s\n", encodingName(enc,encBuf,sizeof(encBuf))); } } } } if (cl->preferredEncoding == -1) { if (lastPreferredEncoding==-1) { cl->preferredEncoding = rfbEncodingRaw; rfbLog("Defaulting to %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } else { cl->preferredEncoding = lastPreferredEncoding; rfbLog("Sticking with %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } } else { if (lastPreferredEncoding==-1) { rfbLog("Using %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } else { rfbLog("Switching from %s to %s Encoding for client %s\n", encodingName(lastPreferredEncoding,encBuf2,sizeof(encBuf2)), encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)), cl->host); } } if (cl->enableCursorPosUpdates && !cl->enableCursorShapeUpdates) { rfbLog("Disabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = FALSE; } return; } case rfbFramebufferUpdateRequest: { sraRegionPtr tmpRegion; if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFramebufferUpdateRequestMsg-1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbFramebufferUpdateRequestMsg,sz_rfbFramebufferUpdateRequestMsg); /* The values come in based on the scaled screen, we need to convert them to * values based on the main screen's coordinate system */ if(!rectSwapIfLEAndClip(&msg.fur.x,&msg.fur.y,&msg.fur.w,&msg.fur.h,cl)) { rfbLog("Warning, ignoring rfbFramebufferUpdateRequest: %dXx%dY-%dWx%dH\n",msg.fur.x, msg.fur.y, msg.fur.w, msg.fur.h); return; } if (cl->clientFramebufferUpdateRequestHook) cl->clientFramebufferUpdateRequestHook(cl, &msg.fur); tmpRegion = sraRgnCreateRect(msg.fur.x, msg.fur.y, msg.fur.x+msg.fur.w, msg.fur.y+msg.fur.h); LOCK(cl->updateMutex); sraRgnOr(cl->requestedRegion,tmpRegion); if (!cl->readyForSetColourMapEntries) { /* client hasn't sent a SetPixelFormat so is using server's */ cl->readyForSetColourMapEntries = TRUE; if (!cl->format.trueColour) { if (!rfbSetClientColourMap(cl, 0, 0)) { sraRgnDestroy(tmpRegion); TSIGNAL(cl->updateCond); UNLOCK(cl->updateMutex); return; } } } if (!msg.fur.incremental) { sraRgnOr(cl->modifiedRegion,tmpRegion); sraRgnSubtract(cl->copyRegion,tmpRegion); if (cl->useExtDesktopSize) cl->newFBSizePending = TRUE; } TSIGNAL(cl->updateCond); UNLOCK(cl->updateMutex); sraRgnDestroy(tmpRegion); return; } case rfbKeyEvent: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbKeyEventMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbKeyEventMsg, sz_rfbKeyEventMsg); if(!cl->viewOnly) { cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl); } return; case rfbPointerEvent: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbPointerEventMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbPointerEventMsg, sz_rfbPointerEventMsg); if (cl->screen->pointerClient && cl->screen->pointerClient != cl) return; if (msg.pe.buttonMask == 0) cl->screen->pointerClient = NULL; else cl->screen->pointerClient = cl; if(!cl->viewOnly) { if (msg.pe.buttonMask != cl->lastPtrButtons || cl->screen->deferPtrUpdateTime == 0) { cl->screen->ptrAddEvent(msg.pe.buttonMask, ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)), ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)), cl); cl->lastPtrButtons = msg.pe.buttonMask; } else { cl->lastPtrX = ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)); cl->lastPtrY = ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)); cl->lastPtrButtons = msg.pe.buttonMask; } } return; case rfbFileTransfer: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFileTransferMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.ft.size = Swap32IfLE(msg.ft.size); msg.ft.length = Swap32IfLE(msg.ft.length); /* record statistics in rfbProcessFileTransfer as length is filled with garbage when it is not valid */ rfbProcessFileTransfer(cl, msg.ft.contentType, msg.ft.contentParam, msg.ft.size, msg.ft.length); return; case rfbSetSW: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetSWMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.sw.x = Swap16IfLE(msg.sw.x); msg.sw.y = Swap16IfLE(msg.sw.y); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetSWMsg, sz_rfbSetSWMsg); /* msg.sw.status is not initialized in the ultraVNC viewer and contains random numbers (why???) */ rfbLog("Received a rfbSetSingleWindow(%d x, %d y)\n", msg.sw.x, msg.sw.y); if (cl->screen->setSingleWindow!=NULL) cl->screen->setSingleWindow(cl, msg.sw.x, msg.sw.y); return; case rfbSetServerInput: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetServerInputMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetServerInputMsg, sz_rfbSetServerInputMsg); /* msg.sim.pad is not initialized in the ultraVNC viewer and contains random numbers (why???) */ /* msg.sim.pad = Swap16IfLE(msg.sim.pad); */ rfbLog("Received a rfbSetServerInput(%d status)\n", msg.sim.status); if (cl->screen->setServerInput!=NULL) cl->screen->setServerInput(cl, msg.sim.status); return; case rfbTextChat: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbTextChatMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.tc.pad2 = Swap16IfLE(msg.tc.pad2); msg.tc.length = Swap32IfLE(msg.tc.length); switch (msg.tc.length) { case rfbTextChatOpen: case rfbTextChatClose: case rfbTextChatFinished: /* commands do not have text following */ /* Why couldn't they have used the pad byte??? */ str=NULL; rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg, sz_rfbTextChatMsg); break; default: if ((msg.tc.length>0) && (msg.tc.length<rfbTextMaxSize)) { str = (char *)malloc(msg.tc.length); if (str==NULL) { rfbLog("Unable to malloc %d bytes for a TextChat Message\n", msg.tc.length); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, str, msg.tc.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg+msg.tc.length, sz_rfbTextChatMsg+msg.tc.length); } else { /* This should never happen */ rfbLog("client sent us a Text Message that is too big %d>%d\n", msg.tc.length, rfbTextMaxSize); rfbCloseClient(cl); return; } } /* Note: length can be commands: rfbTextChatOpen, rfbTextChatClose, and rfbTextChatFinished * at which point, the str is NULL (as it is not sent) */ if (cl->screen->setTextChat!=NULL) cl->screen->setTextChat(cl, msg.tc.length, str); free(str); return; case rfbClientCutText: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbClientCutTextMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.cct.length = Swap32IfLE(msg.cct.length); /* uint32_t input is passed to malloc()'s size_t argument, * to rfbReadExact()'s int argument, to rfbStatRecordMessageRcvd()'s int * argument increased of sz_rfbClientCutTextMsg, and to setXCutText()'s int * argument. Here we impose a limit of 1 MB so that the value fits * into all of the types to prevent from misinterpretation and thus * from accessing uninitialized memory (CVE-2018-7225) and also to * prevent from a denial-of-service by allocating too much memory in * the server. */ if (msg.cct.length > 1<<20) { rfbLog("rfbClientCutText: too big cut text length requested: %u B > 1 MB\n", (unsigned int)msg.cct.length); rfbCloseClient(cl); return; } /* Allow zero-length client cut text. */ str = (char *)calloc(msg.cct.length ? msg.cct.length : 1, 1); if (str == NULL) { rfbLogPerror("rfbProcessClientNormalMessage: not enough memory"); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, str, msg.cct.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbClientCutTextMsg+msg.cct.length, sz_rfbClientCutTextMsg+msg.cct.length); if(!cl->viewOnly) { cl->screen->setXCutText(str, msg.cct.length, cl); } free(str); return; case rfbPalmVNCSetScaleFactor: cl->PalmVNC = TRUE; if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetScaleMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.ssc.scale == 0) { rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg); rfbLog("rfbSetScale(%d)\n", msg.ssc.scale); rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale); rfbSendNewScaleSize(cl); return; case rfbSetScale: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetScaleMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.ssc.scale == 0) { rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg); rfbLog("rfbSetScale(%d)\n", msg.ssc.scale); rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale); rfbSendNewScaleSize(cl); return; case rfbXvp: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbXvpMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbXvpMsg, sz_rfbXvpMsg); /* only version when is defined, so echo back a fail */ if(msg.xvp.version != 1) { rfbSendXvp(cl, msg.xvp.version, rfbXvp_Fail); } else { /* if the hook exists and fails, send a fail msg */ if(cl->screen->xvpHook && !cl->screen->xvpHook(cl, msg.xvp.version, msg.xvp.code)) rfbSendXvp(cl, 1, rfbXvp_Fail); } return; case rfbSetDesktopSize: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetDesktopSizeMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.sdm.numberOfScreens == 0) { rfbLog("Ignoring setDesktopSize message from client that defines zero screens\n"); return; } extDesktopScreens = (rfbExtDesktopScreen *) malloc(msg.sdm.numberOfScreens * sz_rfbExtDesktopScreen); if (extDesktopScreens == NULL) { rfbLogPerror("rfbProcessClientNormalMessage: not enough memory"); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, ((char *)extDesktopScreens), msg.sdm.numberOfScreens * sz_rfbExtDesktopScreen)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(extDesktopScreens); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetDesktopSizeMsg + msg.sdm.numberOfScreens * sz_rfbExtDesktopScreen, sz_rfbSetDesktopSizeMsg + msg.sdm.numberOfScreens * sz_rfbExtDesktopScreen); for (i=0; i < msg.sdm.numberOfScreens; i++) { extDesktopScreens[i].id = Swap32IfLE(extDesktopScreens[i].id); extDesktopScreens[i].x = Swap16IfLE(extDesktopScreens[i].x); extDesktopScreens[i].y = Swap16IfLE(extDesktopScreens[i].y); extDesktopScreens[i].width = Swap16IfLE(extDesktopScreens[i].width); extDesktopScreens[i].height = Swap16IfLE(extDesktopScreens[i].height); extDesktopScreens[i].flags = Swap32IfLE(extDesktopScreens[i].flags); } msg.sdm.width = Swap16IfLE(msg.sdm.width); msg.sdm.height = Swap16IfLE(msg.sdm.height); rfbLog("Client requested resolution change to (%dx%d)\n", msg.sdm.width, msg.sdm.height); cl->requestedDesktopSizeChange = rfbExtDesktopSize_ClientRequestedChange; cl->lastDesktopSizeChangeError = cl->screen->setDesktopSizeHook(msg.sdm.width, msg.sdm.height, msg.sdm.numberOfScreens, extDesktopScreens, cl); if (cl->lastDesktopSizeChangeError == 0) { /* Let other clients know it was this client that requested the change */ iterator = rfbGetClientIterator(cl->screen); while ((clp = rfbClientIteratorNext(iterator)) != NULL) { LOCK(clp->updateMutex); if (clp != cl) clp->requestedDesktopSizeChange = rfbExtDesktopSize_OtherClientRequestedChange; UNLOCK(clp->updateMutex); } } else { /* Force ExtendedDesktopSize message to be sent with result code in case of error. (In case of success, it is delayed until the new framebuffer is created) */ cl->newFBSizePending = TRUE; } free(extDesktopScreens); return; default: { rfbExtensionData *e,*next; for(e=cl->extensions; e;) { next = e->next; if(e->extension->handleMessage && e->extension->handleMessage(cl, e->data, &msg)) { rfbStatRecordMessageRcvd(cl, msg.type, 0, 0); /* Extension should handle this */ return; } e = next; } rfbLog("rfbProcessClientNormalMessage: unknown message type %d\n", msg.type); rfbLog(" ... closing connection\n"); rfbCloseClient(cl); return; } } } /* * rfbSendFramebufferUpdate - send the currently pending framebuffer update to * the RFB client. * givenUpdateRegion is not changed. */ rfbBool rfbSendFramebufferUpdate(rfbClientPtr cl, sraRegionPtr givenUpdateRegion) { sraRectangleIterator* i=NULL; sraRect rect; int nUpdateRegionRects; rfbFramebufferUpdateMsg *fu = (rfbFramebufferUpdateMsg *)cl->updateBuf; sraRegionPtr updateRegion,updateCopyRegion,tmpRegion; int dx, dy; rfbBool sendCursorShape = FALSE; rfbBool sendCursorPos = FALSE; rfbBool sendKeyboardLedState = FALSE; rfbBool sendSupportedMessages = FALSE; rfbBool sendSupportedEncodings = FALSE; rfbBool sendServerIdentity = FALSE; rfbBool result = TRUE; if(cl->screen->displayHook) cl->screen->displayHook(cl); /* * If framebuffer size was changed and the client supports NewFBSize * encoding, just send NewFBSize marker and return. */ if (cl->useNewFBSize && cl->newFBSizePending) { LOCK(cl->updateMutex); cl->newFBSizePending = FALSE; UNLOCK(cl->updateMutex); fu->type = rfbFramebufferUpdate; fu->nRects = Swap16IfLE(1); cl->ublen = sz_rfbFramebufferUpdateMsg; if (cl->useExtDesktopSize) { if (!rfbSendExtDesktopSize(cl, cl->scaledScreen->width, cl->scaledScreen->height)) { if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, FALSE); return FALSE; } } else if (!rfbSendNewFBSize(cl, cl->scaledScreen->width, cl->scaledScreen->height)) { if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, FALSE); return FALSE; } result = rfbSendUpdateBuf(cl); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, result); return result; } /* * If this client understands cursor shape updates, cursor should be * removed from the framebuffer. Otherwise, make sure it's put up. */ if (cl->enableCursorShapeUpdates) { if (cl->cursorWasChanged && cl->readyForSetColourMapEntries) sendCursorShape = TRUE; } /* * Do we plan to send cursor position update? */ if (cl->enableCursorPosUpdates && cl->cursorWasMoved) sendCursorPos = TRUE; /* * Do we plan to send a keyboard state update? */ if ((cl->enableKeyboardLedState) && (cl->screen->getKeyboardLedStateHook!=NULL)) { int x; x=cl->screen->getKeyboardLedStateHook(cl->screen); if (x!=cl->lastKeyboardLedState) { sendKeyboardLedState = TRUE; cl->lastKeyboardLedState=x; } } /* * Do we plan to send a rfbEncodingSupportedMessages? */ if (cl->enableSupportedMessages) { sendSupportedMessages = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableSupportedMessages = FALSE; } /* * Do we plan to send a rfbEncodingSupportedEncodings? */ if (cl->enableSupportedEncodings) { sendSupportedEncodings = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableSupportedEncodings = FALSE; } /* * Do we plan to send a rfbEncodingServerIdentity? */ if (cl->enableServerIdentity) { sendServerIdentity = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableServerIdentity = FALSE; } LOCK(cl->updateMutex); /* * The modifiedRegion may overlap the destination copyRegion. We remove * any overlapping bits from the copyRegion (since they'd only be * overwritten anyway). */ sraRgnSubtract(cl->copyRegion,cl->modifiedRegion); /* * The client is interested in the region requestedRegion. The region * which should be updated now is the intersection of requestedRegion * and the union of modifiedRegion and copyRegion. If it's empty then * no update is needed. */ updateRegion = sraRgnCreateRgn(givenUpdateRegion); if(cl->screen->progressiveSliceHeight>0) { int height=cl->screen->progressiveSliceHeight, y=cl->progressiveSliceY; sraRegionPtr bbox=sraRgnBBox(updateRegion); sraRect rect; if(sraRgnPopRect(bbox,&rect,0)) { sraRegionPtr slice; if(y<rect.y1 || y>=rect.y2) y=rect.y1; slice=sraRgnCreateRect(0,y,cl->screen->width,y+height); sraRgnAnd(updateRegion,slice); sraRgnDestroy(slice); } sraRgnDestroy(bbox); y+=height; if(y>=cl->screen->height) y=0; cl->progressiveSliceY=y; } sraRgnOr(updateRegion,cl->copyRegion); if(!sraRgnAnd(updateRegion,cl->requestedRegion) && sraRgnEmpty(updateRegion) && (cl->enableCursorShapeUpdates || (cl->cursorX == cl->screen->cursorX && cl->cursorY == cl->screen->cursorY)) && !sendCursorShape && !sendCursorPos && !sendKeyboardLedState && !sendSupportedMessages && !sendSupportedEncodings && !sendServerIdentity) { sraRgnDestroy(updateRegion); UNLOCK(cl->updateMutex); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, TRUE); return TRUE; } /* * We assume that the client doesn't have any pixel data outside the * requestedRegion. In other words, both the source and destination of a * copy must lie within requestedRegion. So the region we can send as a * copy is the intersection of the copyRegion with both the requestedRegion * and the requestedRegion translated by the amount of the copy. We set * updateCopyRegion to this. */ updateCopyRegion = sraRgnCreateRgn(cl->copyRegion); sraRgnAnd(updateCopyRegion,cl->requestedRegion); tmpRegion = sraRgnCreateRgn(cl->requestedRegion); sraRgnOffset(tmpRegion,cl->copyDX,cl->copyDY); sraRgnAnd(updateCopyRegion,tmpRegion); sraRgnDestroy(tmpRegion); dx = cl->copyDX; dy = cl->copyDY; /* * Next we remove updateCopyRegion from updateRegion so that updateRegion * is the part of this update which is sent as ordinary pixel data (i.e not * a copy). */ sraRgnSubtract(updateRegion,updateCopyRegion); /* * Finally we leave modifiedRegion to be the remainder (if any) of parts of * the screen which are modified but outside the requestedRegion. We also * empty both the requestedRegion and the copyRegion - note that we never * carry over a copyRegion for a future update. */ sraRgnOr(cl->modifiedRegion,cl->copyRegion); sraRgnSubtract(cl->modifiedRegion,updateRegion); sraRgnSubtract(cl->modifiedRegion,updateCopyRegion); sraRgnMakeEmpty(cl->requestedRegion); sraRgnMakeEmpty(cl->copyRegion); cl->copyDX = 0; cl->copyDY = 0; UNLOCK(cl->updateMutex); if (!cl->enableCursorShapeUpdates) { if(cl->cursorX != cl->screen->cursorX || cl->cursorY != cl->screen->cursorY) { rfbRedrawAfterHideCursor(cl,updateRegion); LOCK(cl->screen->cursorMutex); cl->cursorX = cl->screen->cursorX; cl->cursorY = cl->screen->cursorY; UNLOCK(cl->screen->cursorMutex); rfbRedrawAfterHideCursor(cl,updateRegion); } rfbShowCursor(cl); } /* * Now send the update. */ rfbStatRecordMessageSent(cl, rfbFramebufferUpdate, 0, 0); if (cl->preferredEncoding == rfbEncodingCoRRE) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int rectsPerRow, rows; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); rectsPerRow = (w-1)/cl->correMaxWidth+1; rows = (h-1)/cl->correMaxHeight+1; nUpdateRegionRects += rectsPerRow*rows; } sraRgnReleaseIterator(i); i=NULL; } else if (cl->preferredEncoding == rfbEncodingUltra) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); nUpdateRegionRects += (((h-1) / (ULTRA_MAX_SIZE( w ) / w)) + 1); } sraRgnReleaseIterator(i); i=NULL; #ifdef LIBVNCSERVER_HAVE_LIBZ } else if (cl->preferredEncoding == rfbEncodingZlib) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); nUpdateRegionRects += (((h-1) / (ZLIB_MAX_SIZE( w ) / w)) + 1); } sraRgnReleaseIterator(i); i=NULL; #ifdef LIBVNCSERVER_HAVE_LIBJPEG } else if (cl->preferredEncoding == rfbEncodingTight) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); i=NULL; #endif #endif #if defined(LIBVNCSERVER_HAVE_LIBJPEG) && defined(LIBVNCSERVER_HAVE_LIBPNG) } else if (cl->preferredEncoding == rfbEncodingTightPng) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); i=NULL; #endif } else { nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->type = rfbFramebufferUpdate; if (nUpdateRegionRects != 0xFFFF) { if(cl->screen->maxRectsPerUpdate>0 /* CoRRE splits the screen into smaller squares */ && cl->preferredEncoding != rfbEncodingCoRRE /* Ultra encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingUltra #ifdef LIBVNCSERVER_HAVE_LIBZ /* Zlib encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingZlib #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTight #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTightPng #endif && nUpdateRegionRects>cl->screen->maxRectsPerUpdate) { sraRegion* newUpdateRegion = sraRgnBBox(updateRegion); sraRgnDestroy(updateRegion); updateRegion = newUpdateRegion; nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->nRects = Swap16IfLE((uint16_t)(sraRgnCountRects(updateCopyRegion) + nUpdateRegionRects + !!sendCursorShape + !!sendCursorPos + !!sendKeyboardLedState + !!sendSupportedMessages + !!sendSupportedEncodings + !!sendServerIdentity)); } else { fu->nRects = 0xFFFF; } cl->ublen = sz_rfbFramebufferUpdateMsg; if (sendCursorShape) { cl->cursorWasChanged = FALSE; if (!rfbSendCursorShape(cl)) goto updateFailed; } if (sendCursorPos) { cl->cursorWasMoved = FALSE; if (!rfbSendCursorPos(cl)) goto updateFailed; } if (sendKeyboardLedState) { if (!rfbSendKeyboardLedState(cl)) goto updateFailed; } if (sendSupportedMessages) { if (!rfbSendSupportedMessages(cl)) goto updateFailed; } if (sendSupportedEncodings) { if (!rfbSendSupportedEncodings(cl)) goto updateFailed; } if (sendServerIdentity) { if (!rfbSendServerIdentity(cl)) goto updateFailed; } if (!sraRgnEmpty(updateCopyRegion)) { if (!rfbSendCopyRegion(cl,updateCopyRegion,dx,dy)) goto updateFailed; } for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); switch (cl->preferredEncoding) { case -1: case rfbEncodingRaw: if (!rfbSendRectEncodingRaw(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingRRE: if (!rfbSendRectEncodingRRE(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingCoRRE: if (!rfbSendRectEncodingCoRRE(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingHextile: if (!rfbSendRectEncodingHextile(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingUltra: if (!rfbSendRectEncodingUltra(cl, x, y, w, h)) goto updateFailed; break; #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: if (!rfbSendRectEncodingZlib(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingZRLE: case rfbEncodingZYWRLE: if (!rfbSendRectEncodingZRLE(cl, x, y, w, h)) goto updateFailed; break; #endif #if defined(LIBVNCSERVER_HAVE_LIBJPEG) && (defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)) case rfbEncodingTight: if (!rfbSendRectEncodingTight(cl, x, y, w, h)) goto updateFailed; break; #ifdef LIBVNCSERVER_HAVE_LIBPNG case rfbEncodingTightPng: if (!rfbSendRectEncodingTightPng(cl, x, y, w, h)) goto updateFailed; break; #endif #endif } } if (i) { sraRgnReleaseIterator(i); i = NULL; } if ( nUpdateRegionRects == 0xFFFF && !rfbSendLastRectMarker(cl) ) goto updateFailed; if (!rfbSendUpdateBuf(cl)) { updateFailed: result = FALSE; } if (!cl->enableCursorShapeUpdates) { rfbHideCursor(cl); } if(i) sraRgnReleaseIterator(i); sraRgnDestroy(updateRegion); sraRgnDestroy(updateCopyRegion); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, result); return result; } /* * Send the copy region as a string of CopyRect encoded rectangles. * The only slightly tricky thing is that we should send the messages in * the correct order so that an earlier CopyRect will not corrupt the source * of a later one. */ rfbBool rfbSendCopyRegion(rfbClientPtr cl, sraRegionPtr reg, int dx, int dy) { int x, y, w, h; rfbFramebufferUpdateRectHeader rect; rfbCopyRect cr; sraRectangleIterator* i; sraRect rect1; /* printf("copyrect: "); sraRgnPrint(reg); putchar('\n');fflush(stdout); */ i = sraRgnGetReverseIterator(reg,dx>0,dy>0); /* correct for the scale of the screen */ dx = ScaleX(cl->screen, cl->scaledScreen, dx); dy = ScaleX(cl->screen, cl->scaledScreen, dy); while(sraRgnIteratorNext(i,&rect1)) { x = rect1.x1; y = rect1.y1; w = rect1.x2 - x; h = rect1.y2 - y; /* correct for scaling (if necessary) */ rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "copyrect"); rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingCopyRect); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; cr.srcX = Swap16IfLE(x - dx); cr.srcY = Swap16IfLE(y - dy); memcpy(&cl->updateBuf[cl->ublen], (char *)&cr, sz_rfbCopyRect); cl->ublen += sz_rfbCopyRect; rfbStatRecordEncodingSent(cl, rfbEncodingCopyRect, sz_rfbFramebufferUpdateRectHeader + sz_rfbCopyRect, w * h * (cl->scaledScreen->bitsPerPixel / 8)); } sraRgnReleaseIterator(i); return TRUE; } /* * Send a given rectangle in raw encoding (rfbEncodingRaw). */ rfbBool rfbSendRectEncodingRaw(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; int nlines; int bytesPerLine = w * (cl->format.bitsPerPixel / 8); char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) + (x * (cl->scaledScreen->bitsPerPixel / 8))); /* Flush the buffer to guarantee correct alignment for translateFn(). */ if (cl->ublen > 0) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRaw); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingRaw, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h); nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine; while (TRUE) { if (nlines > h) nlines = h; (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), &cl->format, fbptr, &cl->updateBuf[cl->ublen], cl->scaledScreen->paddedWidthInBytes, w, nlines); cl->ublen += nlines * bytesPerLine; h -= nlines; if (h == 0) /* rect fitted in buffer, do next one */ return TRUE; /* buffer full - flush partial rect and do another nlines */ if (!rfbSendUpdateBuf(cl)) return FALSE; fbptr += (cl->scaledScreen->paddedWidthInBytes * nlines); nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine; if (nlines == 0) { rfbErr("rfbSendRectEncodingRaw: send buffer too small for %d " "bytes per line\n", bytesPerLine); rfbCloseClient(cl); return FALSE; } } } /* * Send an empty rectangle with encoding field set to value of * rfbEncodingLastRect to notify client that this is the last * rectangle in framebuffer update ("LastRect" extension of RFB * protocol). */ rfbBool rfbSendLastRectMarker(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingLastRect); rect.r.x = 0; rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingLastRect, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); return TRUE; } /* * Send NewFBSize pseudo-rectangle. This tells the client to change * its framebuffer size. */ rfbBool rfbSendNewFBSize(rfbClientPtr cl, int w, int h) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } if (cl->PalmVNC==TRUE) rfbLog("Sending rfbEncodingNewFBSize in response to a PalmVNC style framebuffer resize (%dx%d)\n", w, h); else rfbLog("Sending rfbEncodingNewFBSize for resize to (%dx%d)\n", w, h); rect.encoding = Swap32IfLE(rfbEncodingNewFBSize); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingNewFBSize, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); return TRUE; } /* * Send ExtDesktopSize pseudo-rectangle. This message is used: * - to tell the client to change its framebuffer size * - at the start of the session to inform the client we support size changes through setDesktopSize * - in response to setDesktopSize commands to indicate success or failure */ rfbBool rfbSendExtDesktopSize(rfbClientPtr cl, int w, int h) { rfbFramebufferUpdateRectHeader rect; rfbExtDesktopSizeMsg edsHdr; rfbExtDesktopScreen eds; int i; char *logmsg; int numScreens = cl->screen->numberOfExtDesktopScreensHook(cl); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbExtDesktopSizeMsg + sz_rfbExtDesktopScreen * numScreens > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingExtDesktopSize); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.r.x = Swap16IfLE(cl->requestedDesktopSizeChange); rect.r.y = Swap16IfLE(cl->lastDesktopSizeChangeError); logmsg = ""; if (cl->requestedDesktopSizeChange == rfbExtDesktopSize_ClientRequestedChange) { /* our client requested the resize through setDesktopSize */ switch (cl->lastDesktopSizeChangeError) { case rfbExtDesktopSize_Success: logmsg = "resize successful"; break; case rfbExtDesktopSize_ResizeProhibited: logmsg = "resize prohibited"; break; case rfbExtDesktopSize_OutOfResources: logmsg = "resize failed: out of resources"; break; case rfbExtDesktopSize_InvalidScreenLayout: logmsg = "resize failed: invalid screen layout"; break; default: break; } } cl->requestedDesktopSizeChange = 0; cl->lastDesktopSizeChangeError = 0; rfbLog("Sending rfbEncodingExtDesktopSize for size (%dx%d) %s\n", w, h, logmsg); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; edsHdr.numberOfScreens = numScreens; edsHdr.pad[0] = edsHdr.pad[1] = edsHdr.pad[2] = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&edsHdr, sz_rfbExtDesktopSizeMsg); cl->ublen += sz_rfbExtDesktopSizeMsg; for (i=0; i<numScreens; i++) { if (!cl->screen->getExtDesktopScreenHook(i, &eds, cl)) { rfbErr("Error getting ExtendedDesktopSize information for screen #%d\n", i); return FALSE; } eds.id = Swap32IfLE(eds.id); eds.x = Swap16IfLE(eds.x); eds.y = Swap16IfLE(eds.y); eds.width = Swap16IfLE(eds.width); eds.height = Swap16IfLE(eds.height); eds.flags = Swap32IfLE(eds.flags); memcpy(&cl->updateBuf[cl->ublen], (char *)&eds, sz_rfbExtDesktopScreen); cl->ublen += sz_rfbExtDesktopScreen; } rfbStatRecordEncodingSent(cl, rfbEncodingExtDesktopSize, sz_rfbFramebufferUpdateRectHeader + sz_rfbExtDesktopSizeMsg + sz_rfbExtDesktopScreen * numScreens, sz_rfbFramebufferUpdateRectHeader + sz_rfbExtDesktopSizeMsg + sz_rfbExtDesktopScreen * numScreens); return TRUE; } /* * Send the contents of cl->updateBuf. Returns 1 if successful, -1 if * not (errno should be set). */ rfbBool rfbSendUpdateBuf(rfbClientPtr cl) { if(cl->sock<0) return FALSE; if (rfbWriteExact(cl, cl->updateBuf, cl->ublen) < 0) { rfbLogPerror("rfbSendUpdateBuf: write"); rfbCloseClient(cl); return FALSE; } cl->ublen = 0; return TRUE; } /* * rfbSendSetColourMapEntries sends a SetColourMapEntries message to the * client, using values from the currently installed colormap. */ rfbBool rfbSendSetColourMapEntries(rfbClientPtr cl, int firstColour, int nColours) { char buf[sz_rfbSetColourMapEntriesMsg + 256 * 3 * 2]; char *wbuf = buf; rfbSetColourMapEntriesMsg *scme; uint16_t *rgb; rfbColourMap* cm = &cl->screen->colourMap; int i, len; if (nColours > 256) { /* some rare hardware has, e.g., 4096 colors cells: PseudoColor:12 */ wbuf = (char *) malloc(sz_rfbSetColourMapEntriesMsg + nColours * 3 * 2); } scme = (rfbSetColourMapEntriesMsg *)wbuf; rgb = (uint16_t *)(&wbuf[sz_rfbSetColourMapEntriesMsg]); scme->type = rfbSetColourMapEntries; scme->firstColour = Swap16IfLE(firstColour); scme->nColours = Swap16IfLE(nColours); len = sz_rfbSetColourMapEntriesMsg; for (i = 0; i < nColours; i++) { if(i<(int)cm->count) { if(cm->is16) { rgb[i*3] = Swap16IfLE(cm->data.shorts[i*3]); rgb[i*3+1] = Swap16IfLE(cm->data.shorts[i*3+1]); rgb[i*3+2] = Swap16IfLE(cm->data.shorts[i*3+2]); } else { rgb[i*3] = Swap16IfLE((unsigned short)cm->data.bytes[i*3]); rgb[i*3+1] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+1]); rgb[i*3+2] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+2]); } } } len += nColours * 3 * 2; LOCK(cl->sendMutex); if (rfbWriteExact(cl, wbuf, len) < 0) { rfbLogPerror("rfbSendSetColourMapEntries: write"); rfbCloseClient(cl); if (wbuf != buf) free(wbuf); UNLOCK(cl->sendMutex); return FALSE; } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbSetColourMapEntries, len, len); if (wbuf != buf) free(wbuf); return TRUE; } /* * rfbSendBell sends a Bell message to all the clients. */ void rfbSendBell(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i; rfbClientPtr cl; rfbBellMsg b; i = rfbGetClientIterator(rfbScreen); while((cl=rfbClientIteratorNext(i))) { b.type = rfbBell; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&b, sz_rfbBellMsg) < 0) { rfbLogPerror("rfbSendBell: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); } rfbStatRecordMessageSent(cl, rfbBell, sz_rfbBellMsg, sz_rfbBellMsg); rfbReleaseClientIterator(i); } /* * rfbSendServerCutText sends a ServerCutText message to all the clients. */ void rfbSendServerCutText(rfbScreenInfoPtr rfbScreen,char *str, int len) { rfbClientPtr cl; rfbServerCutTextMsg sct; rfbClientIteratorPtr iterator; iterator = rfbGetClientIterator(rfbScreen); while ((cl = rfbClientIteratorNext(iterator)) != NULL) { sct.type = rfbServerCutText; sct.length = Swap32IfLE(len); LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&sct, sz_rfbServerCutTextMsg) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); continue; } if (rfbWriteExact(cl, str, len) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbServerCutText, sz_rfbServerCutTextMsg+len, sz_rfbServerCutTextMsg+len); } rfbReleaseClientIterator(iterator); } /***************************************************************************** * * UDP can be used for keyboard and pointer events when the underlying * network is highly reliable. This is really here to support ORL's * videotile, whose TCP implementation doesn't like sending lots of small * packets (such as 100s of pen readings per second!). */ static unsigned char ptrAcceleration = 50; void rfbNewUDPConnection(rfbScreenInfoPtr rfbScreen, int sock) { if (write(sock, (char*) &ptrAcceleration, 1) < 0) { rfbLogPerror("rfbNewUDPConnection: write"); } } /* * Because UDP is a message based service, we can't read the first byte and * then the rest of the packet separately like we do with TCP. We will always * get a whole packet delivered in one go, so we ask read() for the maximum * number of bytes we can possibly get. */ void rfbProcessUDPInput(rfbScreenInfoPtr rfbScreen) { int n; rfbClientPtr cl=rfbScreen->udpClient; rfbClientToServerMsg msg; if((!cl) || cl->onHold) return; if ((n = read(rfbScreen->udpSock, (char *)&msg, sizeof(msg))) <= 0) { if (n < 0) { rfbLogPerror("rfbProcessUDPInput: read"); } rfbDisconnectUDPSock(rfbScreen); return; } switch (msg.type) { case rfbKeyEvent: if (n != sz_rfbKeyEventMsg) { rfbErr("rfbProcessUDPInput: key event incorrect length\n"); rfbDisconnectUDPSock(rfbScreen); return; } cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl); break; case rfbPointerEvent: if (n != sz_rfbPointerEventMsg) { rfbErr("rfbProcessUDPInput: ptr event incorrect length\n"); rfbDisconnectUDPSock(rfbScreen); return; } cl->screen->ptrAddEvent(msg.pe.buttonMask, Swap16IfLE(msg.pe.x), Swap16IfLE(msg.pe.y), cl); break; default: rfbErr("rfbProcessUDPInput: unknown message type %d\n", msg.type); rfbDisconnectUDPSock(rfbScreen); } }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_1039_0
crossvul-cpp_data_bad_2615_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD CCCC M M % % D D C MM MM % % D D C M M M % % D D C M M % % DDDD CCCC M M % % % % % % Read DICOM Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/constitute.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/module.h" /* Dicom medical image declarations. */ typedef struct _DicomInfo { const unsigned short group, element; const char *vr, *description; } DicomInfo; static const DicomInfo dicom_info[] = { { 0x0000, 0x0000, "UL", "Group Length" }, { 0x0000, 0x0001, "UL", "Command Length to End" }, { 0x0000, 0x0002, "UI", "Affected SOP Class UID" }, { 0x0000, 0x0003, "UI", "Requested SOP Class UID" }, { 0x0000, 0x0010, "LO", "Command Recognition Code" }, { 0x0000, 0x0100, "US", "Command Field" }, { 0x0000, 0x0110, "US", "Message ID" }, { 0x0000, 0x0120, "US", "Message ID Being Responded To" }, { 0x0000, 0x0200, "AE", "Initiator" }, { 0x0000, 0x0300, "AE", "Receiver" }, { 0x0000, 0x0400, "AE", "Find Location" }, { 0x0000, 0x0600, "AE", "Move Destination" }, { 0x0000, 0x0700, "US", "Priority" }, { 0x0000, 0x0800, "US", "Data Set Type" }, { 0x0000, 0x0850, "US", "Number of Matches" }, { 0x0000, 0x0860, "US", "Response Sequence Number" }, { 0x0000, 0x0900, "US", "Status" }, { 0x0000, 0x0901, "AT", "Offending Element" }, { 0x0000, 0x0902, "LO", "Exception Comment" }, { 0x0000, 0x0903, "US", "Exception ID" }, { 0x0000, 0x1000, "UI", "Affected SOP Instance UID" }, { 0x0000, 0x1001, "UI", "Requested SOP Instance UID" }, { 0x0000, 0x1002, "US", "Event Type ID" }, { 0x0000, 0x1005, "AT", "Attribute Identifier List" }, { 0x0000, 0x1008, "US", "Action Type ID" }, { 0x0000, 0x1020, "US", "Number of Remaining Suboperations" }, { 0x0000, 0x1021, "US", "Number of Completed Suboperations" }, { 0x0000, 0x1022, "US", "Number of Failed Suboperations" }, { 0x0000, 0x1023, "US", "Number of Warning Suboperations" }, { 0x0000, 0x1030, "AE", "Move Originator Application Entity Title" }, { 0x0000, 0x1031, "US", "Move Originator Message ID" }, { 0x0000, 0x4000, "LO", "Dialog Receiver" }, { 0x0000, 0x4010, "LO", "Terminal Type" }, { 0x0000, 0x5010, "SH", "Message Set ID" }, { 0x0000, 0x5020, "SH", "End Message Set" }, { 0x0000, 0x5110, "LO", "Display Format" }, { 0x0000, 0x5120, "LO", "Page Position ID" }, { 0x0000, 0x5130, "LO", "Text Format ID" }, { 0x0000, 0x5140, "LO", "Normal Reverse" }, { 0x0000, 0x5150, "LO", "Add Gray Scale" }, { 0x0000, 0x5160, "LO", "Borders" }, { 0x0000, 0x5170, "IS", "Copies" }, { 0x0000, 0x5180, "LO", "OldMagnificationType" }, { 0x0000, 0x5190, "LO", "Erase" }, { 0x0000, 0x51a0, "LO", "Print" }, { 0x0000, 0x51b0, "US", "Overlays" }, { 0x0002, 0x0000, "UL", "Meta Element Group Length" }, { 0x0002, 0x0001, "OB", "File Meta Information Version" }, { 0x0002, 0x0002, "UI", "Media Storage SOP Class UID" }, { 0x0002, 0x0003, "UI", "Media Storage SOP Instance UID" }, { 0x0002, 0x0010, "UI", "Transfer Syntax UID" }, { 0x0002, 0x0012, "UI", "Implementation Class UID" }, { 0x0002, 0x0013, "SH", "Implementation Version Name" }, { 0x0002, 0x0016, "AE", "Source Application Entity Title" }, { 0x0002, 0x0100, "UI", "Private Information Creator UID" }, { 0x0002, 0x0102, "OB", "Private Information" }, { 0x0003, 0x0000, "US", "?" }, { 0x0003, 0x0008, "US", "ISI Command Field" }, { 0x0003, 0x0011, "US", "Attach ID Application Code" }, { 0x0003, 0x0012, "UL", "Attach ID Message Count" }, { 0x0003, 0x0013, "DA", "Attach ID Date" }, { 0x0003, 0x0014, "TM", "Attach ID Time" }, { 0x0003, 0x0020, "US", "Message Type" }, { 0x0003, 0x0030, "DA", "Max Waiting Date" }, { 0x0003, 0x0031, "TM", "Max Waiting Time" }, { 0x0004, 0x0000, "UL", "File Set Group Length" }, { 0x0004, 0x1130, "CS", "File Set ID" }, { 0x0004, 0x1141, "CS", "File Set Descriptor File ID" }, { 0x0004, 0x1142, "CS", "File Set Descriptor File Specific Character Set" }, { 0x0004, 0x1200, "UL", "Root Directory Entity First Directory Record Offset" }, { 0x0004, 0x1202, "UL", "Root Directory Entity Last Directory Record Offset" }, { 0x0004, 0x1212, "US", "File Set Consistency Flag" }, { 0x0004, 0x1220, "SQ", "Directory Record Sequence" }, { 0x0004, 0x1400, "UL", "Next Directory Record Offset" }, { 0x0004, 0x1410, "US", "Record In Use Flag" }, { 0x0004, 0x1420, "UL", "Referenced Lower Level Directory Entity Offset" }, { 0x0004, 0x1430, "CS", "Directory Record Type" }, { 0x0004, 0x1432, "UI", "Private Record UID" }, { 0x0004, 0x1500, "CS", "Referenced File ID" }, { 0x0004, 0x1504, "UL", "MRDR Directory Record Offset" }, { 0x0004, 0x1510, "UI", "Referenced SOP Class UID In File" }, { 0x0004, 0x1511, "UI", "Referenced SOP Instance UID In File" }, { 0x0004, 0x1512, "UI", "Referenced Transfer Syntax UID In File" }, { 0x0004, 0x1600, "UL", "Number of References" }, { 0x0005, 0x0000, "US", "?" }, { 0x0006, 0x0000, "US", "?" }, { 0x0008, 0x0000, "UL", "Identifying Group Length" }, { 0x0008, 0x0001, "UL", "Length to End" }, { 0x0008, 0x0005, "CS", "Specific Character Set" }, { 0x0008, 0x0008, "CS", "Image Type" }, { 0x0008, 0x0010, "LO", "Recognition Code" }, { 0x0008, 0x0012, "DA", "Instance Creation Date" }, { 0x0008, 0x0013, "TM", "Instance Creation Time" }, { 0x0008, 0x0014, "UI", "Instance Creator UID" }, { 0x0008, 0x0016, "UI", "SOP Class UID" }, { 0x0008, 0x0018, "UI", "SOP Instance UID" }, { 0x0008, 0x0020, "DA", "Study Date" }, { 0x0008, 0x0021, "DA", "Series Date" }, { 0x0008, 0x0022, "DA", "Acquisition Date" }, { 0x0008, 0x0023, "DA", "Image Date" }, { 0x0008, 0x0024, "DA", "Overlay Date" }, { 0x0008, 0x0025, "DA", "Curve Date" }, { 0x0008, 0x0030, "TM", "Study Time" }, { 0x0008, 0x0031, "TM", "Series Time" }, { 0x0008, 0x0032, "TM", "Acquisition Time" }, { 0x0008, 0x0033, "TM", "Image Time" }, { 0x0008, 0x0034, "TM", "Overlay Time" }, { 0x0008, 0x0035, "TM", "Curve Time" }, { 0x0008, 0x0040, "xs", "Old Data Set Type" }, { 0x0008, 0x0041, "xs", "Old Data Set Subtype" }, { 0x0008, 0x0042, "CS", "Nuclear Medicine Series Type" }, { 0x0008, 0x0050, "SH", "Accession Number" }, { 0x0008, 0x0052, "CS", "Query/Retrieve Level" }, { 0x0008, 0x0054, "AE", "Retrieve AE Title" }, { 0x0008, 0x0058, "UI", "Failed SOP Instance UID List" }, { 0x0008, 0x0060, "CS", "Modality" }, { 0x0008, 0x0062, "SQ", "Modality Subtype" }, { 0x0008, 0x0064, "CS", "Conversion Type" }, { 0x0008, 0x0068, "CS", "Presentation Intent Type" }, { 0x0008, 0x0070, "LO", "Manufacturer" }, { 0x0008, 0x0080, "LO", "Institution Name" }, { 0x0008, 0x0081, "ST", "Institution Address" }, { 0x0008, 0x0082, "SQ", "Institution Code Sequence" }, { 0x0008, 0x0090, "PN", "Referring Physician's Name" }, { 0x0008, 0x0092, "ST", "Referring Physician's Address" }, { 0x0008, 0x0094, "SH", "Referring Physician's Telephone Numbers" }, { 0x0008, 0x0100, "SH", "Code Value" }, { 0x0008, 0x0102, "SH", "Coding Scheme Designator" }, { 0x0008, 0x0103, "SH", "Coding Scheme Version" }, { 0x0008, 0x0104, "LO", "Code Meaning" }, { 0x0008, 0x0105, "CS", "Mapping Resource" }, { 0x0008, 0x0106, "DT", "Context Group Version" }, { 0x0008, 0x010b, "CS", "Code Set Extension Flag" }, { 0x0008, 0x010c, "UI", "Private Coding Scheme Creator UID" }, { 0x0008, 0x010d, "UI", "Code Set Extension Creator UID" }, { 0x0008, 0x010f, "CS", "Context Identifier" }, { 0x0008, 0x1000, "LT", "Network ID" }, { 0x0008, 0x1010, "SH", "Station Name" }, { 0x0008, 0x1030, "LO", "Study Description" }, { 0x0008, 0x1032, "SQ", "Procedure Code Sequence" }, { 0x0008, 0x103e, "LO", "Series Description" }, { 0x0008, 0x1040, "LO", "Institutional Department Name" }, { 0x0008, 0x1048, "PN", "Physician of Record" }, { 0x0008, 0x1050, "PN", "Performing Physician's Name" }, { 0x0008, 0x1060, "PN", "Name of Physician(s) Reading Study" }, { 0x0008, 0x1070, "PN", "Operator's Name" }, { 0x0008, 0x1080, "LO", "Admitting Diagnosis Description" }, { 0x0008, 0x1084, "SQ", "Admitting Diagnosis Code Sequence" }, { 0x0008, 0x1090, "LO", "Manufacturer's Model Name" }, { 0x0008, 0x1100, "SQ", "Referenced Results Sequence" }, { 0x0008, 0x1110, "SQ", "Referenced Study Sequence" }, { 0x0008, 0x1111, "SQ", "Referenced Study Component Sequence" }, { 0x0008, 0x1115, "SQ", "Referenced Series Sequence" }, { 0x0008, 0x1120, "SQ", "Referenced Patient Sequence" }, { 0x0008, 0x1125, "SQ", "Referenced Visit Sequence" }, { 0x0008, 0x1130, "SQ", "Referenced Overlay Sequence" }, { 0x0008, 0x1140, "SQ", "Referenced Image Sequence" }, { 0x0008, 0x1145, "SQ", "Referenced Curve Sequence" }, { 0x0008, 0x1148, "SQ", "Referenced Previous Waveform" }, { 0x0008, 0x114a, "SQ", "Referenced Simultaneous Waveforms" }, { 0x0008, 0x114c, "SQ", "Referenced Subsequent Waveform" }, { 0x0008, 0x1150, "UI", "Referenced SOP Class UID" }, { 0x0008, 0x1155, "UI", "Referenced SOP Instance UID" }, { 0x0008, 0x1160, "IS", "Referenced Frame Number" }, { 0x0008, 0x1195, "UI", "Transaction UID" }, { 0x0008, 0x1197, "US", "Failure Reason" }, { 0x0008, 0x1198, "SQ", "Failed SOP Sequence" }, { 0x0008, 0x1199, "SQ", "Referenced SOP Sequence" }, { 0x0008, 0x2110, "CS", "Old Lossy Image Compression" }, { 0x0008, 0x2111, "ST", "Derivation Description" }, { 0x0008, 0x2112, "SQ", "Source Image Sequence" }, { 0x0008, 0x2120, "SH", "Stage Name" }, { 0x0008, 0x2122, "IS", "Stage Number" }, { 0x0008, 0x2124, "IS", "Number of Stages" }, { 0x0008, 0x2128, "IS", "View Number" }, { 0x0008, 0x2129, "IS", "Number of Event Timers" }, { 0x0008, 0x212a, "IS", "Number of Views in Stage" }, { 0x0008, 0x2130, "DS", "Event Elapsed Time(s)" }, { 0x0008, 0x2132, "LO", "Event Timer Name(s)" }, { 0x0008, 0x2142, "IS", "Start Trim" }, { 0x0008, 0x2143, "IS", "Stop Trim" }, { 0x0008, 0x2144, "IS", "Recommended Display Frame Rate" }, { 0x0008, 0x2200, "CS", "Transducer Position" }, { 0x0008, 0x2204, "CS", "Transducer Orientation" }, { 0x0008, 0x2208, "CS", "Anatomic Structure" }, { 0x0008, 0x2218, "SQ", "Anatomic Region Sequence" }, { 0x0008, 0x2220, "SQ", "Anatomic Region Modifier Sequence" }, { 0x0008, 0x2228, "SQ", "Primary Anatomic Structure Sequence" }, { 0x0008, 0x2230, "SQ", "Primary Anatomic Structure Modifier Sequence" }, { 0x0008, 0x2240, "SQ", "Transducer Position Sequence" }, { 0x0008, 0x2242, "SQ", "Transducer Position Modifier Sequence" }, { 0x0008, 0x2244, "SQ", "Transducer Orientation Sequence" }, { 0x0008, 0x2246, "SQ", "Transducer Orientation Modifier Sequence" }, { 0x0008, 0x2251, "SQ", "Anatomic Structure Space Or Region Code Sequence" }, { 0x0008, 0x2253, "SQ", "Anatomic Portal Of Entrance Code Sequence" }, { 0x0008, 0x2255, "SQ", "Anatomic Approach Direction Code Sequence" }, { 0x0008, 0x2256, "ST", "Anatomic Perspective Description" }, { 0x0008, 0x2257, "SQ", "Anatomic Perspective Code Sequence" }, { 0x0008, 0x2258, "ST", "Anatomic Location Of Examining Instrument Description" }, { 0x0008, 0x2259, "SQ", "Anatomic Location Of Examining Instrument Code Sequence" }, { 0x0008, 0x225a, "SQ", "Anatomic Structure Space Or Region Modifier Code Sequence" }, { 0x0008, 0x225c, "SQ", "OnAxis Background Anatomic Structure Code Sequence" }, { 0x0008, 0x4000, "LT", "Identifying Comments" }, { 0x0009, 0x0000, "xs", "?" }, { 0x0009, 0x0001, "xs", "?" }, { 0x0009, 0x0002, "xs", "?" }, { 0x0009, 0x0003, "xs", "?" }, { 0x0009, 0x0004, "xs", "?" }, { 0x0009, 0x0005, "UN", "?" }, { 0x0009, 0x0006, "UN", "?" }, { 0x0009, 0x0007, "UN", "?" }, { 0x0009, 0x0008, "xs", "?" }, { 0x0009, 0x0009, "LT", "?" }, { 0x0009, 0x000a, "IS", "?" }, { 0x0009, 0x000b, "IS", "?" }, { 0x0009, 0x000c, "IS", "?" }, { 0x0009, 0x000d, "IS", "?" }, { 0x0009, 0x000e, "IS", "?" }, { 0x0009, 0x000f, "UN", "?" }, { 0x0009, 0x0010, "xs", "?" }, { 0x0009, 0x0011, "xs", "?" }, { 0x0009, 0x0012, "xs", "?" }, { 0x0009, 0x0013, "xs", "?" }, { 0x0009, 0x0014, "xs", "?" }, { 0x0009, 0x0015, "xs", "?" }, { 0x0009, 0x0016, "xs", "?" }, { 0x0009, 0x0017, "LT", "?" }, { 0x0009, 0x0018, "LT", "Data Set Identifier" }, { 0x0009, 0x001a, "US", "?" }, { 0x0009, 0x001e, "UI", "?" }, { 0x0009, 0x0020, "xs", "?" }, { 0x0009, 0x0021, "xs", "?" }, { 0x0009, 0x0022, "SH", "User Orientation" }, { 0x0009, 0x0023, "SL", "Initiation Type" }, { 0x0009, 0x0024, "xs", "?" }, { 0x0009, 0x0025, "xs", "?" }, { 0x0009, 0x0026, "xs", "?" }, { 0x0009, 0x0027, "xs", "?" }, { 0x0009, 0x0029, "xs", "?" }, { 0x0009, 0x002a, "SL", "?" }, { 0x0009, 0x002c, "LO", "Series Comments" }, { 0x0009, 0x002d, "SL", "Track Beat Average" }, { 0x0009, 0x002e, "FD", "Distance Prescribed" }, { 0x0009, 0x002f, "LT", "?" }, { 0x0009, 0x0030, "xs", "?" }, { 0x0009, 0x0031, "xs", "?" }, { 0x0009, 0x0032, "LT", "?" }, { 0x0009, 0x0034, "xs", "?" }, { 0x0009, 0x0035, "SL", "Gantry Locus Type" }, { 0x0009, 0x0037, "SL", "Starting Heart Rate" }, { 0x0009, 0x0038, "xs", "?" }, { 0x0009, 0x0039, "SL", "RR Window Offset" }, { 0x0009, 0x003a, "SL", "Percent Cycle Imaged" }, { 0x0009, 0x003e, "US", "?" }, { 0x0009, 0x003f, "US", "?" }, { 0x0009, 0x0040, "xs", "?" }, { 0x0009, 0x0041, "xs", "?" }, { 0x0009, 0x0042, "xs", "?" }, { 0x0009, 0x0043, "xs", "?" }, { 0x0009, 0x0050, "LT", "?" }, { 0x0009, 0x0051, "xs", "?" }, { 0x0009, 0x0060, "LT", "?" }, { 0x0009, 0x0061, "LT", "Series Unique Identifier" }, { 0x0009, 0x0070, "LT", "?" }, { 0x0009, 0x0080, "LT", "?" }, { 0x0009, 0x0091, "LT", "?" }, { 0x0009, 0x00e2, "LT", "?" }, { 0x0009, 0x00e3, "UI", "Equipment UID" }, { 0x0009, 0x00e6, "SH", "Genesis Version Now" }, { 0x0009, 0x00e7, "UL", "Exam Record Checksum" }, { 0x0009, 0x00e8, "UL", "?" }, { 0x0009, 0x00e9, "SL", "Actual Series Data Time Stamp" }, { 0x0009, 0x00f2, "UN", "?" }, { 0x0009, 0x00f3, "UN", "?" }, { 0x0009, 0x00f4, "LT", "?" }, { 0x0009, 0x00f5, "xs", "?" }, { 0x0009, 0x00f6, "LT", "PDM Data Object Type Extension" }, { 0x0009, 0x00f8, "US", "?" }, { 0x0009, 0x00fb, "IS", "?" }, { 0x0009, 0x1002, "OB", "?" }, { 0x0009, 0x1003, "OB", "?" }, { 0x0009, 0x1010, "UN", "?" }, { 0x0010, 0x0000, "UL", "Patient Group Length" }, { 0x0010, 0x0010, "PN", "Patient's Name" }, { 0x0010, 0x0020, "LO", "Patient's ID" }, { 0x0010, 0x0021, "LO", "Issuer of Patient's ID" }, { 0x0010, 0x0030, "DA", "Patient's Birth Date" }, { 0x0010, 0x0032, "TM", "Patient's Birth Time" }, { 0x0010, 0x0040, "CS", "Patient's Sex" }, { 0x0010, 0x0050, "SQ", "Patient's Insurance Plan Code Sequence" }, { 0x0010, 0x1000, "LO", "Other Patient's ID's" }, { 0x0010, 0x1001, "PN", "Other Patient's Names" }, { 0x0010, 0x1005, "PN", "Patient's Birth Name" }, { 0x0010, 0x1010, "AS", "Patient's Age" }, { 0x0010, 0x1020, "DS", "Patient's Size" }, { 0x0010, 0x1030, "DS", "Patient's Weight" }, { 0x0010, 0x1040, "LO", "Patient's Address" }, { 0x0010, 0x1050, "LT", "Insurance Plan Identification" }, { 0x0010, 0x1060, "PN", "Patient's Mother's Birth Name" }, { 0x0010, 0x1080, "LO", "Military Rank" }, { 0x0010, 0x1081, "LO", "Branch of Service" }, { 0x0010, 0x1090, "LO", "Medical Record Locator" }, { 0x0010, 0x2000, "LO", "Medical Alerts" }, { 0x0010, 0x2110, "LO", "Contrast Allergies" }, { 0x0010, 0x2150, "LO", "Country of Residence" }, { 0x0010, 0x2152, "LO", "Region of Residence" }, { 0x0010, 0x2154, "SH", "Patients Telephone Numbers" }, { 0x0010, 0x2160, "SH", "Ethnic Group" }, { 0x0010, 0x2180, "SH", "Occupation" }, { 0x0010, 0x21a0, "CS", "Smoking Status" }, { 0x0010, 0x21b0, "LT", "Additional Patient History" }, { 0x0010, 0x21c0, "US", "Pregnancy Status" }, { 0x0010, 0x21d0, "DA", "Last Menstrual Date" }, { 0x0010, 0x21f0, "LO", "Patients Religious Preference" }, { 0x0010, 0x4000, "LT", "Patient Comments" }, { 0x0011, 0x0001, "xs", "?" }, { 0x0011, 0x0002, "US", "?" }, { 0x0011, 0x0003, "LT", "Patient UID" }, { 0x0011, 0x0004, "LT", "Patient ID" }, { 0x0011, 0x000a, "xs", "?" }, { 0x0011, 0x000b, "SL", "Effective Series Duration" }, { 0x0011, 0x000c, "SL", "Num Beats" }, { 0x0011, 0x000d, "LO", "Radio Nuclide Name" }, { 0x0011, 0x0010, "xs", "?" }, { 0x0011, 0x0011, "xs", "?" }, { 0x0011, 0x0012, "LO", "Dataset Name" }, { 0x0011, 0x0013, "LO", "Dataset Type" }, { 0x0011, 0x0015, "xs", "?" }, { 0x0011, 0x0016, "SL", "Energy Number" }, { 0x0011, 0x0017, "SL", "RR Interval Window Number" }, { 0x0011, 0x0018, "SL", "MG Bin Number" }, { 0x0011, 0x0019, "FD", "Radius Of Rotation" }, { 0x0011, 0x001a, "SL", "Detector Count Zone" }, { 0x0011, 0x001b, "SL", "Num Energy Windows" }, { 0x0011, 0x001c, "SL", "Energy Offset" }, { 0x0011, 0x001d, "SL", "Energy Range" }, { 0x0011, 0x001f, "SL", "Image Orientation" }, { 0x0011, 0x0020, "xs", "?" }, { 0x0011, 0x0021, "xs", "?" }, { 0x0011, 0x0022, "xs", "?" }, { 0x0011, 0x0023, "xs", "?" }, { 0x0011, 0x0024, "SL", "FOV Mask Y Cutoff Angle" }, { 0x0011, 0x0025, "xs", "?" }, { 0x0011, 0x0026, "SL", "Table Orientation" }, { 0x0011, 0x0027, "SL", "ROI Top Left" }, { 0x0011, 0x0028, "SL", "ROI Bottom Right" }, { 0x0011, 0x0030, "xs", "?" }, { 0x0011, 0x0031, "xs", "?" }, { 0x0011, 0x0032, "UN", "?" }, { 0x0011, 0x0033, "LO", "Energy Correct Name" }, { 0x0011, 0x0034, "LO", "Spatial Correct Name" }, { 0x0011, 0x0035, "xs", "?" }, { 0x0011, 0x0036, "LO", "Uniformity Correct Name" }, { 0x0011, 0x0037, "LO", "Acquisition Specific Correct Name" }, { 0x0011, 0x0038, "SL", "Byte Order" }, { 0x0011, 0x003a, "SL", "Picture Format" }, { 0x0011, 0x003b, "FD", "Pixel Scale" }, { 0x0011, 0x003c, "FD", "Pixel Offset" }, { 0x0011, 0x003e, "SL", "FOV Shape" }, { 0x0011, 0x003f, "SL", "Dataset Flags" }, { 0x0011, 0x0040, "xs", "?" }, { 0x0011, 0x0041, "LT", "Medical Alerts" }, { 0x0011, 0x0042, "LT", "Contrast Allergies" }, { 0x0011, 0x0044, "FD", "Threshold Center" }, { 0x0011, 0x0045, "FD", "Threshold Width" }, { 0x0011, 0x0046, "SL", "Interpolation Type" }, { 0x0011, 0x0055, "FD", "Period" }, { 0x0011, 0x0056, "FD", "ElapsedTime" }, { 0x0011, 0x00a1, "DA", "Patient Registration Date" }, { 0x0011, 0x00a2, "TM", "Patient Registration Time" }, { 0x0011, 0x00b0, "LT", "Patient Last Name" }, { 0x0011, 0x00b2, "LT", "Patient First Name" }, { 0x0011, 0x00b4, "LT", "Patient Hospital Status" }, { 0x0011, 0x00bc, "TM", "Current Location Time" }, { 0x0011, 0x00c0, "LT", "Patient Insurance Status" }, { 0x0011, 0x00d0, "LT", "Patient Billing Type" }, { 0x0011, 0x00d2, "LT", "Patient Billing Address" }, { 0x0013, 0x0000, "LT", "Modifying Physician" }, { 0x0013, 0x0010, "xs", "?" }, { 0x0013, 0x0011, "SL", "?" }, { 0x0013, 0x0012, "xs", "?" }, { 0x0013, 0x0016, "SL", "AutoTrack Peak" }, { 0x0013, 0x0017, "SL", "AutoTrack Width" }, { 0x0013, 0x0018, "FD", "Transmission Scan Time" }, { 0x0013, 0x0019, "FD", "Transmission Mask Width" }, { 0x0013, 0x001a, "FD", "Copper Attenuator Thickness" }, { 0x0013, 0x001c, "FD", "?" }, { 0x0013, 0x001d, "FD", "?" }, { 0x0013, 0x001e, "FD", "Tomo View Offset" }, { 0x0013, 0x0020, "LT", "Patient Name" }, { 0x0013, 0x0022, "LT", "Patient Id" }, { 0x0013, 0x0026, "LT", "Study Comments" }, { 0x0013, 0x0030, "DA", "Patient Birthdate" }, { 0x0013, 0x0031, "DS", "Patient Weight" }, { 0x0013, 0x0032, "LT", "Patients Maiden Name" }, { 0x0013, 0x0033, "LT", "Referring Physician" }, { 0x0013, 0x0034, "LT", "Admitting Diagnosis" }, { 0x0013, 0x0035, "LT", "Patient Sex" }, { 0x0013, 0x0040, "LT", "Procedure Description" }, { 0x0013, 0x0042, "LT", "Patient Rest Direction" }, { 0x0013, 0x0044, "LT", "Patient Position" }, { 0x0013, 0x0046, "LT", "View Direction" }, { 0x0015, 0x0001, "DS", "Stenosis Calibration Ratio" }, { 0x0015, 0x0002, "DS", "Stenosis Magnification" }, { 0x0015, 0x0003, "DS", "Cardiac Calibration Ratio" }, { 0x0018, 0x0000, "UL", "Acquisition Group Length" }, { 0x0018, 0x0010, "LO", "Contrast/Bolus Agent" }, { 0x0018, 0x0012, "SQ", "Contrast/Bolus Agent Sequence" }, { 0x0018, 0x0014, "SQ", "Contrast/Bolus Administration Route Sequence" }, { 0x0018, 0x0015, "CS", "Body Part Examined" }, { 0x0018, 0x0020, "CS", "Scanning Sequence" }, { 0x0018, 0x0021, "CS", "Sequence Variant" }, { 0x0018, 0x0022, "CS", "Scan Options" }, { 0x0018, 0x0023, "CS", "MR Acquisition Type" }, { 0x0018, 0x0024, "SH", "Sequence Name" }, { 0x0018, 0x0025, "CS", "Angio Flag" }, { 0x0018, 0x0026, "SQ", "Intervention Drug Information Sequence" }, { 0x0018, 0x0027, "TM", "Intervention Drug Stop Time" }, { 0x0018, 0x0028, "DS", "Intervention Drug Dose" }, { 0x0018, 0x0029, "SQ", "Intervention Drug Code Sequence" }, { 0x0018, 0x002a, "SQ", "Additional Drug Sequence" }, { 0x0018, 0x0030, "LO", "Radionuclide" }, { 0x0018, 0x0031, "LO", "Radiopharmaceutical" }, { 0x0018, 0x0032, "DS", "Energy Window Centerline" }, { 0x0018, 0x0033, "DS", "Energy Window Total Width" }, { 0x0018, 0x0034, "LO", "Intervention Drug Name" }, { 0x0018, 0x0035, "TM", "Intervention Drug Start Time" }, { 0x0018, 0x0036, "SQ", "Intervention Therapy Sequence" }, { 0x0018, 0x0037, "CS", "Therapy Type" }, { 0x0018, 0x0038, "CS", "Intervention Status" }, { 0x0018, 0x0039, "CS", "Therapy Description" }, { 0x0018, 0x0040, "IS", "Cine Rate" }, { 0x0018, 0x0050, "DS", "Slice Thickness" }, { 0x0018, 0x0060, "DS", "KVP" }, { 0x0018, 0x0070, "IS", "Counts Accumulated" }, { 0x0018, 0x0071, "CS", "Acquisition Termination Condition" }, { 0x0018, 0x0072, "DS", "Effective Series Duration" }, { 0x0018, 0x0073, "CS", "Acquisition Start Condition" }, { 0x0018, 0x0074, "IS", "Acquisition Start Condition Data" }, { 0x0018, 0x0075, "IS", "Acquisition Termination Condition Data" }, { 0x0018, 0x0080, "DS", "Repetition Time" }, { 0x0018, 0x0081, "DS", "Echo Time" }, { 0x0018, 0x0082, "DS", "Inversion Time" }, { 0x0018, 0x0083, "DS", "Number of Averages" }, { 0x0018, 0x0084, "DS", "Imaging Frequency" }, { 0x0018, 0x0085, "SH", "Imaged Nucleus" }, { 0x0018, 0x0086, "IS", "Echo Number(s)" }, { 0x0018, 0x0087, "DS", "Magnetic Field Strength" }, { 0x0018, 0x0088, "DS", "Spacing Between Slices" }, { 0x0018, 0x0089, "IS", "Number of Phase Encoding Steps" }, { 0x0018, 0x0090, "DS", "Data Collection Diameter" }, { 0x0018, 0x0091, "IS", "Echo Train Length" }, { 0x0018, 0x0093, "DS", "Percent Sampling" }, { 0x0018, 0x0094, "DS", "Percent Phase Field of View" }, { 0x0018, 0x0095, "DS", "Pixel Bandwidth" }, { 0x0018, 0x1000, "LO", "Device Serial Number" }, { 0x0018, 0x1004, "LO", "Plate ID" }, { 0x0018, 0x1010, "LO", "Secondary Capture Device ID" }, { 0x0018, 0x1012, "DA", "Date of Secondary Capture" }, { 0x0018, 0x1014, "TM", "Time of Secondary Capture" }, { 0x0018, 0x1016, "LO", "Secondary Capture Device Manufacturer" }, { 0x0018, 0x1018, "LO", "Secondary Capture Device Manufacturer Model Name" }, { 0x0018, 0x1019, "LO", "Secondary Capture Device Software Version(s)" }, { 0x0018, 0x1020, "LO", "Software Version(s)" }, { 0x0018, 0x1022, "SH", "Video Image Format Acquired" }, { 0x0018, 0x1023, "LO", "Digital Image Format Acquired" }, { 0x0018, 0x1030, "LO", "Protocol Name" }, { 0x0018, 0x1040, "LO", "Contrast/Bolus Route" }, { 0x0018, 0x1041, "DS", "Contrast/Bolus Volume" }, { 0x0018, 0x1042, "TM", "Contrast/Bolus Start Time" }, { 0x0018, 0x1043, "TM", "Contrast/Bolus Stop Time" }, { 0x0018, 0x1044, "DS", "Contrast/Bolus Total Dose" }, { 0x0018, 0x1045, "IS", "Syringe Counts" }, { 0x0018, 0x1046, "DS", "Contrast Flow Rate" }, { 0x0018, 0x1047, "DS", "Contrast Flow Duration" }, { 0x0018, 0x1048, "CS", "Contrast/Bolus Ingredient" }, { 0x0018, 0x1049, "DS", "Contrast/Bolus Ingredient Concentration" }, { 0x0018, 0x1050, "DS", "Spatial Resolution" }, { 0x0018, 0x1060, "DS", "Trigger Time" }, { 0x0018, 0x1061, "LO", "Trigger Source or Type" }, { 0x0018, 0x1062, "IS", "Nominal Interval" }, { 0x0018, 0x1063, "DS", "Frame Time" }, { 0x0018, 0x1064, "LO", "Framing Type" }, { 0x0018, 0x1065, "DS", "Frame Time Vector" }, { 0x0018, 0x1066, "DS", "Frame Delay" }, { 0x0018, 0x1067, "DS", "Image Trigger Delay" }, { 0x0018, 0x1068, "DS", "Group Time Offset" }, { 0x0018, 0x1069, "DS", "Trigger Time Offset" }, { 0x0018, 0x106a, "CS", "Synchronization Trigger" }, { 0x0018, 0x106b, "UI", "Synchronization Frame of Reference" }, { 0x0018, 0x106e, "UL", "Trigger Sample Position" }, { 0x0018, 0x1070, "LO", "Radiopharmaceutical Route" }, { 0x0018, 0x1071, "DS", "Radiopharmaceutical Volume" }, { 0x0018, 0x1072, "TM", "Radiopharmaceutical Start Time" }, { 0x0018, 0x1073, "TM", "Radiopharmaceutical Stop Time" }, { 0x0018, 0x1074, "DS", "Radionuclide Total Dose" }, { 0x0018, 0x1075, "DS", "Radionuclide Half Life" }, { 0x0018, 0x1076, "DS", "Radionuclide Positron Fraction" }, { 0x0018, 0x1077, "DS", "Radiopharmaceutical Specific Activity" }, { 0x0018, 0x1080, "CS", "Beat Rejection Flag" }, { 0x0018, 0x1081, "IS", "Low R-R Value" }, { 0x0018, 0x1082, "IS", "High R-R Value" }, { 0x0018, 0x1083, "IS", "Intervals Acquired" }, { 0x0018, 0x1084, "IS", "Intervals Rejected" }, { 0x0018, 0x1085, "LO", "PVC Rejection" }, { 0x0018, 0x1086, "IS", "Skip Beats" }, { 0x0018, 0x1088, "IS", "Heart Rate" }, { 0x0018, 0x1090, "IS", "Cardiac Number of Images" }, { 0x0018, 0x1094, "IS", "Trigger Window" }, { 0x0018, 0x1100, "DS", "Reconstruction Diameter" }, { 0x0018, 0x1110, "DS", "Distance Source to Detector" }, { 0x0018, 0x1111, "DS", "Distance Source to Patient" }, { 0x0018, 0x1114, "DS", "Estimated Radiographic Magnification Factor" }, { 0x0018, 0x1120, "DS", "Gantry/Detector Tilt" }, { 0x0018, 0x1121, "DS", "Gantry/Detector Slew" }, { 0x0018, 0x1130, "DS", "Table Height" }, { 0x0018, 0x1131, "DS", "Table Traverse" }, { 0x0018, 0x1134, "CS", "Table Motion" }, { 0x0018, 0x1135, "DS", "Table Vertical Increment" }, { 0x0018, 0x1136, "DS", "Table Lateral Increment" }, { 0x0018, 0x1137, "DS", "Table Longitudinal Increment" }, { 0x0018, 0x1138, "DS", "Table Angle" }, { 0x0018, 0x113a, "CS", "Table Type" }, { 0x0018, 0x1140, "CS", "Rotation Direction" }, { 0x0018, 0x1141, "DS", "Angular Position" }, { 0x0018, 0x1142, "DS", "Radial Position" }, { 0x0018, 0x1143, "DS", "Scan Arc" }, { 0x0018, 0x1144, "DS", "Angular Step" }, { 0x0018, 0x1145, "DS", "Center of Rotation Offset" }, { 0x0018, 0x1146, "DS", "Rotation Offset" }, { 0x0018, 0x1147, "CS", "Field of View Shape" }, { 0x0018, 0x1149, "IS", "Field of View Dimension(s)" }, { 0x0018, 0x1150, "IS", "Exposure Time" }, { 0x0018, 0x1151, "IS", "X-ray Tube Current" }, { 0x0018, 0x1152, "IS", "Exposure" }, { 0x0018, 0x1153, "IS", "Exposure in uAs" }, { 0x0018, 0x1154, "DS", "AveragePulseWidth" }, { 0x0018, 0x1155, "CS", "RadiationSetting" }, { 0x0018, 0x1156, "CS", "Rectification Type" }, { 0x0018, 0x115a, "CS", "RadiationMode" }, { 0x0018, 0x115e, "DS", "ImageAreaDoseProduct" }, { 0x0018, 0x1160, "SH", "Filter Type" }, { 0x0018, 0x1161, "LO", "TypeOfFilters" }, { 0x0018, 0x1162, "DS", "IntensifierSize" }, { 0x0018, 0x1164, "DS", "ImagerPixelSpacing" }, { 0x0018, 0x1166, "CS", "Grid" }, { 0x0018, 0x1170, "IS", "Generator Power" }, { 0x0018, 0x1180, "SH", "Collimator/Grid Name" }, { 0x0018, 0x1181, "CS", "Collimator Type" }, { 0x0018, 0x1182, "IS", "Focal Distance" }, { 0x0018, 0x1183, "DS", "X Focus Center" }, { 0x0018, 0x1184, "DS", "Y Focus Center" }, { 0x0018, 0x1190, "DS", "Focal Spot(s)" }, { 0x0018, 0x1191, "CS", "Anode Target Material" }, { 0x0018, 0x11a0, "DS", "Body Part Thickness" }, { 0x0018, 0x11a2, "DS", "Compression Force" }, { 0x0018, 0x1200, "DA", "Date of Last Calibration" }, { 0x0018, 0x1201, "TM", "Time of Last Calibration" }, { 0x0018, 0x1210, "SH", "Convolution Kernel" }, { 0x0018, 0x1240, "IS", "Upper/Lower Pixel Values" }, { 0x0018, 0x1242, "IS", "Actual Frame Duration" }, { 0x0018, 0x1243, "IS", "Count Rate" }, { 0x0018, 0x1244, "US", "Preferred Playback Sequencing" }, { 0x0018, 0x1250, "SH", "Receiving Coil" }, { 0x0018, 0x1251, "SH", "Transmitting Coil" }, { 0x0018, 0x1260, "SH", "Plate Type" }, { 0x0018, 0x1261, "LO", "Phosphor Type" }, { 0x0018, 0x1300, "DS", "Scan Velocity" }, { 0x0018, 0x1301, "CS", "Whole Body Technique" }, { 0x0018, 0x1302, "IS", "Scan Length" }, { 0x0018, 0x1310, "US", "Acquisition Matrix" }, { 0x0018, 0x1312, "CS", "Phase Encoding Direction" }, { 0x0018, 0x1314, "DS", "Flip Angle" }, { 0x0018, 0x1315, "CS", "Variable Flip Angle Flag" }, { 0x0018, 0x1316, "DS", "SAR" }, { 0x0018, 0x1318, "DS", "dB/dt" }, { 0x0018, 0x1400, "LO", "Acquisition Device Processing Description" }, { 0x0018, 0x1401, "LO", "Acquisition Device Processing Code" }, { 0x0018, 0x1402, "CS", "Cassette Orientation" }, { 0x0018, 0x1403, "CS", "Cassette Size" }, { 0x0018, 0x1404, "US", "Exposures on Plate" }, { 0x0018, 0x1405, "IS", "Relative X-ray Exposure" }, { 0x0018, 0x1450, "DS", "Column Angulation" }, { 0x0018, 0x1460, "DS", "Tomo Layer Height" }, { 0x0018, 0x1470, "DS", "Tomo Angle" }, { 0x0018, 0x1480, "DS", "Tomo Time" }, { 0x0018, 0x1490, "CS", "Tomo Type" }, { 0x0018, 0x1491, "CS", "Tomo Class" }, { 0x0018, 0x1495, "IS", "Number of Tomosynthesis Source Images" }, { 0x0018, 0x1500, "CS", "PositionerMotion" }, { 0x0018, 0x1508, "CS", "Positioner Type" }, { 0x0018, 0x1510, "DS", "PositionerPrimaryAngle" }, { 0x0018, 0x1511, "DS", "PositionerSecondaryAngle" }, { 0x0018, 0x1520, "DS", "PositionerPrimaryAngleIncrement" }, { 0x0018, 0x1521, "DS", "PositionerSecondaryAngleIncrement" }, { 0x0018, 0x1530, "DS", "DetectorPrimaryAngle" }, { 0x0018, 0x1531, "DS", "DetectorSecondaryAngle" }, { 0x0018, 0x1600, "CS", "Shutter Shape" }, { 0x0018, 0x1602, "IS", "Shutter Left Vertical Edge" }, { 0x0018, 0x1604, "IS", "Shutter Right Vertical Edge" }, { 0x0018, 0x1606, "IS", "Shutter Upper Horizontal Edge" }, { 0x0018, 0x1608, "IS", "Shutter Lower Horizonta lEdge" }, { 0x0018, 0x1610, "IS", "Center of Circular Shutter" }, { 0x0018, 0x1612, "IS", "Radius of Circular Shutter" }, { 0x0018, 0x1620, "IS", "Vertices of Polygonal Shutter" }, { 0x0018, 0x1622, "US", "Shutter Presentation Value" }, { 0x0018, 0x1623, "US", "Shutter Overlay Group" }, { 0x0018, 0x1700, "CS", "Collimator Shape" }, { 0x0018, 0x1702, "IS", "Collimator Left Vertical Edge" }, { 0x0018, 0x1704, "IS", "Collimator Right Vertical Edge" }, { 0x0018, 0x1706, "IS", "Collimator Upper Horizontal Edge" }, { 0x0018, 0x1708, "IS", "Collimator Lower Horizontal Edge" }, { 0x0018, 0x1710, "IS", "Center of Circular Collimator" }, { 0x0018, 0x1712, "IS", "Radius of Circular Collimator" }, { 0x0018, 0x1720, "IS", "Vertices of Polygonal Collimator" }, { 0x0018, 0x1800, "CS", "Acquisition Time Synchronized" }, { 0x0018, 0x1801, "SH", "Time Source" }, { 0x0018, 0x1802, "CS", "Time Distribution Protocol" }, { 0x0018, 0x4000, "LT", "Acquisition Comments" }, { 0x0018, 0x5000, "SH", "Output Power" }, { 0x0018, 0x5010, "LO", "Transducer Data" }, { 0x0018, 0x5012, "DS", "Focus Depth" }, { 0x0018, 0x5020, "LO", "Processing Function" }, { 0x0018, 0x5021, "LO", "Postprocessing Function" }, { 0x0018, 0x5022, "DS", "Mechanical Index" }, { 0x0018, 0x5024, "DS", "Thermal Index" }, { 0x0018, 0x5026, "DS", "Cranial Thermal Index" }, { 0x0018, 0x5027, "DS", "Soft Tissue Thermal Index" }, { 0x0018, 0x5028, "DS", "Soft Tissue-Focus Thermal Index" }, { 0x0018, 0x5029, "DS", "Soft Tissue-Surface Thermal Index" }, { 0x0018, 0x5030, "DS", "Dynamic Range" }, { 0x0018, 0x5040, "DS", "Total Gain" }, { 0x0018, 0x5050, "IS", "Depth of Scan Field" }, { 0x0018, 0x5100, "CS", "Patient Position" }, { 0x0018, 0x5101, "CS", "View Position" }, { 0x0018, 0x5104, "SQ", "Projection Eponymous Name Code Sequence" }, { 0x0018, 0x5210, "DS", "Image Transformation Matrix" }, { 0x0018, 0x5212, "DS", "Image Translation Vector" }, { 0x0018, 0x6000, "DS", "Sensitivity" }, { 0x0018, 0x6011, "IS", "Sequence of Ultrasound Regions" }, { 0x0018, 0x6012, "US", "Region Spatial Format" }, { 0x0018, 0x6014, "US", "Region Data Type" }, { 0x0018, 0x6016, "UL", "Region Flags" }, { 0x0018, 0x6018, "UL", "Region Location Min X0" }, { 0x0018, 0x601a, "UL", "Region Location Min Y0" }, { 0x0018, 0x601c, "UL", "Region Location Max X1" }, { 0x0018, 0x601e, "UL", "Region Location Max Y1" }, { 0x0018, 0x6020, "SL", "Reference Pixel X0" }, { 0x0018, 0x6022, "SL", "Reference Pixel Y0" }, { 0x0018, 0x6024, "US", "Physical Units X Direction" }, { 0x0018, 0x6026, "US", "Physical Units Y Direction" }, { 0x0018, 0x6028, "FD", "Reference Pixel Physical Value X" }, { 0x0018, 0x602a, "US", "Reference Pixel Physical Value Y" }, { 0x0018, 0x602c, "US", "Physical Delta X" }, { 0x0018, 0x602e, "US", "Physical Delta Y" }, { 0x0018, 0x6030, "UL", "Transducer Frequency" }, { 0x0018, 0x6031, "CS", "Transducer Type" }, { 0x0018, 0x6032, "UL", "Pulse Repetition Frequency" }, { 0x0018, 0x6034, "FD", "Doppler Correction Angle" }, { 0x0018, 0x6036, "FD", "Steering Angle" }, { 0x0018, 0x6038, "UL", "Doppler Sample Volume X Position" }, { 0x0018, 0x603a, "UL", "Doppler Sample Volume Y Position" }, { 0x0018, 0x603c, "UL", "TM-Line Position X0" }, { 0x0018, 0x603e, "UL", "TM-Line Position Y0" }, { 0x0018, 0x6040, "UL", "TM-Line Position X1" }, { 0x0018, 0x6042, "UL", "TM-Line Position Y1" }, { 0x0018, 0x6044, "US", "Pixel Component Organization" }, { 0x0018, 0x6046, "UL", "Pixel Component Mask" }, { 0x0018, 0x6048, "UL", "Pixel Component Range Start" }, { 0x0018, 0x604a, "UL", "Pixel Component Range Stop" }, { 0x0018, 0x604c, "US", "Pixel Component Physical Units" }, { 0x0018, 0x604e, "US", "Pixel Component Data Type" }, { 0x0018, 0x6050, "UL", "Number of Table Break Points" }, { 0x0018, 0x6052, "UL", "Table of X Break Points" }, { 0x0018, 0x6054, "FD", "Table of Y Break Points" }, { 0x0018, 0x6056, "UL", "Number of Table Entries" }, { 0x0018, 0x6058, "UL", "Table of Pixel Values" }, { 0x0018, 0x605a, "FL", "Table of Parameter Values" }, { 0x0018, 0x7000, "CS", "Detector Conditions Nominal Flag" }, { 0x0018, 0x7001, "DS", "Detector Temperature" }, { 0x0018, 0x7004, "CS", "Detector Type" }, { 0x0018, 0x7005, "CS", "Detector Configuration" }, { 0x0018, 0x7006, "LT", "Detector Description" }, { 0x0018, 0x7008, "LT", "Detector Mode" }, { 0x0018, 0x700a, "SH", "Detector ID" }, { 0x0018, 0x700c, "DA", "Date of Last Detector Calibration " }, { 0x0018, 0x700e, "TM", "Time of Last Detector Calibration" }, { 0x0018, 0x7010, "IS", "Exposures on Detector Since Last Calibration" }, { 0x0018, 0x7011, "IS", "Exposures on Detector Since Manufactured" }, { 0x0018, 0x7012, "DS", "Detector Time Since Last Exposure" }, { 0x0018, 0x7014, "DS", "Detector Active Time" }, { 0x0018, 0x7016, "DS", "Detector Activation Offset From Exposure" }, { 0x0018, 0x701a, "DS", "Detector Binning" }, { 0x0018, 0x7020, "DS", "Detector Element Physical Size" }, { 0x0018, 0x7022, "DS", "Detector Element Spacing" }, { 0x0018, 0x7024, "CS", "Detector Active Shape" }, { 0x0018, 0x7026, "DS", "Detector Active Dimensions" }, { 0x0018, 0x7028, "DS", "Detector Active Origin" }, { 0x0018, 0x7030, "DS", "Field of View Origin" }, { 0x0018, 0x7032, "DS", "Field of View Rotation" }, { 0x0018, 0x7034, "CS", "Field of View Horizontal Flip" }, { 0x0018, 0x7040, "LT", "Grid Absorbing Material" }, { 0x0018, 0x7041, "LT", "Grid Spacing Material" }, { 0x0018, 0x7042, "DS", "Grid Thickness" }, { 0x0018, 0x7044, "DS", "Grid Pitch" }, { 0x0018, 0x7046, "IS", "Grid Aspect Ratio" }, { 0x0018, 0x7048, "DS", "Grid Period" }, { 0x0018, 0x704c, "DS", "Grid Focal Distance" }, { 0x0018, 0x7050, "LT", "Filter Material" }, { 0x0018, 0x7052, "DS", "Filter Thickness Minimum" }, { 0x0018, 0x7054, "DS", "Filter Thickness Maximum" }, { 0x0018, 0x7060, "CS", "Exposure Control Mode" }, { 0x0018, 0x7062, "LT", "Exposure Control Mode Description" }, { 0x0018, 0x7064, "CS", "Exposure Status" }, { 0x0018, 0x7065, "DS", "Phototimer Setting" }, { 0x0019, 0x0000, "xs", "?" }, { 0x0019, 0x0001, "xs", "?" }, { 0x0019, 0x0002, "xs", "?" }, { 0x0019, 0x0003, "xs", "?" }, { 0x0019, 0x0004, "xs", "?" }, { 0x0019, 0x0005, "xs", "?" }, { 0x0019, 0x0006, "xs", "?" }, { 0x0019, 0x0007, "xs", "?" }, { 0x0019, 0x0008, "xs", "?" }, { 0x0019, 0x0009, "xs", "?" }, { 0x0019, 0x000a, "xs", "?" }, { 0x0019, 0x000b, "DS", "?" }, { 0x0019, 0x000c, "US", "?" }, { 0x0019, 0x000d, "TM", "Time" }, { 0x0019, 0x000e, "xs", "?" }, { 0x0019, 0x000f, "DS", "Horizontal Frame Of Reference" }, { 0x0019, 0x0010, "xs", "?" }, { 0x0019, 0x0011, "xs", "?" }, { 0x0019, 0x0012, "xs", "?" }, { 0x0019, 0x0013, "xs", "?" }, { 0x0019, 0x0014, "xs", "?" }, { 0x0019, 0x0015, "xs", "?" }, { 0x0019, 0x0016, "xs", "?" }, { 0x0019, 0x0017, "xs", "?" }, { 0x0019, 0x0018, "xs", "?" }, { 0x0019, 0x0019, "xs", "?" }, { 0x0019, 0x001a, "xs", "?" }, { 0x0019, 0x001b, "xs", "?" }, { 0x0019, 0x001c, "CS", "Dose" }, { 0x0019, 0x001d, "IS", "Side Mark" }, { 0x0019, 0x001e, "xs", "?" }, { 0x0019, 0x001f, "DS", "Exposure Duration" }, { 0x0019, 0x0020, "xs", "?" }, { 0x0019, 0x0021, "xs", "?" }, { 0x0019, 0x0022, "xs", "?" }, { 0x0019, 0x0023, "xs", "?" }, { 0x0019, 0x0024, "xs", "?" }, { 0x0019, 0x0025, "xs", "?" }, { 0x0019, 0x0026, "xs", "?" }, { 0x0019, 0x0027, "xs", "?" }, { 0x0019, 0x0028, "xs", "?" }, { 0x0019, 0x0029, "IS", "?" }, { 0x0019, 0x002a, "xs", "?" }, { 0x0019, 0x002b, "DS", "Xray Off Position" }, { 0x0019, 0x002c, "xs", "?" }, { 0x0019, 0x002d, "US", "?" }, { 0x0019, 0x002e, "xs", "?" }, { 0x0019, 0x002f, "DS", "Trigger Frequency" }, { 0x0019, 0x0030, "xs", "?" }, { 0x0019, 0x0031, "xs", "?" }, { 0x0019, 0x0032, "xs", "?" }, { 0x0019, 0x0033, "UN", "ECG 2 Offset 2" }, { 0x0019, 0x0034, "US", "?" }, { 0x0019, 0x0036, "US", "?" }, { 0x0019, 0x0038, "US", "?" }, { 0x0019, 0x0039, "xs", "?" }, { 0x0019, 0x003a, "xs", "?" }, { 0x0019, 0x003b, "LT", "?" }, { 0x0019, 0x003c, "xs", "?" }, { 0x0019, 0x003e, "xs", "?" }, { 0x0019, 0x003f, "UN", "?" }, { 0x0019, 0x0040, "xs", "?" }, { 0x0019, 0x0041, "xs", "?" }, { 0x0019, 0x0042, "xs", "?" }, { 0x0019, 0x0043, "xs", "?" }, { 0x0019, 0x0044, "xs", "?" }, { 0x0019, 0x0045, "xs", "?" }, { 0x0019, 0x0046, "xs", "?" }, { 0x0019, 0x0047, "xs", "?" }, { 0x0019, 0x0048, "xs", "?" }, { 0x0019, 0x0049, "US", "?" }, { 0x0019, 0x004a, "xs", "?" }, { 0x0019, 0x004b, "SL", "Data Size For Scan Data" }, { 0x0019, 0x004c, "US", "?" }, { 0x0019, 0x004e, "US", "?" }, { 0x0019, 0x0050, "xs", "?" }, { 0x0019, 0x0051, "xs", "?" }, { 0x0019, 0x0052, "xs", "?" }, { 0x0019, 0x0053, "LT", "Barcode" }, { 0x0019, 0x0054, "xs", "?" }, { 0x0019, 0x0055, "DS", "Receiver Reference Gain" }, { 0x0019, 0x0056, "xs", "?" }, { 0x0019, 0x0057, "SS", "CT Water Number" }, { 0x0019, 0x0058, "xs", "?" }, { 0x0019, 0x005a, "xs", "?" }, { 0x0019, 0x005c, "xs", "?" }, { 0x0019, 0x005d, "US", "?" }, { 0x0019, 0x005e, "xs", "?" }, { 0x0019, 0x005f, "SL", "Increment Between Channels" }, { 0x0019, 0x0060, "xs", "?" }, { 0x0019, 0x0061, "xs", "?" }, { 0x0019, 0x0062, "xs", "?" }, { 0x0019, 0x0063, "xs", "?" }, { 0x0019, 0x0064, "xs", "?" }, { 0x0019, 0x0065, "xs", "?" }, { 0x0019, 0x0066, "xs", "?" }, { 0x0019, 0x0067, "xs", "?" }, { 0x0019, 0x0068, "xs", "?" }, { 0x0019, 0x0069, "UL", "Convolution Mode" }, { 0x0019, 0x006a, "xs", "?" }, { 0x0019, 0x006b, "SS", "Field Of View In Detector Cells" }, { 0x0019, 0x006c, "US", "?" }, { 0x0019, 0x006e, "US", "?" }, { 0x0019, 0x0070, "xs", "?" }, { 0x0019, 0x0071, "xs", "?" }, { 0x0019, 0x0072, "xs", "?" }, { 0x0019, 0x0073, "xs", "?" }, { 0x0019, 0x0074, "xs", "?" }, { 0x0019, 0x0075, "xs", "?" }, { 0x0019, 0x0076, "xs", "?" }, { 0x0019, 0x0077, "US", "?" }, { 0x0019, 0x0078, "US", "?" }, { 0x0019, 0x007a, "US", "?" }, { 0x0019, 0x007c, "US", "?" }, { 0x0019, 0x007d, "DS", "Second Echo" }, { 0x0019, 0x007e, "xs", "?" }, { 0x0019, 0x007f, "DS", "Table Delta" }, { 0x0019, 0x0080, "xs", "?" }, { 0x0019, 0x0081, "xs", "?" }, { 0x0019, 0x0082, "xs", "?" }, { 0x0019, 0x0083, "xs", "?" }, { 0x0019, 0x0084, "xs", "?" }, { 0x0019, 0x0085, "xs", "?" }, { 0x0019, 0x0086, "xs", "?" }, { 0x0019, 0x0087, "xs", "?" }, { 0x0019, 0x0088, "xs", "?" }, { 0x0019, 0x008a, "xs", "?" }, { 0x0019, 0x008b, "SS", "Actual Receive Gain Digital" }, { 0x0019, 0x008c, "US", "?" }, { 0x0019, 0x008d, "DS", "Delay After Trigger" }, { 0x0019, 0x008e, "US", "?" }, { 0x0019, 0x008f, "SS", "Swap Phase Frequency" }, { 0x0019, 0x0090, "xs", "?" }, { 0x0019, 0x0091, "xs", "?" }, { 0x0019, 0x0092, "xs", "?" }, { 0x0019, 0x0093, "xs", "?" }, { 0x0019, 0x0094, "xs", "?" }, { 0x0019, 0x0095, "SS", "Analog Receiver Gain" }, { 0x0019, 0x0096, "xs", "?" }, { 0x0019, 0x0097, "xs", "?" }, { 0x0019, 0x0098, "xs", "?" }, { 0x0019, 0x0099, "US", "?" }, { 0x0019, 0x009a, "US", "?" }, { 0x0019, 0x009b, "SS", "Pulse Sequence Mode" }, { 0x0019, 0x009c, "xs", "?" }, { 0x0019, 0x009d, "DT", "Pulse Sequence Date" }, { 0x0019, 0x009e, "xs", "?" }, { 0x0019, 0x009f, "xs", "?" }, { 0x0019, 0x00a0, "xs", "?" }, { 0x0019, 0x00a1, "xs", "?" }, { 0x0019, 0x00a2, "xs", "?" }, { 0x0019, 0x00a3, "xs", "?" }, { 0x0019, 0x00a4, "xs", "?" }, { 0x0019, 0x00a5, "xs", "?" }, { 0x0019, 0x00a6, "xs", "?" }, { 0x0019, 0x00a7, "xs", "?" }, { 0x0019, 0x00a8, "xs", "?" }, { 0x0019, 0x00a9, "xs", "?" }, { 0x0019, 0x00aa, "xs", "?" }, { 0x0019, 0x00ab, "xs", "?" }, { 0x0019, 0x00ac, "xs", "?" }, { 0x0019, 0x00ad, "xs", "?" }, { 0x0019, 0x00ae, "xs", "?" }, { 0x0019, 0x00af, "xs", "?" }, { 0x0019, 0x00b0, "xs", "?" }, { 0x0019, 0x00b1, "xs", "?" }, { 0x0019, 0x00b2, "xs", "?" }, { 0x0019, 0x00b3, "xs", "?" }, { 0x0019, 0x00b4, "xs", "?" }, { 0x0019, 0x00b5, "xs", "?" }, { 0x0019, 0x00b6, "DS", "User Data" }, { 0x0019, 0x00b7, "DS", "User Data" }, { 0x0019, 0x00b8, "DS", "User Data" }, { 0x0019, 0x00b9, "DS", "User Data" }, { 0x0019, 0x00ba, "DS", "User Data" }, { 0x0019, 0x00bb, "DS", "User Data" }, { 0x0019, 0x00bc, "DS", "User Data" }, { 0x0019, 0x00bd, "DS", "User Data" }, { 0x0019, 0x00be, "DS", "Projection Angle" }, { 0x0019, 0x00c0, "xs", "?" }, { 0x0019, 0x00c1, "xs", "?" }, { 0x0019, 0x00c2, "xs", "?" }, { 0x0019, 0x00c3, "xs", "?" }, { 0x0019, 0x00c4, "xs", "?" }, { 0x0019, 0x00c5, "xs", "?" }, { 0x0019, 0x00c6, "SS", "SAT Location H" }, { 0x0019, 0x00c7, "SS", "SAT Location F" }, { 0x0019, 0x00c8, "SS", "SAT Thickness R L" }, { 0x0019, 0x00c9, "SS", "SAT Thickness A P" }, { 0x0019, 0x00ca, "SS", "SAT Thickness H F" }, { 0x0019, 0x00cb, "xs", "?" }, { 0x0019, 0x00cc, "xs", "?" }, { 0x0019, 0x00cd, "SS", "Thickness Disclaimer" }, { 0x0019, 0x00ce, "SS", "Prescan Type" }, { 0x0019, 0x00cf, "SS", "Prescan Status" }, { 0x0019, 0x00d0, "SH", "Raw Data Type" }, { 0x0019, 0x00d1, "DS", "Flow Sensitivity" }, { 0x0019, 0x00d2, "xs", "?" }, { 0x0019, 0x00d3, "xs", "?" }, { 0x0019, 0x00d4, "xs", "?" }, { 0x0019, 0x00d5, "xs", "?" }, { 0x0019, 0x00d6, "xs", "?" }, { 0x0019, 0x00d7, "xs", "?" }, { 0x0019, 0x00d8, "xs", "?" }, { 0x0019, 0x00d9, "xs", "?" }, { 0x0019, 0x00da, "xs", "?" }, { 0x0019, 0x00db, "DS", "Back Projector Coefficient" }, { 0x0019, 0x00dc, "SS", "Primary Speed Correction Used" }, { 0x0019, 0x00dd, "SS", "Overrange Correction Used" }, { 0x0019, 0x00de, "DS", "Dynamic Z Alpha Value" }, { 0x0019, 0x00df, "DS", "User Data" }, { 0x0019, 0x00e0, "DS", "User Data" }, { 0x0019, 0x00e1, "xs", "?" }, { 0x0019, 0x00e2, "xs", "?" }, { 0x0019, 0x00e3, "xs", "?" }, { 0x0019, 0x00e4, "LT", "?" }, { 0x0019, 0x00e5, "IS", "?" }, { 0x0019, 0x00e6, "US", "?" }, { 0x0019, 0x00e8, "DS", "?" }, { 0x0019, 0x00e9, "DS", "?" }, { 0x0019, 0x00eb, "DS", "?" }, { 0x0019, 0x00ec, "US", "?" }, { 0x0019, 0x00f0, "xs", "?" }, { 0x0019, 0x00f1, "xs", "?" }, { 0x0019, 0x00f2, "xs", "?" }, { 0x0019, 0x00f3, "xs", "?" }, { 0x0019, 0x00f4, "LT", "?" }, { 0x0019, 0x00f9, "DS", "Transmission Gain" }, { 0x0019, 0x1015, "UN", "?" }, { 0x0020, 0x0000, "UL", "Relationship Group Length" }, { 0x0020, 0x000d, "UI", "Study Instance UID" }, { 0x0020, 0x000e, "UI", "Series Instance UID" }, { 0x0020, 0x0010, "SH", "Study ID" }, { 0x0020, 0x0011, "IS", "Series Number" }, { 0x0020, 0x0012, "IS", "Acquisition Number" }, { 0x0020, 0x0013, "IS", "Instance (formerly Image) Number" }, { 0x0020, 0x0014, "IS", "Isotope Number" }, { 0x0020, 0x0015, "IS", "Phase Number" }, { 0x0020, 0x0016, "IS", "Interval Number" }, { 0x0020, 0x0017, "IS", "Time Slot Number" }, { 0x0020, 0x0018, "IS", "Angle Number" }, { 0x0020, 0x0020, "CS", "Patient Orientation" }, { 0x0020, 0x0022, "IS", "Overlay Number" }, { 0x0020, 0x0024, "IS", "Curve Number" }, { 0x0020, 0x0026, "IS", "LUT Number" }, { 0x0020, 0x0030, "DS", "Image Position" }, { 0x0020, 0x0032, "DS", "Image Position (Patient)" }, { 0x0020, 0x0035, "DS", "Image Orientation" }, { 0x0020, 0x0037, "DS", "Image Orientation (Patient)" }, { 0x0020, 0x0050, "DS", "Location" }, { 0x0020, 0x0052, "UI", "Frame of Reference UID" }, { 0x0020, 0x0060, "CS", "Laterality" }, { 0x0020, 0x0062, "CS", "Image Laterality" }, { 0x0020, 0x0070, "LT", "Image Geometry Type" }, { 0x0020, 0x0080, "LO", "Masking Image" }, { 0x0020, 0x0100, "IS", "Temporal Position Identifier" }, { 0x0020, 0x0105, "IS", "Number of Temporal Positions" }, { 0x0020, 0x0110, "DS", "Temporal Resolution" }, { 0x0020, 0x1000, "IS", "Series in Study" }, { 0x0020, 0x1001, "DS", "Acquisitions in Series" }, { 0x0020, 0x1002, "IS", "Images in Acquisition" }, { 0x0020, 0x1003, "IS", "Images in Series" }, { 0x0020, 0x1004, "IS", "Acquisitions in Study" }, { 0x0020, 0x1005, "IS", "Images in Study" }, { 0x0020, 0x1020, "LO", "Reference" }, { 0x0020, 0x1040, "LO", "Position Reference Indicator" }, { 0x0020, 0x1041, "DS", "Slice Location" }, { 0x0020, 0x1070, "IS", "Other Study Numbers" }, { 0x0020, 0x1200, "IS", "Number of Patient Related Studies" }, { 0x0020, 0x1202, "IS", "Number of Patient Related Series" }, { 0x0020, 0x1204, "IS", "Number of Patient Related Images" }, { 0x0020, 0x1206, "IS", "Number of Study Related Series" }, { 0x0020, 0x1208, "IS", "Number of Study Related Series" }, { 0x0020, 0x3100, "LO", "Source Image IDs" }, { 0x0020, 0x3401, "LO", "Modifying Device ID" }, { 0x0020, 0x3402, "LO", "Modified Image ID" }, { 0x0020, 0x3403, "xs", "Modified Image Date" }, { 0x0020, 0x3404, "LO", "Modifying Device Manufacturer" }, { 0x0020, 0x3405, "xs", "Modified Image Time" }, { 0x0020, 0x3406, "xs", "Modified Image Description" }, { 0x0020, 0x4000, "LT", "Image Comments" }, { 0x0020, 0x5000, "AT", "Original Image Identification" }, { 0x0020, 0x5002, "LO", "Original Image Identification Nomenclature" }, { 0x0021, 0x0000, "xs", "?" }, { 0x0021, 0x0001, "xs", "?" }, { 0x0021, 0x0002, "xs", "?" }, { 0x0021, 0x0003, "xs", "?" }, { 0x0021, 0x0004, "DS", "VOI Position" }, { 0x0021, 0x0005, "xs", "?" }, { 0x0021, 0x0006, "IS", "CSI Matrix Size Original" }, { 0x0021, 0x0007, "xs", "?" }, { 0x0021, 0x0008, "DS", "Spatial Grid Shift" }, { 0x0021, 0x0009, "DS", "Signal Limits Minimum" }, { 0x0021, 0x0010, "xs", "?" }, { 0x0021, 0x0011, "xs", "?" }, { 0x0021, 0x0012, "xs", "?" }, { 0x0021, 0x0013, "xs", "?" }, { 0x0021, 0x0014, "xs", "?" }, { 0x0021, 0x0015, "xs", "?" }, { 0x0021, 0x0016, "xs", "?" }, { 0x0021, 0x0017, "DS", "EPI Operation Mode Flag" }, { 0x0021, 0x0018, "xs", "?" }, { 0x0021, 0x0019, "xs", "?" }, { 0x0021, 0x0020, "xs", "?" }, { 0x0021, 0x0021, "xs", "?" }, { 0x0021, 0x0022, "xs", "?" }, { 0x0021, 0x0024, "xs", "?" }, { 0x0021, 0x0025, "US", "?" }, { 0x0021, 0x0026, "IS", "Image Pixel Offset" }, { 0x0021, 0x0030, "xs", "?" }, { 0x0021, 0x0031, "xs", "?" }, { 0x0021, 0x0032, "xs", "?" }, { 0x0021, 0x0034, "xs", "?" }, { 0x0021, 0x0035, "SS", "Series From Which Prescribed" }, { 0x0021, 0x0036, "xs", "?" }, { 0x0021, 0x0037, "SS", "Screen Format" }, { 0x0021, 0x0039, "DS", "Slab Thickness" }, { 0x0021, 0x0040, "xs", "?" }, { 0x0021, 0x0041, "xs", "?" }, { 0x0021, 0x0042, "xs", "?" }, { 0x0021, 0x0043, "xs", "?" }, { 0x0021, 0x0044, "xs", "?" }, { 0x0021, 0x0045, "xs", "?" }, { 0x0021, 0x0046, "xs", "?" }, { 0x0021, 0x0047, "xs", "?" }, { 0x0021, 0x0048, "xs", "?" }, { 0x0021, 0x0049, "xs", "?" }, { 0x0021, 0x004a, "xs", "?" }, { 0x0021, 0x004e, "US", "?" }, { 0x0021, 0x004f, "xs", "?" }, { 0x0021, 0x0050, "xs", "?" }, { 0x0021, 0x0051, "xs", "?" }, { 0x0021, 0x0052, "xs", "?" }, { 0x0021, 0x0053, "xs", "?" }, { 0x0021, 0x0054, "xs", "?" }, { 0x0021, 0x0055, "xs", "?" }, { 0x0021, 0x0056, "xs", "?" }, { 0x0021, 0x0057, "xs", "?" }, { 0x0021, 0x0058, "xs", "?" }, { 0x0021, 0x0059, "xs", "?" }, { 0x0021, 0x005a, "SL", "Integer Slop" }, { 0x0021, 0x005b, "DS", "Float Slop" }, { 0x0021, 0x005c, "DS", "Float Slop" }, { 0x0021, 0x005d, "DS", "Float Slop" }, { 0x0021, 0x005e, "DS", "Float Slop" }, { 0x0021, 0x005f, "DS", "Float Slop" }, { 0x0021, 0x0060, "xs", "?" }, { 0x0021, 0x0061, "DS", "Image Normal" }, { 0x0021, 0x0062, "IS", "Reference Type Code" }, { 0x0021, 0x0063, "DS", "Image Distance" }, { 0x0021, 0x0065, "US", "Image Positioning History Mask" }, { 0x0021, 0x006a, "DS", "Image Row" }, { 0x0021, 0x006b, "DS", "Image Column" }, { 0x0021, 0x0070, "xs", "?" }, { 0x0021, 0x0071, "xs", "?" }, { 0x0021, 0x0072, "xs", "?" }, { 0x0021, 0x0073, "DS", "Second Repetition Time" }, { 0x0021, 0x0075, "DS", "Light Brightness" }, { 0x0021, 0x0076, "DS", "Light Contrast" }, { 0x0021, 0x007a, "IS", "Overlay Threshold" }, { 0x0021, 0x007b, "IS", "Surface Threshold" }, { 0x0021, 0x007c, "IS", "Grey Scale Threshold" }, { 0x0021, 0x0080, "xs", "?" }, { 0x0021, 0x0081, "DS", "Auto Window Level Alpha" }, { 0x0021, 0x0082, "xs", "?" }, { 0x0021, 0x0083, "DS", "Auto Window Level Window" }, { 0x0021, 0x0084, "DS", "Auto Window Level Level" }, { 0x0021, 0x0090, "xs", "?" }, { 0x0021, 0x0091, "xs", "?" }, { 0x0021, 0x0092, "xs", "?" }, { 0x0021, 0x0093, "xs", "?" }, { 0x0021, 0x0094, "DS", "EPI Change Value of X Component" }, { 0x0021, 0x0095, "DS", "EPI Change Value of Y Component" }, { 0x0021, 0x0096, "DS", "EPI Change Value of Z Component" }, { 0x0021, 0x00a0, "xs", "?" }, { 0x0021, 0x00a1, "DS", "?" }, { 0x0021, 0x00a2, "xs", "?" }, { 0x0021, 0x00a3, "LT", "?" }, { 0x0021, 0x00a4, "LT", "?" }, { 0x0021, 0x00a7, "LT", "?" }, { 0x0021, 0x00b0, "IS", "?" }, { 0x0021, 0x00c0, "IS", "?" }, { 0x0023, 0x0000, "xs", "?" }, { 0x0023, 0x0001, "SL", "Number Of Series In Study" }, { 0x0023, 0x0002, "SL", "Number Of Unarchived Series" }, { 0x0023, 0x0010, "xs", "?" }, { 0x0023, 0x0020, "xs", "?" }, { 0x0023, 0x0030, "xs", "?" }, { 0x0023, 0x0040, "xs", "?" }, { 0x0023, 0x0050, "xs", "?" }, { 0x0023, 0x0060, "xs", "?" }, { 0x0023, 0x0070, "xs", "?" }, { 0x0023, 0x0074, "SL", "Number Of Updates To Info" }, { 0x0023, 0x007d, "SS", "Indicates If Study Has Complete Info" }, { 0x0023, 0x0080, "xs", "?" }, { 0x0023, 0x0090, "xs", "?" }, { 0x0023, 0x00ff, "US", "?" }, { 0x0025, 0x0000, "UL", "Group Length" }, { 0x0025, 0x0006, "SS", "Last Pulse Sequence Used" }, { 0x0025, 0x0007, "SL", "Images In Series" }, { 0x0025, 0x0010, "SS", "Landmark Counter" }, { 0x0025, 0x0011, "SS", "Number Of Acquisitions" }, { 0x0025, 0x0014, "SL", "Indicates Number Of Updates To Info" }, { 0x0025, 0x0017, "SL", "Series Complete Flag" }, { 0x0025, 0x0018, "SL", "Number Of Images Archived" }, { 0x0025, 0x0019, "SL", "Last Image Number Used" }, { 0x0025, 0x001a, "SH", "Primary Receiver Suite And Host" }, { 0x0027, 0x0000, "US", "?" }, { 0x0027, 0x0006, "SL", "Image Archive Flag" }, { 0x0027, 0x0010, "SS", "Scout Type" }, { 0x0027, 0x0011, "UN", "?" }, { 0x0027, 0x0012, "IS", "?" }, { 0x0027, 0x0013, "IS", "?" }, { 0x0027, 0x0014, "IS", "?" }, { 0x0027, 0x0015, "IS", "?" }, { 0x0027, 0x0016, "LT", "?" }, { 0x0027, 0x001c, "SL", "Vma Mamp" }, { 0x0027, 0x001d, "SS", "Vma Phase" }, { 0x0027, 0x001e, "SL", "Vma Mod" }, { 0x0027, 0x001f, "SL", "Vma Clip" }, { 0x0027, 0x0020, "SS", "Smart Scan On Off Flag" }, { 0x0027, 0x0030, "SH", "Foreign Image Revision" }, { 0x0027, 0x0031, "SS", "Imaging Mode" }, { 0x0027, 0x0032, "SS", "Pulse Sequence" }, { 0x0027, 0x0033, "SL", "Imaging Options" }, { 0x0027, 0x0035, "SS", "Plane Type" }, { 0x0027, 0x0036, "SL", "Oblique Plane" }, { 0x0027, 0x0040, "SH", "RAS Letter Of Image Location" }, { 0x0027, 0x0041, "FL", "Image Location" }, { 0x0027, 0x0042, "FL", "Center R Coord Of Plane Image" }, { 0x0027, 0x0043, "FL", "Center A Coord Of Plane Image" }, { 0x0027, 0x0044, "FL", "Center S Coord Of Plane Image" }, { 0x0027, 0x0045, "FL", "Normal R Coord" }, { 0x0027, 0x0046, "FL", "Normal A Coord" }, { 0x0027, 0x0047, "FL", "Normal S Coord" }, { 0x0027, 0x0048, "FL", "R Coord Of Top Right Corner" }, { 0x0027, 0x0049, "FL", "A Coord Of Top Right Corner" }, { 0x0027, 0x004a, "FL", "S Coord Of Top Right Corner" }, { 0x0027, 0x004b, "FL", "R Coord Of Bottom Right Corner" }, { 0x0027, 0x004c, "FL", "A Coord Of Bottom Right Corner" }, { 0x0027, 0x004d, "FL", "S Coord Of Bottom Right Corner" }, { 0x0027, 0x0050, "FL", "Table Start Location" }, { 0x0027, 0x0051, "FL", "Table End Location" }, { 0x0027, 0x0052, "SH", "RAS Letter For Side Of Image" }, { 0x0027, 0x0053, "SH", "RAS Letter For Anterior Posterior" }, { 0x0027, 0x0054, "SH", "RAS Letter For Scout Start Loc" }, { 0x0027, 0x0055, "SH", "RAS Letter For Scout End Loc" }, { 0x0027, 0x0060, "FL", "Image Dimension X" }, { 0x0027, 0x0061, "FL", "Image Dimension Y" }, { 0x0027, 0x0062, "FL", "Number Of Excitations" }, { 0x0028, 0x0000, "UL", "Image Presentation Group Length" }, { 0x0028, 0x0002, "US", "Samples per Pixel" }, { 0x0028, 0x0004, "CS", "Photometric Interpretation" }, { 0x0028, 0x0005, "US", "Image Dimensions" }, { 0x0028, 0x0006, "US", "Planar Configuration" }, { 0x0028, 0x0008, "IS", "Number of Frames" }, { 0x0028, 0x0009, "AT", "Frame Increment Pointer" }, { 0x0028, 0x0010, "US", "Rows" }, { 0x0028, 0x0011, "US", "Columns" }, { 0x0028, 0x0012, "US", "Planes" }, { 0x0028, 0x0014, "US", "Ultrasound Color Data Present" }, { 0x0028, 0x0030, "DS", "Pixel Spacing" }, { 0x0028, 0x0031, "DS", "Zoom Factor" }, { 0x0028, 0x0032, "DS", "Zoom Center" }, { 0x0028, 0x0034, "IS", "Pixel Aspect Ratio" }, { 0x0028, 0x0040, "LO", "Image Format" }, { 0x0028, 0x0050, "LT", "Manipulated Image" }, { 0x0028, 0x0051, "CS", "Corrected Image" }, { 0x0028, 0x005f, "LO", "Compression Recognition Code" }, { 0x0028, 0x0060, "LO", "Compression Code" }, { 0x0028, 0x0061, "SH", "Compression Originator" }, { 0x0028, 0x0062, "SH", "Compression Label" }, { 0x0028, 0x0063, "SH", "Compression Description" }, { 0x0028, 0x0065, "LO", "Compression Sequence" }, { 0x0028, 0x0066, "AT", "Compression Step Pointers" }, { 0x0028, 0x0068, "US", "Repeat Interval" }, { 0x0028, 0x0069, "US", "Bits Grouped" }, { 0x0028, 0x0070, "US", "Perimeter Table" }, { 0x0028, 0x0071, "xs", "Perimeter Value" }, { 0x0028, 0x0080, "US", "Predictor Rows" }, { 0x0028, 0x0081, "US", "Predictor Columns" }, { 0x0028, 0x0082, "US", "Predictor Constants" }, { 0x0028, 0x0090, "LO", "Blocked Pixels" }, { 0x0028, 0x0091, "US", "Block Rows" }, { 0x0028, 0x0092, "US", "Block Columns" }, { 0x0028, 0x0093, "US", "Row Overlap" }, { 0x0028, 0x0094, "US", "Column Overlap" }, { 0x0028, 0x0100, "US", "Bits Allocated" }, { 0x0028, 0x0101, "US", "Bits Stored" }, { 0x0028, 0x0102, "US", "High Bit" }, { 0x0028, 0x0103, "US", "Pixel Representation" }, { 0x0028, 0x0104, "xs", "Smallest Valid Pixel Value" }, { 0x0028, 0x0105, "xs", "Largest Valid Pixel Value" }, { 0x0028, 0x0106, "xs", "Smallest Image Pixel Value" }, { 0x0028, 0x0107, "xs", "Largest Image Pixel Value" }, { 0x0028, 0x0108, "xs", "Smallest Pixel Value in Series" }, { 0x0028, 0x0109, "xs", "Largest Pixel Value in Series" }, { 0x0028, 0x0110, "xs", "Smallest Pixel Value in Plane" }, { 0x0028, 0x0111, "xs", "Largest Pixel Value in Plane" }, { 0x0028, 0x0120, "xs", "Pixel Padding Value" }, { 0x0028, 0x0200, "xs", "Image Location" }, { 0x0028, 0x0300, "CS", "Quality Control Image" }, { 0x0028, 0x0301, "CS", "Burned In Annotation" }, { 0x0028, 0x0400, "xs", "?" }, { 0x0028, 0x0401, "xs", "?" }, { 0x0028, 0x0402, "xs", "?" }, { 0x0028, 0x0403, "xs", "?" }, { 0x0028, 0x0404, "AT", "Details of Coefficients" }, { 0x0028, 0x0700, "LO", "DCT Label" }, { 0x0028, 0x0701, "LO", "Data Block Description" }, { 0x0028, 0x0702, "AT", "Data Block" }, { 0x0028, 0x0710, "US", "Normalization Factor Format" }, { 0x0028, 0x0720, "US", "Zonal Map Number Format" }, { 0x0028, 0x0721, "AT", "Zonal Map Location" }, { 0x0028, 0x0722, "US", "Zonal Map Format" }, { 0x0028, 0x0730, "US", "Adaptive Map Format" }, { 0x0028, 0x0740, "US", "Code Number Format" }, { 0x0028, 0x0800, "LO", "Code Label" }, { 0x0028, 0x0802, "US", "Number of Tables" }, { 0x0028, 0x0803, "AT", "Code Table Location" }, { 0x0028, 0x0804, "US", "Bits For Code Word" }, { 0x0028, 0x0808, "AT", "Image Data Location" }, { 0x0028, 0x1040, "CS", "Pixel Intensity Relationship" }, { 0x0028, 0x1041, "SS", "Pixel Intensity Relationship Sign" }, { 0x0028, 0x1050, "DS", "Window Center" }, { 0x0028, 0x1051, "DS", "Window Width" }, { 0x0028, 0x1052, "DS", "Rescale Intercept" }, { 0x0028, 0x1053, "DS", "Rescale Slope" }, { 0x0028, 0x1054, "LO", "Rescale Type" }, { 0x0028, 0x1055, "LO", "Window Center & Width Explanation" }, { 0x0028, 0x1080, "LO", "Gray Scale" }, { 0x0028, 0x1090, "CS", "Recommended Viewing Mode" }, { 0x0028, 0x1100, "xs", "Gray Lookup Table Descriptor" }, { 0x0028, 0x1101, "xs", "Red Palette Color Lookup Table Descriptor" }, { 0x0028, 0x1102, "xs", "Green Palette Color Lookup Table Descriptor" }, { 0x0028, 0x1103, "xs", "Blue Palette Color Lookup Table Descriptor" }, { 0x0028, 0x1111, "OW", "Large Red Palette Color Lookup Table Descriptor" }, { 0x0028, 0x1112, "OW", "Large Green Palette Color Lookup Table Descriptor" }, { 0x0028, 0x1113, "OW", "Large Blue Palette Color Lookup Table Descriptor" }, { 0x0028, 0x1199, "UI", "Palette Color Lookup Table UID" }, { 0x0028, 0x1200, "xs", "Gray Lookup Table Data" }, { 0x0028, 0x1201, "OW", "Red Palette Color Lookup Table Data" }, { 0x0028, 0x1202, "OW", "Green Palette Color Lookup Table Data" }, { 0x0028, 0x1203, "OW", "Blue Palette Color Lookup Table Data" }, { 0x0028, 0x1211, "OW", "Large Red Palette Color Lookup Table Data" }, { 0x0028, 0x1212, "OW", "Large Green Palette Color Lookup Table Data" }, { 0x0028, 0x1213, "OW", "Large Blue Palette Color Lookup Table Data" }, { 0x0028, 0x1214, "UI", "Large Palette Color Lookup Table UID" }, { 0x0028, 0x1221, "OW", "Segmented Red Palette Color Lookup Table Data" }, { 0x0028, 0x1222, "OW", "Segmented Green Palette Color Lookup Table Data" }, { 0x0028, 0x1223, "OW", "Segmented Blue Palette Color Lookup Table Data" }, { 0x0028, 0x1300, "CS", "Implant Present" }, { 0x0028, 0x2110, "CS", "Lossy Image Compression" }, { 0x0028, 0x2112, "DS", "Lossy Image Compression Ratio" }, { 0x0028, 0x3000, "SQ", "Modality LUT Sequence" }, { 0x0028, 0x3002, "US", "LUT Descriptor" }, { 0x0028, 0x3003, "LO", "LUT Explanation" }, { 0x0028, 0x3004, "LO", "Modality LUT Type" }, { 0x0028, 0x3006, "US", "LUT Data" }, { 0x0028, 0x3010, "xs", "VOI LUT Sequence" }, { 0x0028, 0x4000, "LT", "Image Presentation Comments" }, { 0x0028, 0x5000, "SQ", "Biplane Acquisition Sequence" }, { 0x0028, 0x6010, "US", "Representative Frame Number" }, { 0x0028, 0x6020, "US", "Frame Numbers of Interest" }, { 0x0028, 0x6022, "LO", "Frame of Interest Description" }, { 0x0028, 0x6030, "US", "Mask Pointer" }, { 0x0028, 0x6040, "US", "R Wave Pointer" }, { 0x0028, 0x6100, "SQ", "Mask Subtraction Sequence" }, { 0x0028, 0x6101, "CS", "Mask Operation" }, { 0x0028, 0x6102, "US", "Applicable Frame Range" }, { 0x0028, 0x6110, "US", "Mask Frame Numbers" }, { 0x0028, 0x6112, "US", "Contrast Frame Averaging" }, { 0x0028, 0x6114, "FL", "Mask Sub-Pixel Shift" }, { 0x0028, 0x6120, "SS", "TID Offset" }, { 0x0028, 0x6190, "ST", "Mask Operation Explanation" }, { 0x0029, 0x0000, "xs", "?" }, { 0x0029, 0x0001, "xs", "?" }, { 0x0029, 0x0002, "xs", "?" }, { 0x0029, 0x0003, "xs", "?" }, { 0x0029, 0x0004, "xs", "?" }, { 0x0029, 0x0005, "xs", "?" }, { 0x0029, 0x0006, "xs", "?" }, { 0x0029, 0x0007, "SL", "Lower Range Of Pixels" }, { 0x0029, 0x0008, "SH", "Lower Range Of Pixels" }, { 0x0029, 0x0009, "SH", "Lower Range Of Pixels" }, { 0x0029, 0x000a, "SS", "Lower Range Of Pixels" }, { 0x0029, 0x000c, "xs", "?" }, { 0x0029, 0x000e, "CS", "Zoom Enable Status" }, { 0x0029, 0x000f, "CS", "Zoom Select Status" }, { 0x0029, 0x0010, "xs", "?" }, { 0x0029, 0x0011, "xs", "?" }, { 0x0029, 0x0013, "LT", "?" }, { 0x0029, 0x0015, "xs", "?" }, { 0x0029, 0x0016, "SL", "Lower Range Of Pixels" }, { 0x0029, 0x0017, "SL", "Lower Range Of Pixels" }, { 0x0029, 0x0018, "SL", "Upper Range Of Pixels" }, { 0x0029, 0x001a, "SL", "Length Of Total Info In Bytes" }, { 0x0029, 0x001e, "xs", "?" }, { 0x0029, 0x001f, "xs", "?" }, { 0x0029, 0x0020, "xs", "?" }, { 0x0029, 0x0022, "IS", "Pixel Quality Value" }, { 0x0029, 0x0025, "LT", "Processed Pixel Data Quality" }, { 0x0029, 0x0026, "SS", "Version Of Info Structure" }, { 0x0029, 0x0030, "xs", "?" }, { 0x0029, 0x0031, "xs", "?" }, { 0x0029, 0x0032, "xs", "?" }, { 0x0029, 0x0033, "xs", "?" }, { 0x0029, 0x0034, "xs", "?" }, { 0x0029, 0x0035, "SL", "Advantage Comp Underflow" }, { 0x0029, 0x0038, "US", "?" }, { 0x0029, 0x0040, "xs", "?" }, { 0x0029, 0x0041, "DS", "Magnifying Glass Rectangle" }, { 0x0029, 0x0043, "DS", "Magnifying Glass Factor" }, { 0x0029, 0x0044, "US", "Magnifying Glass Function" }, { 0x0029, 0x004e, "CS", "Magnifying Glass Enable Status" }, { 0x0029, 0x004f, "CS", "Magnifying Glass Select Status" }, { 0x0029, 0x0050, "xs", "?" }, { 0x0029, 0x0051, "LT", "Exposure Code" }, { 0x0029, 0x0052, "LT", "Sort Code" }, { 0x0029, 0x0053, "LT", "?" }, { 0x0029, 0x0060, "xs", "?" }, { 0x0029, 0x0061, "xs", "?" }, { 0x0029, 0x0067, "LT", "?" }, { 0x0029, 0x0070, "xs", "?" }, { 0x0029, 0x0071, "xs", "?" }, { 0x0029, 0x0072, "xs", "?" }, { 0x0029, 0x0077, "CS", "Window Select Status" }, { 0x0029, 0x0078, "LT", "ECG Display Printing ID" }, { 0x0029, 0x0079, "CS", "ECG Display Printing" }, { 0x0029, 0x007e, "CS", "ECG Display Printing Enable Status" }, { 0x0029, 0x007f, "CS", "ECG Display Printing Select Status" }, { 0x0029, 0x0080, "xs", "?" }, { 0x0029, 0x0081, "xs", "?" }, { 0x0029, 0x0082, "IS", "View Zoom" }, { 0x0029, 0x0083, "IS", "View Transform" }, { 0x0029, 0x008e, "CS", "Physiological Display Enable Status" }, { 0x0029, 0x008f, "CS", "Physiological Display Select Status" }, { 0x0029, 0x0090, "IS", "?" }, { 0x0029, 0x0099, "LT", "Shutter Type" }, { 0x0029, 0x00a0, "US", "Rows of Rectangular Shutter" }, { 0x0029, 0x00a1, "US", "Columns of Rectangular Shutter" }, { 0x0029, 0x00a2, "US", "Origin of Rectangular Shutter" }, { 0x0029, 0x00b0, "US", "Radius of Circular Shutter" }, { 0x0029, 0x00b2, "US", "Origin of Circular Shutter" }, { 0x0029, 0x00c0, "LT", "Functional Shutter ID" }, { 0x0029, 0x00c1, "xs", "?" }, { 0x0029, 0x00c3, "IS", "Scan Resolution" }, { 0x0029, 0x00c4, "IS", "Field of View" }, { 0x0029, 0x00c5, "LT", "Field Of Shutter Rectangle" }, { 0x0029, 0x00ce, "CS", "Shutter Enable Status" }, { 0x0029, 0x00cf, "CS", "Shutter Select Status" }, { 0x0029, 0x00d0, "IS", "?" }, { 0x0029, 0x00d1, "IS", "?" }, { 0x0029, 0x00d5, "LT", "Slice Thickness" }, { 0x0031, 0x0010, "LT", "Request UID" }, { 0x0031, 0x0012, "LT", "Examination Reason" }, { 0x0031, 0x0030, "DA", "Requested Date" }, { 0x0031, 0x0032, "TM", "Worklist Request Start Time" }, { 0x0031, 0x0033, "TM", "Worklist Request End Time" }, { 0x0031, 0x0045, "LT", "Requesting Physician" }, { 0x0031, 0x004a, "TM", "Requested Time" }, { 0x0031, 0x0050, "LT", "Requested Physician" }, { 0x0031, 0x0080, "LT", "Requested Location" }, { 0x0032, 0x0000, "UL", "Study Group Length" }, { 0x0032, 0x000a, "CS", "Study Status ID" }, { 0x0032, 0x000c, "CS", "Study Priority ID" }, { 0x0032, 0x0012, "LO", "Study ID Issuer" }, { 0x0032, 0x0032, "DA", "Study Verified Date" }, { 0x0032, 0x0033, "TM", "Study Verified Time" }, { 0x0032, 0x0034, "DA", "Study Read Date" }, { 0x0032, 0x0035, "TM", "Study Read Time" }, { 0x0032, 0x1000, "DA", "Scheduled Study Start Date" }, { 0x0032, 0x1001, "TM", "Scheduled Study Start Time" }, { 0x0032, 0x1010, "DA", "Scheduled Study Stop Date" }, { 0x0032, 0x1011, "TM", "Scheduled Study Stop Time" }, { 0x0032, 0x1020, "LO", "Scheduled Study Location" }, { 0x0032, 0x1021, "AE", "Scheduled Study Location AE Title(s)" }, { 0x0032, 0x1030, "LO", "Reason for Study" }, { 0x0032, 0x1032, "PN", "Requesting Physician" }, { 0x0032, 0x1033, "LO", "Requesting Service" }, { 0x0032, 0x1040, "DA", "Study Arrival Date" }, { 0x0032, 0x1041, "TM", "Study Arrival Time" }, { 0x0032, 0x1050, "DA", "Study Completion Date" }, { 0x0032, 0x1051, "TM", "Study Completion Time" }, { 0x0032, 0x1055, "CS", "Study Component Status ID" }, { 0x0032, 0x1060, "LO", "Requested Procedure Description" }, { 0x0032, 0x1064, "SQ", "Requested Procedure Code Sequence" }, { 0x0032, 0x1070, "LO", "Requested Contrast Agent" }, { 0x0032, 0x4000, "LT", "Study Comments" }, { 0x0033, 0x0001, "UN", "?" }, { 0x0033, 0x0002, "UN", "?" }, { 0x0033, 0x0005, "UN", "?" }, { 0x0033, 0x0006, "UN", "?" }, { 0x0033, 0x0010, "LT", "Patient Study UID" }, { 0x0037, 0x0010, "LO", "ReferringDepartment" }, { 0x0037, 0x0020, "US", "ScreenNumber" }, { 0x0037, 0x0040, "SH", "LeftOrientation" }, { 0x0037, 0x0042, "SH", "RightOrientation" }, { 0x0037, 0x0050, "CS", "Inversion" }, { 0x0037, 0x0060, "US", "DSA" }, { 0x0038, 0x0000, "UL", "Visit Group Length" }, { 0x0038, 0x0004, "SQ", "Referenced Patient Alias Sequence" }, { 0x0038, 0x0008, "CS", "Visit Status ID" }, { 0x0038, 0x0010, "LO", "Admission ID" }, { 0x0038, 0x0011, "LO", "Issuer of Admission ID" }, { 0x0038, 0x0016, "LO", "Route of Admissions" }, { 0x0038, 0x001a, "DA", "Scheduled Admission Date" }, { 0x0038, 0x001b, "TM", "Scheduled Admission Time" }, { 0x0038, 0x001c, "DA", "Scheduled Discharge Date" }, { 0x0038, 0x001d, "TM", "Scheduled Discharge Time" }, { 0x0038, 0x001e, "LO", "Scheduled Patient Institution Residence" }, { 0x0038, 0x0020, "DA", "Admitting Date" }, { 0x0038, 0x0021, "TM", "Admitting Time" }, { 0x0038, 0x0030, "DA", "Discharge Date" }, { 0x0038, 0x0032, "TM", "Discharge Time" }, { 0x0038, 0x0040, "LO", "Discharge Diagnosis Description" }, { 0x0038, 0x0044, "SQ", "Discharge Diagnosis Code Sequence" }, { 0x0038, 0x0050, "LO", "Special Needs" }, { 0x0038, 0x0300, "LO", "Current Patient Location" }, { 0x0038, 0x0400, "LO", "Patient's Institution Residence" }, { 0x0038, 0x0500, "LO", "Patient State" }, { 0x0038, 0x4000, "LT", "Visit Comments" }, { 0x0039, 0x0080, "IS", "Private Entity Number" }, { 0x0039, 0x0085, "DA", "Private Entity Date" }, { 0x0039, 0x0090, "TM", "Private Entity Time" }, { 0x0039, 0x0095, "LO", "Private Entity Launch Command" }, { 0x0039, 0x00aa, "CS", "Private Entity Type" }, { 0x003a, 0x0002, "SQ", "Waveform Sequence" }, { 0x003a, 0x0005, "US", "Waveform Number of Channels" }, { 0x003a, 0x0010, "UL", "Waveform Number of Samples" }, { 0x003a, 0x001a, "DS", "Sampling Frequency" }, { 0x003a, 0x0020, "SH", "Group Label" }, { 0x003a, 0x0103, "CS", "Waveform Sample Value Representation" }, { 0x003a, 0x0122, "OB", "Waveform Padding Value" }, { 0x003a, 0x0200, "SQ", "Channel Definition" }, { 0x003a, 0x0202, "IS", "Waveform Channel Number" }, { 0x003a, 0x0203, "SH", "Channel Label" }, { 0x003a, 0x0205, "CS", "Channel Status" }, { 0x003a, 0x0208, "SQ", "Channel Source" }, { 0x003a, 0x0209, "SQ", "Channel Source Modifiers" }, { 0x003a, 0x020a, "SQ", "Differential Channel Source" }, { 0x003a, 0x020b, "SQ", "Differential Channel Source Modifiers" }, { 0x003a, 0x0210, "DS", "Channel Sensitivity" }, { 0x003a, 0x0211, "SQ", "Channel Sensitivity Units" }, { 0x003a, 0x0212, "DS", "Channel Sensitivity Correction Factor" }, { 0x003a, 0x0213, "DS", "Channel Baseline" }, { 0x003a, 0x0214, "DS", "Channel Time Skew" }, { 0x003a, 0x0215, "DS", "Channel Sample Skew" }, { 0x003a, 0x0216, "OB", "Channel Minimum Value" }, { 0x003a, 0x0217, "OB", "Channel Maximum Value" }, { 0x003a, 0x0218, "DS", "Channel Offset" }, { 0x003a, 0x021a, "US", "Bits Per Sample" }, { 0x003a, 0x0220, "DS", "Filter Low Frequency" }, { 0x003a, 0x0221, "DS", "Filter High Frequency" }, { 0x003a, 0x0222, "DS", "Notch Filter Frequency" }, { 0x003a, 0x0223, "DS", "Notch Filter Bandwidth" }, { 0x003a, 0x1000, "OB", "Waveform Data" }, { 0x0040, 0x0001, "AE", "Scheduled Station AE Title" }, { 0x0040, 0x0002, "DA", "Scheduled Procedure Step Start Date" }, { 0x0040, 0x0003, "TM", "Scheduled Procedure Step Start Time" }, { 0x0040, 0x0004, "DA", "Scheduled Procedure Step End Date" }, { 0x0040, 0x0005, "TM", "Scheduled Procedure Step End Time" }, { 0x0040, 0x0006, "PN", "Scheduled Performing Physician Name" }, { 0x0040, 0x0007, "LO", "Scheduled Procedure Step Description" }, { 0x0040, 0x0008, "SQ", "Scheduled Action Item Code Sequence" }, { 0x0040, 0x0009, "SH", "Scheduled Procedure Step ID" }, { 0x0040, 0x0010, "SH", "Scheduled Station Name" }, { 0x0040, 0x0011, "SH", "Scheduled Procedure Step Location" }, { 0x0040, 0x0012, "LO", "Pre-Medication" }, { 0x0040, 0x0020, "CS", "Scheduled Procedure Step Status" }, { 0x0040, 0x0100, "SQ", "Scheduled Procedure Step Sequence" }, { 0x0040, 0x0302, "US", "Entrance Dose" }, { 0x0040, 0x0303, "US", "Exposed Area" }, { 0x0040, 0x0306, "DS", "Distance Source to Entrance" }, { 0x0040, 0x0307, "DS", "Distance Source to Support" }, { 0x0040, 0x0310, "ST", "Comments On Radiation Dose" }, { 0x0040, 0x0312, "DS", "X-Ray Output" }, { 0x0040, 0x0314, "DS", "Half Value Layer" }, { 0x0040, 0x0316, "DS", "Organ Dose" }, { 0x0040, 0x0318, "CS", "Organ Exposed" }, { 0x0040, 0x0400, "LT", "Comments On Scheduled Procedure Step" }, { 0x0040, 0x050a, "LO", "Specimen Accession Number" }, { 0x0040, 0x0550, "SQ", "Specimen Sequence" }, { 0x0040, 0x0551, "LO", "Specimen Identifier" }, { 0x0040, 0x0552, "SQ", "Specimen Description Sequence" }, { 0x0040, 0x0553, "ST", "Specimen Description" }, { 0x0040, 0x0555, "SQ", "Acquisition Context Sequence" }, { 0x0040, 0x0556, "ST", "Acquisition Context Description" }, { 0x0040, 0x059a, "SQ", "Specimen Type Code Sequence" }, { 0x0040, 0x06fa, "LO", "Slide Identifier" }, { 0x0040, 0x071a, "SQ", "Image Center Point Coordinates Sequence" }, { 0x0040, 0x072a, "DS", "X Offset In Slide Coordinate System" }, { 0x0040, 0x073a, "DS", "Y Offset In Slide Coordinate System" }, { 0x0040, 0x074a, "DS", "Z Offset In Slide Coordinate System" }, { 0x0040, 0x08d8, "SQ", "Pixel Spacing Sequence" }, { 0x0040, 0x08da, "SQ", "Coordinate System Axis Code Sequence" }, { 0x0040, 0x08ea, "SQ", "Measurement Units Code Sequence" }, { 0x0040, 0x09f8, "SQ", "Vital Stain Code Sequence" }, { 0x0040, 0x1001, "SH", "Requested Procedure ID" }, { 0x0040, 0x1002, "LO", "Reason For Requested Procedure" }, { 0x0040, 0x1003, "SH", "Requested Procedure Priority" }, { 0x0040, 0x1004, "LO", "Patient Transport Arrangements" }, { 0x0040, 0x1005, "LO", "Requested Procedure Location" }, { 0x0040, 0x1006, "SH", "Placer Order Number of Procedure" }, { 0x0040, 0x1007, "SH", "Filler Order Number of Procedure" }, { 0x0040, 0x1008, "LO", "Confidentiality Code" }, { 0x0040, 0x1009, "SH", "Reporting Priority" }, { 0x0040, 0x1010, "PN", "Names of Intended Recipients of Results" }, { 0x0040, 0x1400, "LT", "Requested Procedure Comments" }, { 0x0040, 0x2001, "LO", "Reason For Imaging Service Request" }, { 0x0040, 0x2004, "DA", "Issue Date of Imaging Service Request" }, { 0x0040, 0x2005, "TM", "Issue Time of Imaging Service Request" }, { 0x0040, 0x2006, "SH", "Placer Order Number of Imaging Service Request" }, { 0x0040, 0x2007, "SH", "Filler Order Number of Imaging Service Request" }, { 0x0040, 0x2008, "PN", "Order Entered By" }, { 0x0040, 0x2009, "SH", "Order Enterer Location" }, { 0x0040, 0x2010, "SH", "Order Callback Phone Number" }, { 0x0040, 0x2400, "LT", "Imaging Service Request Comments" }, { 0x0040, 0x3001, "LO", "Confidentiality Constraint On Patient Data" }, { 0x0040, 0xa007, "CS", "Findings Flag" }, { 0x0040, 0xa020, "SQ", "Findings Sequence" }, { 0x0040, 0xa021, "UI", "Findings Group UID" }, { 0x0040, 0xa022, "UI", "Referenced Findings Group UID" }, { 0x0040, 0xa023, "DA", "Findings Group Recording Date" }, { 0x0040, 0xa024, "TM", "Findings Group Recording Time" }, { 0x0040, 0xa026, "SQ", "Findings Source Category Code Sequence" }, { 0x0040, 0xa027, "LO", "Documenting Organization" }, { 0x0040, 0xa028, "SQ", "Documenting Organization Identifier Code Sequence" }, { 0x0040, 0xa032, "LO", "History Reliability Qualifier Description" }, { 0x0040, 0xa043, "SQ", "Concept Name Code Sequence" }, { 0x0040, 0xa047, "LO", "Measurement Precision Description" }, { 0x0040, 0xa057, "CS", "Urgency or Priority Alerts" }, { 0x0040, 0xa060, "LO", "Sequencing Indicator" }, { 0x0040, 0xa066, "SQ", "Document Identifier Code Sequence" }, { 0x0040, 0xa067, "PN", "Document Author" }, { 0x0040, 0xa068, "SQ", "Document Author Identifier Code Sequence" }, { 0x0040, 0xa070, "SQ", "Identifier Code Sequence" }, { 0x0040, 0xa073, "LO", "Object String Identifier" }, { 0x0040, 0xa074, "OB", "Object Binary Identifier" }, { 0x0040, 0xa075, "PN", "Documenting Observer" }, { 0x0040, 0xa076, "SQ", "Documenting Observer Identifier Code Sequence" }, { 0x0040, 0xa078, "SQ", "Observation Subject Identifier Code Sequence" }, { 0x0040, 0xa080, "SQ", "Person Identifier Code Sequence" }, { 0x0040, 0xa085, "SQ", "Procedure Identifier Code Sequence" }, { 0x0040, 0xa088, "LO", "Object Directory String Identifier" }, { 0x0040, 0xa089, "OB", "Object Directory Binary Identifier" }, { 0x0040, 0xa090, "CS", "History Reliability Qualifier" }, { 0x0040, 0xa0a0, "CS", "Referenced Type of Data" }, { 0x0040, 0xa0b0, "US", "Referenced Waveform Channels" }, { 0x0040, 0xa110, "DA", "Date of Document or Verbal Transaction" }, { 0x0040, 0xa112, "TM", "Time of Document Creation or Verbal Transaction" }, { 0x0040, 0xa121, "DA", "Date" }, { 0x0040, 0xa122, "TM", "Time" }, { 0x0040, 0xa123, "PN", "Person Name" }, { 0x0040, 0xa124, "SQ", "Referenced Person Sequence" }, { 0x0040, 0xa125, "CS", "Report Status ID" }, { 0x0040, 0xa130, "CS", "Temporal Range Type" }, { 0x0040, 0xa132, "UL", "Referenced Sample Offsets" }, { 0x0040, 0xa136, "US", "Referenced Frame Numbers" }, { 0x0040, 0xa138, "DS", "Referenced Time Offsets" }, { 0x0040, 0xa13a, "DT", "Referenced Datetime" }, { 0x0040, 0xa160, "UT", "Text Value" }, { 0x0040, 0xa167, "SQ", "Observation Category Code Sequence" }, { 0x0040, 0xa168, "SQ", "Concept Code Sequence" }, { 0x0040, 0xa16a, "ST", "Bibliographic Citation" }, { 0x0040, 0xa170, "CS", "Observation Class" }, { 0x0040, 0xa171, "UI", "Observation UID" }, { 0x0040, 0xa172, "UI", "Referenced Observation UID" }, { 0x0040, 0xa173, "CS", "Referenced Observation Class" }, { 0x0040, 0xa174, "CS", "Referenced Object Observation Class" }, { 0x0040, 0xa180, "US", "Annotation Group Number" }, { 0x0040, 0xa192, "DA", "Observation Date" }, { 0x0040, 0xa193, "TM", "Observation Time" }, { 0x0040, 0xa194, "CS", "Measurement Automation" }, { 0x0040, 0xa195, "SQ", "Concept Name Code Sequence Modifier" }, { 0x0040, 0xa224, "ST", "Identification Description" }, { 0x0040, 0xa290, "CS", "Coordinates Set Geometric Type" }, { 0x0040, 0xa296, "SQ", "Algorithm Code Sequence" }, { 0x0040, 0xa297, "ST", "Algorithm Description" }, { 0x0040, 0xa29a, "SL", "Pixel Coordinates Set" }, { 0x0040, 0xa300, "SQ", "Measured Value Sequence" }, { 0x0040, 0xa307, "PN", "Current Observer" }, { 0x0040, 0xa30a, "DS", "Numeric Value" }, { 0x0040, 0xa313, "SQ", "Referenced Accession Sequence" }, { 0x0040, 0xa33a, "ST", "Report Status Comment" }, { 0x0040, 0xa340, "SQ", "Procedure Context Sequence" }, { 0x0040, 0xa352, "PN", "Verbal Source" }, { 0x0040, 0xa353, "ST", "Address" }, { 0x0040, 0xa354, "LO", "Telephone Number" }, { 0x0040, 0xa358, "SQ", "Verbal Source Identifier Code Sequence" }, { 0x0040, 0xa380, "SQ", "Report Detail Sequence" }, { 0x0040, 0xa402, "UI", "Observation Subject UID" }, { 0x0040, 0xa403, "CS", "Observation Subject Class" }, { 0x0040, 0xa404, "SQ", "Observation Subject Type Code Sequence" }, { 0x0040, 0xa600, "CS", "Observation Subject Context Flag" }, { 0x0040, 0xa601, "CS", "Observer Context Flag" }, { 0x0040, 0xa603, "CS", "Procedure Context Flag" }, { 0x0040, 0xa730, "SQ", "Observations Sequence" }, { 0x0040, 0xa731, "SQ", "Relationship Sequence" }, { 0x0040, 0xa732, "SQ", "Relationship Type Code Sequence" }, { 0x0040, 0xa744, "SQ", "Language Code Sequence" }, { 0x0040, 0xa992, "ST", "Uniform Resource Locator" }, { 0x0040, 0xb020, "SQ", "Annotation Sequence" }, { 0x0040, 0xdb73, "SQ", "Relationship Type Code Sequence Modifier" }, { 0x0041, 0x0000, "LT", "Papyrus Comments" }, { 0x0041, 0x0010, "xs", "?" }, { 0x0041, 0x0011, "xs", "?" }, { 0x0041, 0x0012, "UL", "Pixel Offset" }, { 0x0041, 0x0013, "SQ", "Image Identifier Sequence" }, { 0x0041, 0x0014, "SQ", "External File Reference Sequence" }, { 0x0041, 0x0015, "US", "Number of Images" }, { 0x0041, 0x0020, "xs", "?" }, { 0x0041, 0x0021, "UI", "Referenced SOP Class UID" }, { 0x0041, 0x0022, "UI", "Referenced SOP Instance UID" }, { 0x0041, 0x0030, "xs", "?" }, { 0x0041, 0x0031, "xs", "?" }, { 0x0041, 0x0032, "xs", "?" }, { 0x0041, 0x0034, "DA", "Modified Date" }, { 0x0041, 0x0036, "TM", "Modified Time" }, { 0x0041, 0x0040, "LT", "Owner Name" }, { 0x0041, 0x0041, "UI", "Referenced Image SOP Class UID" }, { 0x0041, 0x0042, "UI", "Referenced Image SOP Instance UID" }, { 0x0041, 0x0050, "xs", "?" }, { 0x0041, 0x0060, "UL", "Number of Images" }, { 0x0041, 0x0062, "UL", "Number of Other" }, { 0x0041, 0x00a0, "LT", "External Folder Element DSID" }, { 0x0041, 0x00a1, "US", "External Folder Element Data Set Type" }, { 0x0041, 0x00a2, "LT", "External Folder Element File Location" }, { 0x0041, 0x00a3, "UL", "External Folder Element Length" }, { 0x0041, 0x00b0, "LT", "Internal Folder Element DSID" }, { 0x0041, 0x00b1, "US", "Internal Folder Element Data Set Type" }, { 0x0041, 0x00b2, "UL", "Internal Offset To Data Set" }, { 0x0041, 0x00b3, "UL", "Internal Offset To Image" }, { 0x0043, 0x0001, "SS", "Bitmap Of Prescan Options" }, { 0x0043, 0x0002, "SS", "Gradient Offset In X" }, { 0x0043, 0x0003, "SS", "Gradient Offset In Y" }, { 0x0043, 0x0004, "SS", "Gradient Offset In Z" }, { 0x0043, 0x0005, "SS", "Image Is Original Or Unoriginal" }, { 0x0043, 0x0006, "SS", "Number Of EPI Shots" }, { 0x0043, 0x0007, "SS", "Views Per Segment" }, { 0x0043, 0x0008, "SS", "Respiratory Rate In BPM" }, { 0x0043, 0x0009, "SS", "Respiratory Trigger Point" }, { 0x0043, 0x000a, "SS", "Type Of Receiver Used" }, { 0x0043, 0x000b, "DS", "Peak Rate Of Change Of Gradient Field" }, { 0x0043, 0x000c, "DS", "Limits In Units Of Percent" }, { 0x0043, 0x000d, "DS", "PSD Estimated Limit" }, { 0x0043, 0x000e, "DS", "PSD Estimated Limit In Tesla Per Second" }, { 0x0043, 0x000f, "DS", "SAR Avg Head" }, { 0x0043, 0x0010, "US", "Window Value" }, { 0x0043, 0x0011, "US", "Total Input Views" }, { 0x0043, 0x0012, "SS", "Xray Chain" }, { 0x0043, 0x0013, "SS", "Recon Kernel Parameters" }, { 0x0043, 0x0014, "SS", "Calibration Parameters" }, { 0x0043, 0x0015, "SS", "Total Output Views" }, { 0x0043, 0x0016, "SS", "Number Of Overranges" }, { 0x0043, 0x0017, "DS", "IBH Image Scale Factors" }, { 0x0043, 0x0018, "DS", "BBH Coefficients" }, { 0x0043, 0x0019, "SS", "Number Of BBH Chains To Blend" }, { 0x0043, 0x001a, "SL", "Starting Channel Number" }, { 0x0043, 0x001b, "SS", "PPScan Parameters" }, { 0x0043, 0x001c, "SS", "GE Image Integrity" }, { 0x0043, 0x001d, "SS", "Level Value" }, { 0x0043, 0x001e, "xs", "?" }, { 0x0043, 0x001f, "SL", "Max Overranges In A View" }, { 0x0043, 0x0020, "DS", "Avg Overranges All Views" }, { 0x0043, 0x0021, "SS", "Corrected Afterglow Terms" }, { 0x0043, 0x0025, "SS", "Reference Channels" }, { 0x0043, 0x0026, "US", "No Views Ref Channels Blocked" }, { 0x0043, 0x0027, "xs", "?" }, { 0x0043, 0x0028, "OB", "Unique Image Identifier" }, { 0x0043, 0x0029, "OB", "Histogram Tables" }, { 0x0043, 0x002a, "OB", "User Defined Data" }, { 0x0043, 0x002b, "SS", "Private Scan Options" }, { 0x0043, 0x002c, "SS", "Effective Echo Spacing" }, { 0x0043, 0x002d, "SH", "String Slop Field 1" }, { 0x0043, 0x002e, "SH", "String Slop Field 2" }, { 0x0043, 0x002f, "SS", "Raw Data Type" }, { 0x0043, 0x0030, "SS", "Raw Data Type" }, { 0x0043, 0x0031, "DS", "RA Coord Of Target Recon Centre" }, { 0x0043, 0x0032, "SS", "Raw Data Type" }, { 0x0043, 0x0033, "FL", "Neg Scan Spacing" }, { 0x0043, 0x0034, "IS", "Offset Frequency" }, { 0x0043, 0x0035, "UL", "User Usage Tag" }, { 0x0043, 0x0036, "UL", "User Fill Map MSW" }, { 0x0043, 0x0037, "UL", "User Fill Map LSW" }, { 0x0043, 0x0038, "FL", "User 25 To User 48" }, { 0x0043, 0x0039, "IS", "Slop Integer 6 To Slop Integer 9" }, { 0x0043, 0x0040, "FL", "Trigger On Position" }, { 0x0043, 0x0041, "FL", "Degree Of Rotation" }, { 0x0043, 0x0042, "SL", "DAS Trigger Source" }, { 0x0043, 0x0043, "SL", "DAS Fpa Gain" }, { 0x0043, 0x0044, "SL", "DAS Output Source" }, { 0x0043, 0x0045, "SL", "DAS Ad Input" }, { 0x0043, 0x0046, "SL", "DAS Cal Mode" }, { 0x0043, 0x0047, "SL", "DAS Cal Frequency" }, { 0x0043, 0x0048, "SL", "DAS Reg Xm" }, { 0x0043, 0x0049, "SL", "DAS Auto Zero" }, { 0x0043, 0x004a, "SS", "Starting Channel Of View" }, { 0x0043, 0x004b, "SL", "DAS Xm Pattern" }, { 0x0043, 0x004c, "SS", "TGGC Trigger Mode" }, { 0x0043, 0x004d, "FL", "Start Scan To Xray On Delay" }, { 0x0043, 0x004e, "FL", "Duration Of Xray On" }, { 0x0044, 0x0000, "UI", "?" }, { 0x0045, 0x0004, "CS", "AES" }, { 0x0045, 0x0006, "DS", "Angulation" }, { 0x0045, 0x0009, "DS", "Real Magnification Factor" }, { 0x0045, 0x000b, "CS", "Senograph Type" }, { 0x0045, 0x000c, "DS", "Integration Time" }, { 0x0045, 0x000d, "DS", "ROI Origin X and Y" }, { 0x0045, 0x0011, "DS", "Receptor Size cm X and Y" }, { 0x0045, 0x0012, "IS", "Receptor Size Pixels X and Y" }, { 0x0045, 0x0013, "ST", "Screen" }, { 0x0045, 0x0014, "DS", "Pixel Pitch Microns" }, { 0x0045, 0x0015, "IS", "Pixel Depth Bits" }, { 0x0045, 0x0016, "IS", "Binning Factor X and Y" }, { 0x0045, 0x001b, "CS", "Clinical View" }, { 0x0045, 0x001d, "DS", "Mean Of Raw Gray Levels" }, { 0x0045, 0x001e, "DS", "Mean Of Offset Gray Levels" }, { 0x0045, 0x001f, "DS", "Mean Of Corrected Gray Levels" }, { 0x0045, 0x0020, "DS", "Mean Of Region Gray Levels" }, { 0x0045, 0x0021, "DS", "Mean Of Log Region Gray Levels" }, { 0x0045, 0x0022, "DS", "Standard Deviation Of Raw Gray Levels" }, { 0x0045, 0x0023, "DS", "Standard Deviation Of Corrected Gray Levels" }, { 0x0045, 0x0024, "DS", "Standard Deviation Of Region Gray Levels" }, { 0x0045, 0x0025, "DS", "Standard Deviation Of Log Region Gray Levels" }, { 0x0045, 0x0026, "OB", "MAO Buffer" }, { 0x0045, 0x0027, "IS", "Set Number" }, { 0x0045, 0x0028, "CS", "WindowingType (LINEAR or GAMMA)" }, { 0x0045, 0x0029, "DS", "WindowingParameters" }, { 0x0045, 0x002a, "IS", "Crosshair Cursor X Coordinates" }, { 0x0045, 0x002b, "IS", "Crosshair Cursor Y Coordinates" }, { 0x0045, 0x0039, "US", "Vignette Rows" }, { 0x0045, 0x003a, "US", "Vignette Columns" }, { 0x0045, 0x003b, "US", "Vignette Bits Allocated" }, { 0x0045, 0x003c, "US", "Vignette Bits Stored" }, { 0x0045, 0x003d, "US", "Vignette High Bit" }, { 0x0045, 0x003e, "US", "Vignette Pixel Representation" }, { 0x0045, 0x003f, "OB", "Vignette Pixel Data" }, { 0x0047, 0x0001, "SQ", "Reconstruction Parameters Sequence" }, { 0x0047, 0x0050, "UL", "Volume Voxel Count" }, { 0x0047, 0x0051, "UL", "Volume Segment Count" }, { 0x0047, 0x0053, "US", "Volume Slice Size" }, { 0x0047, 0x0054, "US", "Volume Slice Count" }, { 0x0047, 0x0055, "SL", "Volume Threshold Value" }, { 0x0047, 0x0057, "DS", "Volume Voxel Ratio" }, { 0x0047, 0x0058, "DS", "Volume Voxel Size" }, { 0x0047, 0x0059, "US", "Volume Z Position Size" }, { 0x0047, 0x0060, "DS", "Volume Base Line" }, { 0x0047, 0x0061, "DS", "Volume Center Point" }, { 0x0047, 0x0063, "SL", "Volume Skew Base" }, { 0x0047, 0x0064, "DS", "Volume Registration Transform Rotation Matrix" }, { 0x0047, 0x0065, "DS", "Volume Registration Transform Translation Vector" }, { 0x0047, 0x0070, "DS", "KVP List" }, { 0x0047, 0x0071, "IS", "XRay Tube Current List" }, { 0x0047, 0x0072, "IS", "Exposure List" }, { 0x0047, 0x0080, "LO", "Acquisition DLX Identifier" }, { 0x0047, 0x0085, "SQ", "Acquisition DLX 2D Series Sequence" }, { 0x0047, 0x0089, "DS", "Contrast Agent Volume List" }, { 0x0047, 0x008a, "US", "Number Of Injections" }, { 0x0047, 0x008b, "US", "Frame Count" }, { 0x0047, 0x0096, "IS", "Used Frames" }, { 0x0047, 0x0091, "LO", "XA 3D Reconstruction Algorithm Name" }, { 0x0047, 0x0092, "CS", "XA 3D Reconstruction Algorithm Version" }, { 0x0047, 0x0093, "DA", "DLX Calibration Date" }, { 0x0047, 0x0094, "TM", "DLX Calibration Time" }, { 0x0047, 0x0095, "CS", "DLX Calibration Status" }, { 0x0047, 0x0098, "US", "Transform Count" }, { 0x0047, 0x0099, "SQ", "Transform Sequence" }, { 0x0047, 0x009a, "DS", "Transform Rotation Matrix" }, { 0x0047, 0x009b, "DS", "Transform Translation Vector" }, { 0x0047, 0x009c, "LO", "Transform Label" }, { 0x0047, 0x00b1, "US", "Wireframe Count" }, { 0x0047, 0x00b2, "US", "Location System" }, { 0x0047, 0x00b0, "SQ", "Wireframe List" }, { 0x0047, 0x00b5, "LO", "Wireframe Name" }, { 0x0047, 0x00b6, "LO", "Wireframe Group Name" }, { 0x0047, 0x00b7, "LO", "Wireframe Color" }, { 0x0047, 0x00b8, "SL", "Wireframe Attributes" }, { 0x0047, 0x00b9, "SL", "Wireframe Point Count" }, { 0x0047, 0x00ba, "SL", "Wireframe Timestamp" }, { 0x0047, 0x00bb, "SQ", "Wireframe Point List" }, { 0x0047, 0x00bc, "DS", "Wireframe Points Coordinates" }, { 0x0047, 0x00c0, "DS", "Volume Upper Left High Corner RAS" }, { 0x0047, 0x00c1, "DS", "Volume Slice To RAS Rotation Matrix" }, { 0x0047, 0x00c2, "DS", "Volume Upper Left High Corner TLOC" }, { 0x0047, 0x00d1, "OB", "Volume Segment List" }, { 0x0047, 0x00d2, "OB", "Volume Gradient List" }, { 0x0047, 0x00d3, "OB", "Volume Density List" }, { 0x0047, 0x00d4, "OB", "Volume Z Position List" }, { 0x0047, 0x00d5, "OB", "Volume Original Index List" }, { 0x0050, 0x0000, "UL", "Calibration Group Length" }, { 0x0050, 0x0004, "CS", "Calibration Object" }, { 0x0050, 0x0010, "SQ", "DeviceSequence" }, { 0x0050, 0x0014, "DS", "DeviceLength" }, { 0x0050, 0x0016, "DS", "DeviceDiameter" }, { 0x0050, 0x0017, "CS", "DeviceDiameterUnits" }, { 0x0050, 0x0018, "DS", "DeviceVolume" }, { 0x0050, 0x0019, "DS", "InterMarkerDistance" }, { 0x0050, 0x0020, "LO", "DeviceDescription" }, { 0x0050, 0x0030, "SQ", "CodedInterventionDeviceSequence" }, { 0x0051, 0x0010, "xs", "Image Text" }, { 0x0054, 0x0000, "UL", "Nuclear Acquisition Group Length" }, { 0x0054, 0x0010, "US", "Energy Window Vector" }, { 0x0054, 0x0011, "US", "Number of Energy Windows" }, { 0x0054, 0x0012, "SQ", "Energy Window Information Sequence" }, { 0x0054, 0x0013, "SQ", "Energy Window Range Sequence" }, { 0x0054, 0x0014, "DS", "Energy Window Lower Limit" }, { 0x0054, 0x0015, "DS", "Energy Window Upper Limit" }, { 0x0054, 0x0016, "SQ", "Radiopharmaceutical Information Sequence" }, { 0x0054, 0x0017, "IS", "Residual Syringe Counts" }, { 0x0054, 0x0018, "SH", "Energy Window Name" }, { 0x0054, 0x0020, "US", "Detector Vector" }, { 0x0054, 0x0021, "US", "Number of Detectors" }, { 0x0054, 0x0022, "SQ", "Detector Information Sequence" }, { 0x0054, 0x0030, "US", "Phase Vector" }, { 0x0054, 0x0031, "US", "Number of Phases" }, { 0x0054, 0x0032, "SQ", "Phase Information Sequence" }, { 0x0054, 0x0033, "US", "Number of Frames In Phase" }, { 0x0054, 0x0036, "IS", "Phase Delay" }, { 0x0054, 0x0038, "IS", "Pause Between Frames" }, { 0x0054, 0x0050, "US", "Rotation Vector" }, { 0x0054, 0x0051, "US", "Number of Rotations" }, { 0x0054, 0x0052, "SQ", "Rotation Information Sequence" }, { 0x0054, 0x0053, "US", "Number of Frames In Rotation" }, { 0x0054, 0x0060, "US", "R-R Interval Vector" }, { 0x0054, 0x0061, "US", "Number of R-R Intervals" }, { 0x0054, 0x0062, "SQ", "Gated Information Sequence" }, { 0x0054, 0x0063, "SQ", "Data Information Sequence" }, { 0x0054, 0x0070, "US", "Time Slot Vector" }, { 0x0054, 0x0071, "US", "Number of Time Slots" }, { 0x0054, 0x0072, "SQ", "Time Slot Information Sequence" }, { 0x0054, 0x0073, "DS", "Time Slot Time" }, { 0x0054, 0x0080, "US", "Slice Vector" }, { 0x0054, 0x0081, "US", "Number of Slices" }, { 0x0054, 0x0090, "US", "Angular View Vector" }, { 0x0054, 0x0100, "US", "Time Slice Vector" }, { 0x0054, 0x0101, "US", "Number Of Time Slices" }, { 0x0054, 0x0200, "DS", "Start Angle" }, { 0x0054, 0x0202, "CS", "Type of Detector Motion" }, { 0x0054, 0x0210, "IS", "Trigger Vector" }, { 0x0054, 0x0211, "US", "Number of Triggers in Phase" }, { 0x0054, 0x0220, "SQ", "View Code Sequence" }, { 0x0054, 0x0222, "SQ", "View Modifier Code Sequence" }, { 0x0054, 0x0300, "SQ", "Radionuclide Code Sequence" }, { 0x0054, 0x0302, "SQ", "Radiopharmaceutical Route Code Sequence" }, { 0x0054, 0x0304, "SQ", "Radiopharmaceutical Code Sequence" }, { 0x0054, 0x0306, "SQ", "Calibration Data Sequence" }, { 0x0054, 0x0308, "US", "Energy Window Number" }, { 0x0054, 0x0400, "SH", "Image ID" }, { 0x0054, 0x0410, "SQ", "Patient Orientation Code Sequence" }, { 0x0054, 0x0412, "SQ", "Patient Orientation Modifier Code Sequence" }, { 0x0054, 0x0414, "SQ", "Patient Gantry Relationship Code Sequence" }, { 0x0054, 0x1000, "CS", "Positron Emission Tomography Series Type" }, { 0x0054, 0x1001, "CS", "Positron Emission Tomography Units" }, { 0x0054, 0x1002, "CS", "Counts Source" }, { 0x0054, 0x1004, "CS", "Reprojection Method" }, { 0x0054, 0x1100, "CS", "Randoms Correction Method" }, { 0x0054, 0x1101, "LO", "Attenuation Correction Method" }, { 0x0054, 0x1102, "CS", "Decay Correction" }, { 0x0054, 0x1103, "LO", "Reconstruction Method" }, { 0x0054, 0x1104, "LO", "Detector Lines of Response Used" }, { 0x0054, 0x1105, "LO", "Scatter Correction Method" }, { 0x0054, 0x1200, "DS", "Axial Acceptance" }, { 0x0054, 0x1201, "IS", "Axial Mash" }, { 0x0054, 0x1202, "IS", "Transverse Mash" }, { 0x0054, 0x1203, "DS", "Detector Element Size" }, { 0x0054, 0x1210, "DS", "Coincidence Window Width" }, { 0x0054, 0x1220, "CS", "Secondary Counts Type" }, { 0x0054, 0x1300, "DS", "Frame Reference Time" }, { 0x0054, 0x1310, "IS", "Primary Prompts Counts Accumulated" }, { 0x0054, 0x1311, "IS", "Secondary Counts Accumulated" }, { 0x0054, 0x1320, "DS", "Slice Sensitivity Factor" }, { 0x0054, 0x1321, "DS", "Decay Factor" }, { 0x0054, 0x1322, "DS", "Dose Calibration Factor" }, { 0x0054, 0x1323, "DS", "Scatter Fraction Factor" }, { 0x0054, 0x1324, "DS", "Dead Time Factor" }, { 0x0054, 0x1330, "US", "Image Index" }, { 0x0054, 0x1400, "CS", "Counts Included" }, { 0x0054, 0x1401, "CS", "Dead Time Correction Flag" }, { 0x0055, 0x0046, "LT", "Current Ward" }, { 0x0058, 0x0000, "SQ", "?" }, { 0x0060, 0x3000, "SQ", "Histogram Sequence" }, { 0x0060, 0x3002, "US", "Histogram Number of Bins" }, { 0x0060, 0x3004, "xs", "Histogram First Bin Value" }, { 0x0060, 0x3006, "xs", "Histogram Last Bin Value" }, { 0x0060, 0x3008, "US", "Histogram Bin Width" }, { 0x0060, 0x3010, "LO", "Histogram Explanation" }, { 0x0060, 0x3020, "UL", "Histogram Data" }, { 0x0070, 0x0001, "SQ", "Graphic Annotation Sequence" }, { 0x0070, 0x0002, "CS", "Graphic Layer" }, { 0x0070, 0x0003, "CS", "Bounding Box Annotation Units" }, { 0x0070, 0x0004, "CS", "Anchor Point Annotation Units" }, { 0x0070, 0x0005, "CS", "Graphic Annotation Units" }, { 0x0070, 0x0006, "ST", "Unformatted Text Value" }, { 0x0070, 0x0008, "SQ", "Text Object Sequence" }, { 0x0070, 0x0009, "SQ", "Graphic Object Sequence" }, { 0x0070, 0x0010, "FL", "Bounding Box TLHC" }, { 0x0070, 0x0011, "FL", "Bounding Box BRHC" }, { 0x0070, 0x0014, "FL", "Anchor Point" }, { 0x0070, 0x0015, "CS", "Anchor Point Visibility" }, { 0x0070, 0x0020, "US", "Graphic Dimensions" }, { 0x0070, 0x0021, "US", "Number Of Graphic Points" }, { 0x0070, 0x0022, "FL", "Graphic Data" }, { 0x0070, 0x0023, "CS", "Graphic Type" }, { 0x0070, 0x0024, "CS", "Graphic Filled" }, { 0x0070, 0x0040, "IS", "Image Rotation" }, { 0x0070, 0x0041, "CS", "Image Horizontal Flip" }, { 0x0070, 0x0050, "US", "Displayed Area TLHC" }, { 0x0070, 0x0051, "US", "Displayed Area BRHC" }, { 0x0070, 0x0060, "SQ", "Graphic Layer Sequence" }, { 0x0070, 0x0062, "IS", "Graphic Layer Order" }, { 0x0070, 0x0066, "US", "Graphic Layer Recommended Display Value" }, { 0x0070, 0x0068, "LO", "Graphic Layer Description" }, { 0x0070, 0x0080, "CS", "Presentation Label" }, { 0x0070, 0x0081, "LO", "Presentation Description" }, { 0x0070, 0x0082, "DA", "Presentation Creation Date" }, { 0x0070, 0x0083, "TM", "Presentation Creation Time" }, { 0x0070, 0x0084, "PN", "Presentation Creator's Name" }, { 0x0087, 0x0010, "CS", "Media Type" }, { 0x0087, 0x0020, "CS", "Media Location" }, { 0x0087, 0x0050, "IS", "Estimated Retrieve Time" }, { 0x0088, 0x0000, "UL", "Storage Group Length" }, { 0x0088, 0x0130, "SH", "Storage Media FileSet ID" }, { 0x0088, 0x0140, "UI", "Storage Media FileSet UID" }, { 0x0088, 0x0200, "SQ", "Icon Image Sequence" }, { 0x0088, 0x0904, "LO", "Topic Title" }, { 0x0088, 0x0906, "ST", "Topic Subject" }, { 0x0088, 0x0910, "LO", "Topic Author" }, { 0x0088, 0x0912, "LO", "Topic Key Words" }, { 0x0095, 0x0001, "LT", "Examination Folder ID" }, { 0x0095, 0x0004, "UL", "Folder Reported Status" }, { 0x0095, 0x0005, "LT", "Folder Reporting Radiologist" }, { 0x0095, 0x0007, "LT", "SIENET ISA PLA" }, { 0x0099, 0x0002, "UL", "Data Object Attributes" }, { 0x00e1, 0x0001, "US", "Data Dictionary Version" }, { 0x00e1, 0x0014, "LT", "?" }, { 0x00e1, 0x0022, "DS", "?" }, { 0x00e1, 0x0023, "DS", "?" }, { 0x00e1, 0x0024, "LT", "?" }, { 0x00e1, 0x0025, "LT", "?" }, { 0x00e1, 0x0040, "SH", "Offset From CT MR Images" }, { 0x0193, 0x0002, "DS", "RIS Key" }, { 0x0307, 0x0001, "UN", "RIS Worklist IMGEF" }, { 0x0309, 0x0001, "UN", "RIS Report IMGEF" }, { 0x0601, 0x0000, "SH", "Implementation Version" }, { 0x0601, 0x0020, "DS", "Relative Table Position" }, { 0x0601, 0x0021, "DS", "Relative Table Height" }, { 0x0601, 0x0030, "SH", "Surview Direction" }, { 0x0601, 0x0031, "DS", "Surview Length" }, { 0x0601, 0x0050, "SH", "Image View Type" }, { 0x0601, 0x0070, "DS", "Batch Number" }, { 0x0601, 0x0071, "DS", "Batch Size" }, { 0x0601, 0x0072, "DS", "Batch Slice Number" }, { 0x1000, 0x0000, "xs", "?" }, { 0x1000, 0x0001, "US", "Run Length Triplet" }, { 0x1000, 0x0002, "US", "Huffman Table Size" }, { 0x1000, 0x0003, "US", "Huffman Table Triplet" }, { 0x1000, 0x0004, "US", "Shift Table Size" }, { 0x1000, 0x0005, "US", "Shift Table Triplet" }, { 0x1010, 0x0000, "xs", "?" }, { 0x1369, 0x0000, "US", "?" }, { 0x2000, 0x0000, "UL", "Film Session Group Length" }, { 0x2000, 0x0010, "IS", "Number of Copies" }, { 0x2000, 0x0020, "CS", "Print Priority" }, { 0x2000, 0x0030, "CS", "Medium Type" }, { 0x2000, 0x0040, "CS", "Film Destination" }, { 0x2000, 0x0050, "LO", "Film Session Label" }, { 0x2000, 0x0060, "IS", "Memory Allocation" }, { 0x2000, 0x0500, "SQ", "Referenced Film Box Sequence" }, { 0x2010, 0x0000, "UL", "Film Box Group Length" }, { 0x2010, 0x0010, "ST", "Image Display Format" }, { 0x2010, 0x0030, "CS", "Annotation Display Format ID" }, { 0x2010, 0x0040, "CS", "Film Orientation" }, { 0x2010, 0x0050, "CS", "Film Size ID" }, { 0x2010, 0x0060, "CS", "Magnification Type" }, { 0x2010, 0x0080, "CS", "Smoothing Type" }, { 0x2010, 0x0100, "CS", "Border Density" }, { 0x2010, 0x0110, "CS", "Empty Image Density" }, { 0x2010, 0x0120, "US", "Min Density" }, { 0x2010, 0x0130, "US", "Max Density" }, { 0x2010, 0x0140, "CS", "Trim" }, { 0x2010, 0x0150, "ST", "Configuration Information" }, { 0x2010, 0x0500, "SQ", "Referenced Film Session Sequence" }, { 0x2010, 0x0510, "SQ", "Referenced Image Box Sequence" }, { 0x2010, 0x0520, "SQ", "Referenced Basic Annotation Box Sequence" }, { 0x2020, 0x0000, "UL", "Image Box Group Length" }, { 0x2020, 0x0010, "US", "Image Box Position" }, { 0x2020, 0x0020, "CS", "Polarity" }, { 0x2020, 0x0030, "DS", "Requested Image Size" }, { 0x2020, 0x0110, "SQ", "Preformatted Grayscale Image Sequence" }, { 0x2020, 0x0111, "SQ", "Preformatted Color Image Sequence" }, { 0x2020, 0x0130, "SQ", "Referenced Image Overlay Box Sequence" }, { 0x2020, 0x0140, "SQ", "Referenced VOI LUT Box Sequence" }, { 0x2030, 0x0000, "UL", "Annotation Group Length" }, { 0x2030, 0x0010, "US", "Annotation Position" }, { 0x2030, 0x0020, "LO", "Text String" }, { 0x2040, 0x0000, "UL", "Overlay Box Group Length" }, { 0x2040, 0x0010, "SQ", "Referenced Overlay Plane Sequence" }, { 0x2040, 0x0011, "US", "Referenced Overlay Plane Groups" }, { 0x2040, 0x0060, "CS", "Overlay Magnification Type" }, { 0x2040, 0x0070, "CS", "Overlay Smoothing Type" }, { 0x2040, 0x0080, "CS", "Overlay Foreground Density" }, { 0x2040, 0x0090, "CS", "Overlay Mode" }, { 0x2040, 0x0100, "CS", "Threshold Density" }, { 0x2040, 0x0500, "SQ", "Referenced Overlay Image Box Sequence" }, { 0x2050, 0x0010, "SQ", "Presentation LUT Sequence" }, { 0x2050, 0x0020, "CS", "Presentation LUT Shape" }, { 0x2100, 0x0000, "UL", "Print Job Group Length" }, { 0x2100, 0x0020, "CS", "Execution Status" }, { 0x2100, 0x0030, "CS", "Execution Status Info" }, { 0x2100, 0x0040, "DA", "Creation Date" }, { 0x2100, 0x0050, "TM", "Creation Time" }, { 0x2100, 0x0070, "AE", "Originator" }, { 0x2100, 0x0500, "SQ", "Referenced Print Job Sequence" }, { 0x2110, 0x0000, "UL", "Printer Group Length" }, { 0x2110, 0x0010, "CS", "Printer Status" }, { 0x2110, 0x0020, "CS", "Printer Status Info" }, { 0x2110, 0x0030, "LO", "Printer Name" }, { 0x2110, 0x0099, "SH", "Print Queue ID" }, { 0x3002, 0x0002, "SH", "RT Image Label" }, { 0x3002, 0x0003, "LO", "RT Image Name" }, { 0x3002, 0x0004, "ST", "RT Image Description" }, { 0x3002, 0x000a, "CS", "Reported Values Origin" }, { 0x3002, 0x000c, "CS", "RT Image Plane" }, { 0x3002, 0x000e, "DS", "X-Ray Image Receptor Angle" }, { 0x3002, 0x0010, "DS", "RTImageOrientation" }, { 0x3002, 0x0011, "DS", "Image Plane Pixel Spacing" }, { 0x3002, 0x0012, "DS", "RT Image Position" }, { 0x3002, 0x0020, "SH", "Radiation Machine Name" }, { 0x3002, 0x0022, "DS", "Radiation Machine SAD" }, { 0x3002, 0x0024, "DS", "Radiation Machine SSD" }, { 0x3002, 0x0026, "DS", "RT Image SID" }, { 0x3002, 0x0028, "DS", "Source to Reference Object Distance" }, { 0x3002, 0x0029, "IS", "Fraction Number" }, { 0x3002, 0x0030, "SQ", "Exposure Sequence" }, { 0x3002, 0x0032, "DS", "Meterset Exposure" }, { 0x3004, 0x0001, "CS", "DVH Type" }, { 0x3004, 0x0002, "CS", "Dose Units" }, { 0x3004, 0x0004, "CS", "Dose Type" }, { 0x3004, 0x0006, "LO", "Dose Comment" }, { 0x3004, 0x0008, "DS", "Normalization Point" }, { 0x3004, 0x000a, "CS", "Dose Summation Type" }, { 0x3004, 0x000c, "DS", "GridFrame Offset Vector" }, { 0x3004, 0x000e, "DS", "Dose Grid Scaling" }, { 0x3004, 0x0010, "SQ", "RT Dose ROI Sequence" }, { 0x3004, 0x0012, "DS", "Dose Value" }, { 0x3004, 0x0040, "DS", "DVH Normalization Point" }, { 0x3004, 0x0042, "DS", "DVH Normalization Dose Value" }, { 0x3004, 0x0050, "SQ", "DVH Sequence" }, { 0x3004, 0x0052, "DS", "DVH Dose Scaling" }, { 0x3004, 0x0054, "CS", "DVH Volume Units" }, { 0x3004, 0x0056, "IS", "DVH Number of Bins" }, { 0x3004, 0x0058, "DS", "DVH Data" }, { 0x3004, 0x0060, "SQ", "DVH Referenced ROI Sequence" }, { 0x3004, 0x0062, "CS", "DVH ROI Contribution Type" }, { 0x3004, 0x0070, "DS", "DVH Minimum Dose" }, { 0x3004, 0x0072, "DS", "DVH Maximum Dose" }, { 0x3004, 0x0074, "DS", "DVH Mean Dose" }, { 0x3006, 0x0002, "SH", "Structure Set Label" }, { 0x3006, 0x0004, "LO", "Structure Set Name" }, { 0x3006, 0x0006, "ST", "Structure Set Description" }, { 0x3006, 0x0008, "DA", "Structure Set Date" }, { 0x3006, 0x0009, "TM", "Structure Set Time" }, { 0x3006, 0x0010, "SQ", "Referenced Frame of Reference Sequence" }, { 0x3006, 0x0012, "SQ", "RT Referenced Study Sequence" }, { 0x3006, 0x0014, "SQ", "RT Referenced Series Sequence" }, { 0x3006, 0x0016, "SQ", "Contour Image Sequence" }, { 0x3006, 0x0020, "SQ", "Structure Set ROI Sequence" }, { 0x3006, 0x0022, "IS", "ROI Number" }, { 0x3006, 0x0024, "UI", "Referenced Frame of Reference UID" }, { 0x3006, 0x0026, "LO", "ROI Name" }, { 0x3006, 0x0028, "ST", "ROI Description" }, { 0x3006, 0x002a, "IS", "ROI Display Color" }, { 0x3006, 0x002c, "DS", "ROI Volume" }, { 0x3006, 0x0030, "SQ", "RT Related ROI Sequence" }, { 0x3006, 0x0033, "CS", "RT ROI Relationship" }, { 0x3006, 0x0036, "CS", "ROI Generation Algorithm" }, { 0x3006, 0x0038, "LO", "ROI Generation Description" }, { 0x3006, 0x0039, "SQ", "ROI Contour Sequence" }, { 0x3006, 0x0040, "SQ", "Contour Sequence" }, { 0x3006, 0x0042, "CS", "Contour Geometric Type" }, { 0x3006, 0x0044, "DS", "Contour SlabT hickness" }, { 0x3006, 0x0045, "DS", "Contour Offset Vector" }, { 0x3006, 0x0046, "IS", "Number of Contour Points" }, { 0x3006, 0x0050, "DS", "Contour Data" }, { 0x3006, 0x0080, "SQ", "RT ROI Observations Sequence" }, { 0x3006, 0x0082, "IS", "Observation Number" }, { 0x3006, 0x0084, "IS", "Referenced ROI Number" }, { 0x3006, 0x0085, "SH", "ROI Observation Label" }, { 0x3006, 0x0086, "SQ", "RT ROI Identification Code Sequence" }, { 0x3006, 0x0088, "ST", "ROI Observation Description" }, { 0x3006, 0x00a0, "SQ", "Related RT ROI Observations Sequence" }, { 0x3006, 0x00a4, "CS", "RT ROI Interpreted Type" }, { 0x3006, 0x00a6, "PN", "ROI Interpreter" }, { 0x3006, 0x00b0, "SQ", "ROI Physical Properties Sequence" }, { 0x3006, 0x00b2, "CS", "ROI Physical Property" }, { 0x3006, 0x00b4, "DS", "ROI Physical Property Value" }, { 0x3006, 0x00c0, "SQ", "Frame of Reference Relationship Sequence" }, { 0x3006, 0x00c2, "UI", "Related Frame of Reference UID" }, { 0x3006, 0x00c4, "CS", "Frame of Reference Transformation Type" }, { 0x3006, 0x00c6, "DS", "Frame of Reference Transformation Matrix" }, { 0x3006, 0x00c8, "LO", "Frame of Reference Transformation Comment" }, { 0x300a, 0x0002, "SH", "RT Plan Label" }, { 0x300a, 0x0003, "LO", "RT Plan Name" }, { 0x300a, 0x0004, "ST", "RT Plan Description" }, { 0x300a, 0x0006, "DA", "RT Plan Date" }, { 0x300a, 0x0007, "TM", "RT Plan Time" }, { 0x300a, 0x0009, "LO", "Treatment Protocols" }, { 0x300a, 0x000a, "CS", "Treatment Intent" }, { 0x300a, 0x000b, "LO", "Treatment Sites" }, { 0x300a, 0x000c, "CS", "RT Plan Geometry" }, { 0x300a, 0x000e, "ST", "Prescription Description" }, { 0x300a, 0x0010, "SQ", "Dose ReferenceSequence" }, { 0x300a, 0x0012, "IS", "Dose ReferenceNumber" }, { 0x300a, 0x0014, "CS", "Dose Reference Structure Type" }, { 0x300a, 0x0016, "LO", "Dose ReferenceDescription" }, { 0x300a, 0x0018, "DS", "Dose Reference Point Coordinates" }, { 0x300a, 0x001a, "DS", "Nominal Prior Dose" }, { 0x300a, 0x0020, "CS", "Dose Reference Type" }, { 0x300a, 0x0021, "DS", "Constraint Weight" }, { 0x300a, 0x0022, "DS", "Delivery Warning Dose" }, { 0x300a, 0x0023, "DS", "Delivery Maximum Dose" }, { 0x300a, 0x0025, "DS", "Target Minimum Dose" }, { 0x300a, 0x0026, "DS", "Target Prescription Dose" }, { 0x300a, 0x0027, "DS", "Target Maximum Dose" }, { 0x300a, 0x0028, "DS", "Target Underdose Volume Fraction" }, { 0x300a, 0x002a, "DS", "Organ at Risk Full-volume Dose" }, { 0x300a, 0x002b, "DS", "Organ at Risk Limit Dose" }, { 0x300a, 0x002c, "DS", "Organ at Risk Maximum Dose" }, { 0x300a, 0x002d, "DS", "Organ at Risk Overdose Volume Fraction" }, { 0x300a, 0x0040, "SQ", "Tolerance Table Sequence" }, { 0x300a, 0x0042, "IS", "Tolerance Table Number" }, { 0x300a, 0x0043, "SH", "Tolerance Table Label" }, { 0x300a, 0x0044, "DS", "Gantry Angle Tolerance" }, { 0x300a, 0x0046, "DS", "Beam Limiting Device Angle Tolerance" }, { 0x300a, 0x0048, "SQ", "Beam Limiting Device Tolerance Sequence" }, { 0x300a, 0x004a, "DS", "Beam Limiting Device Position Tolerance" }, { 0x300a, 0x004c, "DS", "Patient Support Angle Tolerance" }, { 0x300a, 0x004e, "DS", "Table Top Eccentric Angle Tolerance" }, { 0x300a, 0x0051, "DS", "Table Top Vertical Position Tolerance" }, { 0x300a, 0x0052, "DS", "Table Top Longitudinal Position Tolerance" }, { 0x300a, 0x0053, "DS", "Table Top Lateral Position Tolerance" }, { 0x300a, 0x0055, "CS", "RT Plan Relationship" }, { 0x300a, 0x0070, "SQ", "Fraction Group Sequence" }, { 0x300a, 0x0071, "IS", "Fraction Group Number" }, { 0x300a, 0x0078, "IS", "Number of Fractions Planned" }, { 0x300a, 0x0079, "IS", "Number of Fractions Per Day" }, { 0x300a, 0x007a, "IS", "Repeat Fraction Cycle Length" }, { 0x300a, 0x007b, "LT", "Fraction Pattern" }, { 0x300a, 0x0080, "IS", "Number of Beams" }, { 0x300a, 0x0082, "DS", "Beam Dose Specification Point" }, { 0x300a, 0x0084, "DS", "Beam Dose" }, { 0x300a, 0x0086, "DS", "Beam Meterset" }, { 0x300a, 0x00a0, "IS", "Number of Brachy Application Setups" }, { 0x300a, 0x00a2, "DS", "Brachy Application Setup Dose Specification Point" }, { 0x300a, 0x00a4, "DS", "Brachy Application Setup Dose" }, { 0x300a, 0x00b0, "SQ", "Beam Sequence" }, { 0x300a, 0x00b2, "SH", "Treatment Machine Name " }, { 0x300a, 0x00b3, "CS", "Primary Dosimeter Unit" }, { 0x300a, 0x00b4, "DS", "Source-Axis Distance" }, { 0x300a, 0x00b6, "SQ", "Beam Limiting Device Sequence" }, { 0x300a, 0x00b8, "CS", "RT Beam Limiting Device Type" }, { 0x300a, 0x00ba, "DS", "Source to Beam Limiting Device Distance" }, { 0x300a, 0x00bc, "IS", "Number of Leaf/Jaw Pairs" }, { 0x300a, 0x00be, "DS", "Leaf Position Boundaries" }, { 0x300a, 0x00c0, "IS", "Beam Number" }, { 0x300a, 0x00c2, "LO", "Beam Name" }, { 0x300a, 0x00c3, "ST", "Beam Description" }, { 0x300a, 0x00c4, "CS", "Beam Type" }, { 0x300a, 0x00c6, "CS", "Radiation Type" }, { 0x300a, 0x00c8, "IS", "Reference Image Number" }, { 0x300a, 0x00ca, "SQ", "Planned Verification Image Sequence" }, { 0x300a, 0x00cc, "LO", "Imaging Device Specific Acquisition Parameters" }, { 0x300a, 0x00ce, "CS", "Treatment Delivery Type" }, { 0x300a, 0x00d0, "IS", "Number of Wedges" }, { 0x300a, 0x00d1, "SQ", "Wedge Sequence" }, { 0x300a, 0x00d2, "IS", "Wedge Number" }, { 0x300a, 0x00d3, "CS", "Wedge Type" }, { 0x300a, 0x00d4, "SH", "Wedge ID" }, { 0x300a, 0x00d5, "IS", "Wedge Angle" }, { 0x300a, 0x00d6, "DS", "Wedge Factor" }, { 0x300a, 0x00d8, "DS", "Wedge Orientation" }, { 0x300a, 0x00da, "DS", "Source to Wedge Tray Distance" }, { 0x300a, 0x00e0, "IS", "Number of Compensators" }, { 0x300a, 0x00e1, "SH", "Material ID" }, { 0x300a, 0x00e2, "DS", "Total Compensator Tray Factor" }, { 0x300a, 0x00e3, "SQ", "Compensator Sequence" }, { 0x300a, 0x00e4, "IS", "Compensator Number" }, { 0x300a, 0x00e5, "SH", "Compensator ID" }, { 0x300a, 0x00e6, "DS", "Source to Compensator Tray Distance" }, { 0x300a, 0x00e7, "IS", "Compensator Rows" }, { 0x300a, 0x00e8, "IS", "Compensator Columns" }, { 0x300a, 0x00e9, "DS", "Compensator Pixel Spacing" }, { 0x300a, 0x00ea, "DS", "Compensator Position" }, { 0x300a, 0x00eb, "DS", "Compensator Transmission Data" }, { 0x300a, 0x00ec, "DS", "Compensator Thickness Data" }, { 0x300a, 0x00ed, "IS", "Number of Boli" }, { 0x300a, 0x00f0, "IS", "Number of Blocks" }, { 0x300a, 0x00f2, "DS", "Total Block Tray Factor" }, { 0x300a, 0x00f4, "SQ", "Block Sequence" }, { 0x300a, 0x00f5, "SH", "Block Tray ID" }, { 0x300a, 0x00f6, "DS", "Source to Block Tray Distance" }, { 0x300a, 0x00f8, "CS", "Block Type" }, { 0x300a, 0x00fa, "CS", "Block Divergence" }, { 0x300a, 0x00fc, "IS", "Block Number" }, { 0x300a, 0x00fe, "LO", "Block Name" }, { 0x300a, 0x0100, "DS", "Block Thickness" }, { 0x300a, 0x0102, "DS", "Block Transmission" }, { 0x300a, 0x0104, "IS", "Block Number of Points" }, { 0x300a, 0x0106, "DS", "Block Data" }, { 0x300a, 0x0107, "SQ", "Applicator Sequence" }, { 0x300a, 0x0108, "SH", "Applicator ID" }, { 0x300a, 0x0109, "CS", "Applicator Type" }, { 0x300a, 0x010a, "LO", "Applicator Description" }, { 0x300a, 0x010c, "DS", "Cumulative Dose Reference Coefficient" }, { 0x300a, 0x010e, "DS", "Final Cumulative Meterset Weight" }, { 0x300a, 0x0110, "IS", "Number of Control Points" }, { 0x300a, 0x0111, "SQ", "Control Point Sequence" }, { 0x300a, 0x0112, "IS", "Control Point Index" }, { 0x300a, 0x0114, "DS", "Nominal Beam Energy" }, { 0x300a, 0x0115, "DS", "Dose Rate Set" }, { 0x300a, 0x0116, "SQ", "Wedge Position Sequence" }, { 0x300a, 0x0118, "CS", "Wedge Position" }, { 0x300a, 0x011a, "SQ", "Beam Limiting Device Position Sequence" }, { 0x300a, 0x011c, "DS", "Leaf Jaw Positions" }, { 0x300a, 0x011e, "DS", "Gantry Angle" }, { 0x300a, 0x011f, "CS", "Gantry Rotation Direction" }, { 0x300a, 0x0120, "DS", "Beam Limiting Device Angle" }, { 0x300a, 0x0121, "CS", "Beam Limiting Device Rotation Direction" }, { 0x300a, 0x0122, "DS", "Patient Support Angle" }, { 0x300a, 0x0123, "CS", "Patient Support Rotation Direction" }, { 0x300a, 0x0124, "DS", "Table Top Eccentric Axis Distance" }, { 0x300a, 0x0125, "DS", "Table Top Eccentric Angle" }, { 0x300a, 0x0126, "CS", "Table Top Eccentric Rotation Direction" }, { 0x300a, 0x0128, "DS", "Table Top Vertical Position" }, { 0x300a, 0x0129, "DS", "Table Top Longitudinal Position" }, { 0x300a, 0x012a, "DS", "Table Top Lateral Position" }, { 0x300a, 0x012c, "DS", "Isocenter Position" }, { 0x300a, 0x012e, "DS", "Surface Entry Point" }, { 0x300a, 0x0130, "DS", "Source to Surface Distance" }, { 0x300a, 0x0134, "DS", "Cumulative Meterset Weight" }, { 0x300a, 0x0180, "SQ", "Patient Setup Sequence" }, { 0x300a, 0x0182, "IS", "Patient Setup Number" }, { 0x300a, 0x0184, "LO", "Patient Additional Position" }, { 0x300a, 0x0190, "SQ", "Fixation Device Sequence" }, { 0x300a, 0x0192, "CS", "Fixation Device Type" }, { 0x300a, 0x0194, "SH", "Fixation Device Label" }, { 0x300a, 0x0196, "ST", "Fixation Device Description" }, { 0x300a, 0x0198, "SH", "Fixation Device Position" }, { 0x300a, 0x01a0, "SQ", "Shielding Device Sequence" }, { 0x300a, 0x01a2, "CS", "Shielding Device Type" }, { 0x300a, 0x01a4, "SH", "Shielding Device Label" }, { 0x300a, 0x01a6, "ST", "Shielding Device Description" }, { 0x300a, 0x01a8, "SH", "Shielding Device Position" }, { 0x300a, 0x01b0, "CS", "Setup Technique" }, { 0x300a, 0x01b2, "ST", "Setup TechniqueDescription" }, { 0x300a, 0x01b4, "SQ", "Setup Device Sequence" }, { 0x300a, 0x01b6, "CS", "Setup Device Type" }, { 0x300a, 0x01b8, "SH", "Setup Device Label" }, { 0x300a, 0x01ba, "ST", "Setup Device Description" }, { 0x300a, 0x01bc, "DS", "Setup Device Parameter" }, { 0x300a, 0x01d0, "ST", "Setup ReferenceDescription" }, { 0x300a, 0x01d2, "DS", "Table Top Vertical Setup Displacement" }, { 0x300a, 0x01d4, "DS", "Table Top Longitudinal Setup Displacement" }, { 0x300a, 0x01d6, "DS", "Table Top Lateral Setup Displacement" }, { 0x300a, 0x0200, "CS", "Brachy Treatment Technique" }, { 0x300a, 0x0202, "CS", "Brachy Treatment Type" }, { 0x300a, 0x0206, "SQ", "Treatment Machine Sequence" }, { 0x300a, 0x0210, "SQ", "Source Sequence" }, { 0x300a, 0x0212, "IS", "Source Number" }, { 0x300a, 0x0214, "CS", "Source Type" }, { 0x300a, 0x0216, "LO", "Source Manufacturer" }, { 0x300a, 0x0218, "DS", "Active Source Diameter" }, { 0x300a, 0x021a, "DS", "Active Source Length" }, { 0x300a, 0x0222, "DS", "Source Encapsulation Nominal Thickness" }, { 0x300a, 0x0224, "DS", "Source Encapsulation Nominal Transmission" }, { 0x300a, 0x0226, "LO", "Source IsotopeName" }, { 0x300a, 0x0228, "DS", "Source Isotope Half Life" }, { 0x300a, 0x022a, "DS", "Reference Air Kerma Rate" }, { 0x300a, 0x022c, "DA", "Air Kerma Rate Reference Date" }, { 0x300a, 0x022e, "TM", "Air Kerma Rate Reference Time" }, { 0x300a, 0x0230, "SQ", "Application Setup Sequence" }, { 0x300a, 0x0232, "CS", "Application Setup Type" }, { 0x300a, 0x0234, "IS", "Application Setup Number" }, { 0x300a, 0x0236, "LO", "Application Setup Name" }, { 0x300a, 0x0238, "LO", "Application Setup Manufacturer" }, { 0x300a, 0x0240, "IS", "Template Number" }, { 0x300a, 0x0242, "SH", "Template Type" }, { 0x300a, 0x0244, "LO", "Template Name" }, { 0x300a, 0x0250, "DS", "Total Reference Air Kerma" }, { 0x300a, 0x0260, "SQ", "Brachy Accessory Device Sequence" }, { 0x300a, 0x0262, "IS", "Brachy Accessory Device Number" }, { 0x300a, 0x0263, "SH", "Brachy Accessory Device ID" }, { 0x300a, 0x0264, "CS", "Brachy Accessory Device Type" }, { 0x300a, 0x0266, "LO", "Brachy Accessory Device Name" }, { 0x300a, 0x026a, "DS", "Brachy Accessory Device Nominal Thickness" }, { 0x300a, 0x026c, "DS", "Brachy Accessory Device Nominal Transmission" }, { 0x300a, 0x0280, "SQ", "Channel Sequence" }, { 0x300a, 0x0282, "IS", "Channel Number" }, { 0x300a, 0x0284, "DS", "Channel Length" }, { 0x300a, 0x0286, "DS", "Channel Total Time" }, { 0x300a, 0x0288, "CS", "Source Movement Type" }, { 0x300a, 0x028a, "IS", "Number of Pulses" }, { 0x300a, 0x028c, "DS", "Pulse Repetition Interval" }, { 0x300a, 0x0290, "IS", "Source Applicator Number" }, { 0x300a, 0x0291, "SH", "Source Applicator ID" }, { 0x300a, 0x0292, "CS", "Source Applicator Type" }, { 0x300a, 0x0294, "LO", "Source Applicator Name" }, { 0x300a, 0x0296, "DS", "Source Applicator Length" }, { 0x300a, 0x0298, "LO", "Source Applicator Manufacturer" }, { 0x300a, 0x029c, "DS", "Source Applicator Wall Nominal Thickness" }, { 0x300a, 0x029e, "DS", "Source Applicator Wall Nominal Transmission" }, { 0x300a, 0x02a0, "DS", "Source Applicator Step Size" }, { 0x300a, 0x02a2, "IS", "Transfer Tube Number" }, { 0x300a, 0x02a4, "DS", "Transfer Tube Length" }, { 0x300a, 0x02b0, "SQ", "Channel Shield Sequence" }, { 0x300a, 0x02b2, "IS", "Channel Shield Number" }, { 0x300a, 0x02b3, "SH", "Channel Shield ID" }, { 0x300a, 0x02b4, "LO", "Channel Shield Name" }, { 0x300a, 0x02b8, "DS", "Channel Shield Nominal Thickness" }, { 0x300a, 0x02ba, "DS", "Channel Shield Nominal Transmission" }, { 0x300a, 0x02c8, "DS", "Final Cumulative Time Weight" }, { 0x300a, 0x02d0, "SQ", "Brachy Control Point Sequence" }, { 0x300a, 0x02d2, "DS", "Control Point Relative Position" }, { 0x300a, 0x02d4, "DS", "Control Point 3D Position" }, { 0x300a, 0x02d6, "DS", "Cumulative Time Weight" }, { 0x300c, 0x0002, "SQ", "Referenced RT Plan Sequence" }, { 0x300c, 0x0004, "SQ", "Referenced Beam Sequence" }, { 0x300c, 0x0006, "IS", "Referenced Beam Number" }, { 0x300c, 0x0007, "IS", "Referenced Reference Image Number" }, { 0x300c, 0x0008, "DS", "Start Cumulative Meterset Weight" }, { 0x300c, 0x0009, "DS", "End Cumulative Meterset Weight" }, { 0x300c, 0x000a, "SQ", "Referenced Brachy Application Setup Sequence" }, { 0x300c, 0x000c, "IS", "Referenced Brachy Application Setup Number" }, { 0x300c, 0x000e, "IS", "Referenced Source Number" }, { 0x300c, 0x0020, "SQ", "Referenced Fraction Group Sequence" }, { 0x300c, 0x0022, "IS", "Referenced Fraction Group Number" }, { 0x300c, 0x0040, "SQ", "Referenced Verification Image Sequence" }, { 0x300c, 0x0042, "SQ", "Referenced Reference Image Sequence" }, { 0x300c, 0x0050, "SQ", "Referenced Dose Reference Sequence" }, { 0x300c, 0x0051, "IS", "Referenced Dose Reference Number" }, { 0x300c, 0x0055, "SQ", "Brachy Referenced Dose Reference Sequence" }, { 0x300c, 0x0060, "SQ", "Referenced Structure Set Sequence" }, { 0x300c, 0x006a, "IS", "Referenced Patient Setup Number" }, { 0x300c, 0x0080, "SQ", "Referenced Dose Sequence" }, { 0x300c, 0x00a0, "IS", "Referenced Tolerance Table Number" }, { 0x300c, 0x00b0, "SQ", "Referenced Bolus Sequence" }, { 0x300c, 0x00c0, "IS", "Referenced Wedge Number" }, { 0x300c, 0x00d0, "IS", "Referenced Compensato rNumber" }, { 0x300c, 0x00e0, "IS", "Referenced Block Number" }, { 0x300c, 0x00f0, "IS", "Referenced Control Point" }, { 0x300e, 0x0002, "CS", "Approval Status" }, { 0x300e, 0x0004, "DA", "Review Date" }, { 0x300e, 0x0005, "TM", "Review Time" }, { 0x300e, 0x0008, "PN", "Reviewer Name" }, { 0x4000, 0x0000, "UL", "Text Group Length" }, { 0x4000, 0x0010, "LT", "Text Arbitrary" }, { 0x4000, 0x4000, "LT", "Text Comments" }, { 0x4008, 0x0000, "UL", "Results Group Length" }, { 0x4008, 0x0040, "SH", "Results ID" }, { 0x4008, 0x0042, "LO", "Results ID Issuer" }, { 0x4008, 0x0050, "SQ", "Referenced Interpretation Sequence" }, { 0x4008, 0x00ff, "CS", "Report Production Status" }, { 0x4008, 0x0100, "DA", "Interpretation Recorded Date" }, { 0x4008, 0x0101, "TM", "Interpretation Recorded Time" }, { 0x4008, 0x0102, "PN", "Interpretation Recorder" }, { 0x4008, 0x0103, "LO", "Reference to Recorded Sound" }, { 0x4008, 0x0108, "DA", "Interpretation Transcription Date" }, { 0x4008, 0x0109, "TM", "Interpretation Transcription Time" }, { 0x4008, 0x010a, "PN", "Interpretation Transcriber" }, { 0x4008, 0x010b, "ST", "Interpretation Text" }, { 0x4008, 0x010c, "PN", "Interpretation Author" }, { 0x4008, 0x0111, "SQ", "Interpretation Approver Sequence" }, { 0x4008, 0x0112, "DA", "Interpretation Approval Date" }, { 0x4008, 0x0113, "TM", "Interpretation Approval Time" }, { 0x4008, 0x0114, "PN", "Physician Approving Interpretation" }, { 0x4008, 0x0115, "LT", "Interpretation Diagnosis Description" }, { 0x4008, 0x0117, "SQ", "InterpretationDiagnosis Code Sequence" }, { 0x4008, 0x0118, "SQ", "Results Distribution List Sequence" }, { 0x4008, 0x0119, "PN", "Distribution Name" }, { 0x4008, 0x011a, "LO", "Distribution Address" }, { 0x4008, 0x0200, "SH", "Interpretation ID" }, { 0x4008, 0x0202, "LO", "Interpretation ID Issuer" }, { 0x4008, 0x0210, "CS", "Interpretation Type ID" }, { 0x4008, 0x0212, "CS", "Interpretation Status ID" }, { 0x4008, 0x0300, "ST", "Impressions" }, { 0x4008, 0x4000, "ST", "Results Comments" }, { 0x4009, 0x0001, "LT", "Report ID" }, { 0x4009, 0x0020, "LT", "Report Status" }, { 0x4009, 0x0030, "DA", "Report Creation Date" }, { 0x4009, 0x0070, "LT", "Report Approving Physician" }, { 0x4009, 0x00e0, "LT", "Report Text" }, { 0x4009, 0x00e1, "LT", "Report Author" }, { 0x4009, 0x00e3, "LT", "Reporting Radiologist" }, { 0x5000, 0x0000, "UL", "Curve Group Length" }, { 0x5000, 0x0005, "US", "Curve Dimensions" }, { 0x5000, 0x0010, "US", "Number of Points" }, { 0x5000, 0x0020, "CS", "Type of Data" }, { 0x5000, 0x0022, "LO", "Curve Description" }, { 0x5000, 0x0030, "SH", "Axis Units" }, { 0x5000, 0x0040, "SH", "Axis Labels" }, { 0x5000, 0x0103, "US", "Data Value Representation" }, { 0x5000, 0x0104, "US", "Minimum Coordinate Value" }, { 0x5000, 0x0105, "US", "Maximum Coordinate Value" }, { 0x5000, 0x0106, "SH", "Curve Range" }, { 0x5000, 0x0110, "US", "Curve Data Descriptor" }, { 0x5000, 0x0112, "US", "Coordinate Start Value" }, { 0x5000, 0x0114, "US", "Coordinate Step Value" }, { 0x5000, 0x1001, "CS", "Curve Activation Layer" }, { 0x5000, 0x2000, "US", "Audio Type" }, { 0x5000, 0x2002, "US", "Audio Sample Format" }, { 0x5000, 0x2004, "US", "Number of Channels" }, { 0x5000, 0x2006, "UL", "Number of Samples" }, { 0x5000, 0x2008, "UL", "Sample Rate" }, { 0x5000, 0x200a, "UL", "Total Time" }, { 0x5000, 0x200c, "xs", "Audio Sample Data" }, { 0x5000, 0x200e, "LT", "Audio Comments" }, { 0x5000, 0x2500, "LO", "Curve Label" }, { 0x5000, 0x2600, "SQ", "CurveReferenced Overlay Sequence" }, { 0x5000, 0x2610, "US", "CurveReferenced Overlay Group" }, { 0x5000, 0x3000, "OW", "Curve Data" }, { 0x6000, 0x0000, "UL", "Overlay Group Length" }, { 0x6000, 0x0001, "US", "Gray Palette Color Lookup Table Descriptor" }, { 0x6000, 0x0002, "US", "Gray Palette Color Lookup Table Data" }, { 0x6000, 0x0010, "US", "Overlay Rows" }, { 0x6000, 0x0011, "US", "Overlay Columns" }, { 0x6000, 0x0012, "US", "Overlay Planes" }, { 0x6000, 0x0015, "IS", "Number of Frames in Overlay" }, { 0x6000, 0x0022, "LO", "Overlay Description" }, { 0x6000, 0x0040, "CS", "Overlay Type" }, { 0x6000, 0x0045, "CS", "Overlay Subtype" }, { 0x6000, 0x0050, "SS", "Overlay Origin" }, { 0x6000, 0x0051, "US", "Image Frame Origin" }, { 0x6000, 0x0052, "US", "Plane Origin" }, { 0x6000, 0x0060, "LO", "Overlay Compression Code" }, { 0x6000, 0x0061, "SH", "Overlay Compression Originator" }, { 0x6000, 0x0062, "SH", "Overlay Compression Label" }, { 0x6000, 0x0063, "SH", "Overlay Compression Description" }, { 0x6000, 0x0066, "AT", "Overlay Compression Step Pointers" }, { 0x6000, 0x0068, "US", "Overlay Repeat Interval" }, { 0x6000, 0x0069, "US", "Overlay Bits Grouped" }, { 0x6000, 0x0100, "US", "Overlay Bits Allocated" }, { 0x6000, 0x0102, "US", "Overlay Bit Position" }, { 0x6000, 0x0110, "LO", "Overlay Format" }, { 0x6000, 0x0200, "xs", "Overlay Location" }, { 0x6000, 0x0800, "LO", "Overlay Code Label" }, { 0x6000, 0x0802, "US", "Overlay Number of Tables" }, { 0x6000, 0x0803, "AT", "Overlay Code Table Location" }, { 0x6000, 0x0804, "US", "Overlay Bits For Code Word" }, { 0x6000, 0x1001, "CS", "Overlay Activation Layer" }, { 0x6000, 0x1100, "US", "Overlay Descriptor - Gray" }, { 0x6000, 0x1101, "US", "Overlay Descriptor - Red" }, { 0x6000, 0x1102, "US", "Overlay Descriptor - Green" }, { 0x6000, 0x1103, "US", "Overlay Descriptor - Blue" }, { 0x6000, 0x1200, "US", "Overlays - Gray" }, { 0x6000, 0x1201, "US", "Overlays - Red" }, { 0x6000, 0x1202, "US", "Overlays - Green" }, { 0x6000, 0x1203, "US", "Overlays - Blue" }, { 0x6000, 0x1301, "IS", "ROI Area" }, { 0x6000, 0x1302, "DS", "ROI Mean" }, { 0x6000, 0x1303, "DS", "ROI Standard Deviation" }, { 0x6000, 0x1500, "LO", "Overlay Label" }, { 0x6000, 0x3000, "OW", "Overlay Data" }, { 0x6000, 0x4000, "LT", "Overlay Comments" }, { 0x6001, 0x0000, "UN", "?" }, { 0x6001, 0x0010, "LO", "?" }, { 0x6001, 0x1010, "xs", "?" }, { 0x6001, 0x1030, "xs", "?" }, { 0x6021, 0x0000, "xs", "?" }, { 0x6021, 0x0010, "xs", "?" }, { 0x7001, 0x0010, "LT", "Dummy" }, { 0x7003, 0x0010, "LT", "Info" }, { 0x7005, 0x0010, "LT", "Dummy" }, { 0x7000, 0x0004, "ST", "TextAnnotation" }, { 0x7000, 0x0005, "IS", "Box" }, { 0x7000, 0x0007, "IS", "ArrowEnd" }, { 0x7fe0, 0x0000, "UL", "Pixel Data Group Length" }, { 0x7fe0, 0x0010, "xs", "Pixel Data" }, { 0x7fe0, 0x0020, "OW", "Coefficients SDVN" }, { 0x7fe0, 0x0030, "OW", "Coefficients SDHN" }, { 0x7fe0, 0x0040, "OW", "Coefficients SDDN" }, { 0x7fe1, 0x0010, "xs", "Pixel Data" }, { 0x7f00, 0x0000, "UL", "Variable Pixel Data Group Length" }, { 0x7f00, 0x0010, "xs", "Variable Pixel Data" }, { 0x7f00, 0x0011, "US", "Variable Next Data Group" }, { 0x7f00, 0x0020, "OW", "Variable Coefficients SDVN" }, { 0x7f00, 0x0030, "OW", "Variable Coefficients SDHN" }, { 0x7f00, 0x0040, "OW", "Variable Coefficients SDDN" }, { 0x7fe1, 0x0000, "OB", "Binary Data" }, { 0x7fe3, 0x0000, "LT", "Image Graphics Format Code" }, { 0x7fe3, 0x0010, "OB", "Image Graphics" }, { 0x7fe3, 0x0020, "OB", "Image Graphics Dummy" }, { 0x7ff1, 0x0001, "US", "?" }, { 0x7ff1, 0x0002, "US", "?" }, { 0x7ff1, 0x0003, "xs", "?" }, { 0x7ff1, 0x0004, "IS", "?" }, { 0x7ff1, 0x0005, "US", "?" }, { 0x7ff1, 0x0007, "US", "?" }, { 0x7ff1, 0x0008, "US", "?" }, { 0x7ff1, 0x0009, "US", "?" }, { 0x7ff1, 0x000a, "LT", "?" }, { 0x7ff1, 0x000b, "US", "?" }, { 0x7ff1, 0x000c, "US", "?" }, { 0x7ff1, 0x000d, "US", "?" }, { 0x7ff1, 0x0010, "US", "?" }, { 0xfffc, 0xfffc, "OB", "Data Set Trailing Padding" }, { 0xfffe, 0xe000, "!!", "Item" }, { 0xfffe, 0xe00d, "!!", "Item Delimitation Item" }, { 0xfffe, 0xe0dd, "!!", "Sequence Delimitation Item" }, { 0xffff, 0xffff, "xs", (char *) NULL } }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s D C M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsDCM() returns MagickTrue if the image format type, identified by the % magick string, is DCM. % % The format of the ReadDCMImage method is: % % MagickBooleanType IsDCM(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsDCM(const unsigned char *magick,const size_t length) { if (length < 132) return(MagickFalse); if (LocaleNCompare((char *) (magick+128),"DICM",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d D C M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadDCMImage() reads a Digital Imaging and Communications in Medicine % (DICOM) file and returns it. It allocates the memory necessary for the % new Image structure and returns a pointer to the new image. % % The format of the ReadDCMImage method is: % % Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ typedef struct _DCMInfo { MagickBooleanType polarity; Quantum *scale; size_t bits_allocated, bytes_per_pixel, depth, mask, max_value, samples_per_pixel, signed_data, significant_bits; MagickBooleanType rescale; double rescale_intercept, rescale_slope, window_center, window_width; } DCMInfo; typedef struct _DCMStreamInfo { size_t remaining, segment_count; ssize_t segments[15]; size_t offset_count; ssize_t *offsets; ssize_t count; int byte; } DCMStreamInfo; static int ReadDCMByte(DCMStreamInfo *stream_info,Image *image) { if (image->compression != RLECompression) return(ReadBlobByte(image)); if (stream_info->count == 0) { int byte; ssize_t count; if (stream_info->remaining <= 2) stream_info->remaining=0; else stream_info->remaining-=2; count=(ssize_t) ReadBlobByte(image); byte=ReadBlobByte(image); if (count == 128) return(0); else if (count < 128) { /* Literal bytes. */ stream_info->count=count; stream_info->byte=(-1); return(byte); } else { /* Repeated bytes. */ stream_info->count=256-count; stream_info->byte=byte; return(byte); } } stream_info->count--; if (stream_info->byte >= 0) return(stream_info->byte); if (stream_info->remaining > 0) stream_info->remaining--; return(ReadBlobByte(image)); } static unsigned short ReadDCMShort(DCMStreamInfo *stream_info,Image *image) { int shift; unsigned short value; if (image->compression != RLECompression) return(ReadBlobLSBShort(image)); shift=image->depth < 16 ? 4 : 8; value=ReadDCMByte(stream_info,image) | (unsigned short) (ReadDCMByte(stream_info,image) << shift); return(value); } static signed short ReadDCMSignedShort(DCMStreamInfo *stream_info,Image *image) { union { unsigned short unsigned_value; signed short signed_value; } quantum; quantum.unsigned_value=ReadDCMShort(stream_info,image); return(quantum.signed_value); } static MagickBooleanType ReadDCMPixels(Image *image,DCMInfo *info, DCMStreamInfo *stream_info,MagickBooleanType first_segment, ExceptionInfo *exception) { int byte, index; MagickBooleanType status; LongPixelPacket pixel; register ssize_t i, x; register IndexPacket *indexes; register PixelPacket *q; ssize_t y; /* Convert DCM Medical image to pixel packets. */ byte=0; i=0; status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if (info->samples_per_pixel == 1) { int pixel_value; if (info->bytes_per_pixel == 1) pixel_value=info->polarity != MagickFalse ? ((int) info->max_value- ReadDCMByte(stream_info,image)) : ReadDCMByte(stream_info,image); else if ((info->bits_allocated != 12) || (info->significant_bits != 12)) { if (info->signed_data) pixel_value=ReadDCMSignedShort(stream_info,image); else pixel_value=(int) ReadDCMShort(stream_info,image); if (info->polarity != MagickFalse) pixel_value=(int) info->max_value-pixel_value; } else { if ((i & 0x01) != 0) pixel_value=(ReadDCMByte(stream_info,image) << 8) | byte; else { pixel_value=ReadDCMSignedShort(stream_info,image); byte=(int) (pixel_value & 0x0f); pixel_value>>=4; } i++; } if (info->signed_data == 1) pixel_value-=32767; if (info->rescale) { double scaled_value; scaled_value=pixel_value*info->rescale_slope+ info->rescale_intercept; if (info->window_width == 0) { index=(int) scaled_value; } else { double window_max, window_min; window_min=ceil(info->window_center- (info->window_width-1.0)/2.0-0.5); window_max=floor(info->window_center+ (info->window_width-1.0)/2.0+0.5); if (scaled_value <= window_min) index=0; else if (scaled_value > window_max) index=(int) info->max_value; else index=(int) (info->max_value*(((scaled_value- info->window_center-0.5)/(info->window_width-1))+0.5)); } } else { index=pixel_value; } index&=info->mask; index=(int) ConstrainColormapIndex(image,(size_t) index); if (first_segment != MagickFalse) SetPixelIndex(indexes+x,index); else SetPixelIndex(indexes+x,(((size_t) index) | (((size_t) GetPixelIndex(indexes+x)) << 8))); pixel.red=1U*image->colormap[index].red; pixel.green=1U*image->colormap[index].green; pixel.blue=1U*image->colormap[index].blue; } else { if (info->bytes_per_pixel == 1) { pixel.red=(unsigned int) ReadDCMByte(stream_info,image); pixel.green=(unsigned int) ReadDCMByte(stream_info,image); pixel.blue=(unsigned int) ReadDCMByte(stream_info,image); } else { pixel.red=ReadDCMShort(stream_info,image); pixel.green=ReadDCMShort(stream_info,image); pixel.blue=ReadDCMShort(stream_info,image); } pixel.red&=info->mask; pixel.green&=info->mask; pixel.blue&=info->mask; if (info->scale != (Quantum *) NULL) { if ((MagickSizeType) pixel.red <= GetQuantumRange(info->depth)) pixel.red=info->scale[pixel.red]; if ((MagickSizeType) pixel.green <= GetQuantumRange(info->depth)) pixel.green=info->scale[pixel.green]; if ((MagickSizeType) pixel.blue <= GetQuantumRange(info->depth)) pixel.blue=info->scale[pixel.blue]; } } if (first_segment != MagickFalse) { SetPixelRed(q,pixel.red); SetPixelGreen(q,pixel.green); SetPixelBlue(q,pixel.blue); } else { SetPixelRed(q,(((size_t) pixel.red) | (((size_t) GetPixelRed(q)) << 8))); SetPixelGreen(q,(((size_t) pixel.green) | (((size_t) GetPixelGreen(q)) << 8))); SetPixelBlue(q,(((size_t) pixel.blue) | (((size_t) GetPixelBlue(q)) << 8))); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } return(status); } static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowDCMException(exception,message) \ { \ if (data != (unsigned char *) NULL) \ data=(unsigned char *) RelinquishMagickMemory(data); \ if (stream_info != (DCMStreamInfo *) NULL) \ stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); \ ThrowReaderException((exception),(message)); \ } char explicit_vr[MaxTextExtent], implicit_vr[MaxTextExtent], magick[MaxTextExtent], photometric[MaxTextExtent]; DCMInfo info; DCMStreamInfo *stream_info; Image *image; int *bluemap, datum, *greenmap, *graymap, *redmap; MagickBooleanType explicit_file, explicit_retry, sequence, use_explicit; MagickOffsetType offset; register unsigned char *p; register ssize_t i; size_t colors, height, length, number_scenes, quantum, status, width; ssize_t count, scene; unsigned char *data; unsigned short group, element; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=8UL; image->endian=LSBEndian; /* Read DCM preamble. */ data=(unsigned char *) NULL; stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info)); if (stream_info == (DCMStreamInfo *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(stream_info,0,sizeof(*stream_info)); count=ReadBlob(image,128,(unsigned char *) magick); if (count != 128) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,4,(unsigned char *) magick); if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0)) { offset=SeekBlob(image,0L,SEEK_SET); if (offset < 0) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); } /* Read DCM Medical image. */ (void) CopyMagickString(photometric,"MONOCHROME1 ",MaxTextExtent); info.polarity=MagickFalse; info.scale=(Quantum *) NULL; info.bits_allocated=8; info.bytes_per_pixel=1; info.depth=8; info.mask=0xffff; info.max_value=255UL; info.samples_per_pixel=1; info.signed_data=(~0UL); info.significant_bits=0; info.rescale=MagickFalse; info.rescale_intercept=0.0; info.rescale_slope=1.0; info.window_center=0.0; info.window_width=0.0; data=(unsigned char *) NULL; element=0; explicit_vr[2]='\0'; explicit_file=MagickFalse; colors=0; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; graymap=(int *) NULL; height=0; number_scenes=1; sequence=MagickFalse; use_explicit=MagickFalse; explicit_retry = MagickFalse; width=0; for (group=0; (group != 0x7FE0) || (element != 0x0010) || (sequence != MagickFalse); ) { /* Read a group. */ image->offset=(ssize_t) TellBlob(image); group=ReadBlobLSBShort(image); element=ReadBlobLSBShort(image); if ((group != 0x0002) && (image->endian == MSBEndian)) { group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF)); element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF)); } quantum=0; /* Find corresponding VR for this group and element. */ for (i=0; dicom_info[i].group < 0xffff; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) CopyMagickString(implicit_vr,dicom_info[i].vr,MaxTextExtent); count=ReadBlob(image,2,(unsigned char *) explicit_vr); if (count != 2) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); /* Check for "explicitness", but meta-file headers always explicit. */ if ((explicit_file == MagickFalse) && (group != 0x0002)) explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) && (isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ? MagickTrue : MagickFalse; use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) || (explicit_file != MagickFalse) ? MagickTrue : MagickFalse; if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0)) (void) CopyMagickString(implicit_vr,explicit_vr,MaxTextExtent); if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0)) { offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR); if (offset < 0) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); quantum=4; } else { /* Assume explicit type. */ quantum=2; if ((strncmp(explicit_vr,"OB",2) == 0) || (strncmp(explicit_vr,"UN",2) == 0) || (strncmp(explicit_vr,"OW",2) == 0) || (strncmp(explicit_vr,"SQ",2) == 0)) { (void) ReadBlobLSBShort(image); quantum=4; } } datum=0; if (quantum == 4) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if (quantum == 2) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } quantum=0; length=1; if (datum != 0) { if ((strncmp(implicit_vr,"SS",2) == 0) || (strncmp(implicit_vr,"US",2) == 0)) quantum=2; else if ((strncmp(implicit_vr,"UL",2) == 0) || (strncmp(implicit_vr,"SL",2) == 0) || (strncmp(implicit_vr,"FL",2) == 0)) quantum=4; else if (strncmp(implicit_vr,"FD",2) != 0) quantum=1; else quantum=8; if (datum != ~0) length=(size_t) datum/quantum; else { /* Sequence and item of undefined length. */ quantum=0; length=0; } } if (image_info->verbose != MagickFalse) { /* Display Dicom info. */ if (use_explicit == MagickFalse) explicit_vr[0]='\0'; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)", (unsigned long) image->offset,(long) length,implicit_vr,explicit_vr, (unsigned long) group,(unsigned long) element); if (dicom_info[i].description != (char *) NULL) (void) FormatLocaleFile(stdout," %s",dicom_info[i].description); (void) FormatLocaleFile(stdout,": "); } if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"\n"); break; } /* Allocate space and read an array. */ data=(unsigned char *) NULL; if ((length == 1) && (quantum == 1)) datum=ReadBlobByte(image); else if ((length == 1) && (quantum == 2)) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } else if ((length == 1) && (quantum == 4)) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if ((quantum != 0) && (length != 0)) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); if (~length >= 1) data=(unsigned char *) AcquireQuantumMemory(length+1,quantum* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) quantum*length,data); if (count != (ssize_t) (quantum*length)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"count=%d quantum=%d " "length=%d group=%d\n",(int) count,(int) quantum,(int) length,(int) group); ThrowDCMException(CorruptImageError, "InsufficientImageDataInFile"); } data[length*quantum]='\0'; } else if ((unsigned int) datum == 0xFFFFFFFFU) { sequence=MagickTrue; continue; } if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); sequence=MagickFalse; continue; } if (sequence != MagickFalse) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); continue; } switch (group) { case 0x0002: { switch (element) { case 0x0010: { char transfer_syntax[MaxTextExtent]; /* Transfer Syntax. */ if ((datum == 0) && (explicit_retry == MagickFalse)) { explicit_retry=MagickTrue; (void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET); group=0; element=0; if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout, "Corrupted image - trying explicit format\n"); break; } *transfer_syntax='\0'; if (data != (unsigned char *) NULL) (void) CopyMagickString(transfer_syntax,(char *) data, MaxTextExtent); if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"transfer_syntax=%s\n", (const char *) transfer_syntax); if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0) { int count, subtype, type; type=1; subtype=0; if (strlen(transfer_syntax) > 17) { count=sscanf(transfer_syntax+17,".%d.%d",&type,&subtype); if (count < 1) ThrowDCMException(CorruptImageError, "ImproperImageHeader"); } switch (type) { case 1: { image->endian=LSBEndian; break; } case 2: { image->endian=MSBEndian; break; } case 4: { if ((subtype >= 80) && (subtype <= 81)) image->compression=JPEGCompression; else if ((subtype >= 90) && (subtype <= 93)) image->compression=JPEG2000Compression; else image->compression=JPEGCompression; break; } case 5: { image->compression=RLECompression; break; } } } break; } default: break; } break; } case 0x0028: { switch (element) { case 0x0002: { /* Samples per pixel. */ info.samples_per_pixel=(size_t) datum; break; } case 0x0004: { /* Photometric interpretation. */ if (data == (unsigned char *) NULL) break; for (i=0; i < (ssize_t) MagickMin(length,MaxTextExtent-1); i++) photometric[i]=(char) data[i]; photometric[i]='\0'; info.polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ? MagickTrue : MagickFalse; break; } case 0x0006: { /* Planar configuration. */ if (datum == 1) image->interlace=PlaneInterlace; break; } case 0x0008: { /* Number of frames. */ if (data == (unsigned char *) NULL) break; number_scenes=StringToUnsignedLong((char *) data); break; } case 0x0010: { /* Image rows. */ height=(size_t) datum; break; } case 0x0011: { /* Image columns. */ width=(size_t) datum; break; } case 0x0100: { /* Bits allocated. */ info.bits_allocated=(size_t) datum; info.bytes_per_pixel=1; if (datum > 8) info.bytes_per_pixel=2; info.depth=info.bits_allocated; if (info.depth > 32) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); info.max_value=(1UL << info.bits_allocated)-1; image->depth=info.depth; break; } case 0x0101: { /* Bits stored. */ info.significant_bits=(size_t) datum; info.bytes_per_pixel=1; if (info.significant_bits > 8) info.bytes_per_pixel=2; info.depth=info.significant_bits; if (info.depth > 32) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); info.max_value=(1UL << info.significant_bits)-1; info.mask=(size_t) GetQuantumRange(info.significant_bits); image->depth=info.depth; break; } case 0x0102: { /* High bit. */ break; } case 0x0103: { /* Pixel representation. */ info.signed_data=(size_t) datum; break; } case 0x1050: { /* Visible pixel range: center. */ if (data != (unsigned char *) NULL) info.window_center=StringToDouble((char *) data, (char **) NULL); break; } case 0x1051: { /* Visible pixel range: width. */ if (data != (unsigned char *) NULL) info.window_width=StringToDouble((char *) data, (char **) NULL); break; } case 0x1052: { /* Rescale intercept */ if (data != (unsigned char *) NULL) info.rescale_intercept=StringToDouble((char *) data, (char **) NULL); break; } case 0x1053: { /* Rescale slope */ if (data != (unsigned char *) NULL) info.rescale_slope=StringToDouble((char *) data, (char **) NULL); break; } case 0x1200: case 0x3006: { /* Populate graymap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/info.bytes_per_pixel); datum=(int) colors; graymap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*graymap)); if (graymap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) colors; i++) if (info.bytes_per_pixel == 1) graymap[i]=(int) data[i]; else graymap[i]=(int) ((short *) data)[i]; break; } case 0x1201: { unsigned short index; /* Populate redmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; redmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*redmap)); if (redmap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); redmap[i]=(int) index; p+=2; } break; } case 0x1202: { unsigned short index; /* Populate greenmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; greenmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*greenmap)); if (greenmap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); greenmap[i]=(int) index; p+=2; } break; } case 0x1203: { unsigned short index; /* Populate bluemap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; bluemap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*bluemap)); if (bluemap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); bluemap[i]=(int) index; p+=2; } break; } default: break; } break; } case 0x2050: { switch (element) { case 0x0020: { if ((data != (unsigned char *) NULL) && (strncmp((char *) data,"INVERSE",7) == 0)) info.polarity=MagickTrue; break; } default: break; } break; } default: break; } if (data != (unsigned char *) NULL) { char *attribute; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; if (dicom_info[i].description != (char *) NULL) { attribute=AcquireString("dcm:"); (void) ConcatenateString(&attribute,dicom_info[i].description); for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i == (ssize_t) length) || (length > 4)) { (void) SubstituteString(&attribute," ",""); (void) SetImageProperty(image,attribute,(char *) data); } attribute=DestroyString(attribute); } } if (image_info->verbose != MagickFalse) { if (data == (unsigned char *) NULL) (void) FormatLocaleFile(stdout,"%d\n",datum); else { /* Display group data. */ for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i != (ssize_t) length) && (length <= 4)) { ssize_t j; datum=0; for (j=(ssize_t) length-1; j >= 0; j--) datum=(256*datum+data[j]); (void) FormatLocaleFile(stdout,"%d",datum); } else for (i=0; i < (ssize_t) length; i++) if (isprint((int) data[i]) != MagickFalse) (void) FormatLocaleFile(stdout,"%c",data[i]); else (void) FormatLocaleFile(stdout,"%c",'.'); (void) FormatLocaleFile(stdout,"\n"); } } if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } if ((width == 0) || (height == 0)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); image->columns=(size_t) width; image->rows=(size_t) height; if (info.signed_data == 0xffff) info.signed_data=(size_t) (info.significant_bits == 16 ? 1 : 0); if ((image->compression == JPEGCompression) || (image->compression == JPEG2000Compression)) { Image *images; ImageInfo *read_info; int c; size_t length; unsigned int tag; /* Read offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } /* Handle non-native image formats. */ read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); images=NewImageList(); for (scene=0; scene < (ssize_t) number_scenes; scene++) { char filename[MaxTextExtent]; const char *property; FILE *file; Image *jpeg_image; int unique_file; unsigned int tag; tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); length=(size_t) ReadBlobLSBLong(image); if (tag == 0xFFFEE0DD) break; /* sequence delimiter tag */ if (tag != 0xFFFEE000) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if (file == (FILE *) NULL) { (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError, "UnableToCreateTemporaryFile",filename); break; } for ( ; length != 0; length--) { c=ReadBlobByte(image); if (c == EOF) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } (void) fputc(c,file); } (void) fclose(file); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s", filename); if (image->compression == JPEG2000Compression) (void) FormatLocaleString(read_info->filename,MaxTextExtent,"j2k:%s", filename); jpeg_image=ReadImage(read_info,exception); if (jpeg_image != (Image *) NULL) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) SetImageProperty(jpeg_image,property, GetImageProperty(image,property)); property=GetNextImageProperty(image); } AppendImageToList(&images,jpeg_image); } (void) RelinquishUniqueFileResource(filename); } read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return(GetFirstImageInList(images)); } if (info.depth != (1UL*MAGICKCORE_QUANTUM_DEPTH)) { QuantumAny range; size_t length; /* Compute pixel scaling table. */ length=(size_t) (GetQuantumRange(info.depth)+1); info.scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*info.scale)); if (info.scale == (Quantum *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); range=GetQuantumRange(info.depth); for (i=0; i <= (ssize_t) GetQuantumRange(info.depth); i++) info.scale[i]=ScaleAnyToQuantum((size_t) i,range); } if (image->compression == RLECompression) { size_t length; unsigned int tag; /* Read RLE offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image)+8; for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } } for (scene=0; scene < (ssize_t) number_scenes; scene++) { if (image_info->ping != MagickFalse) break; image->columns=(size_t) width; image->rows=(size_t) height; image->depth=info.depth; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); break; } image->colorspace=RGBColorspace; if ((image->colormap == (PixelPacket *) NULL) && (info.samples_per_pixel == 1)) { int index; size_t one; one=1; if (colors == 0) colors=one << info.depth; if (AcquireImageColormap(image,colors) == MagickFalse) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); if (redmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=redmap[i]; if ((info.scale != (Quantum *) NULL) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(Quantum) index; } if (greenmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=greenmap[i]; if ((info.scale != (Quantum *) NULL) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].green=(Quantum) index; } if (bluemap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=bluemap[i]; if ((info.scale != (Quantum *) NULL) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].blue=(Quantum) index; } if (graymap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=graymap[i]; if ((info.scale != (Quantum *) NULL) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(Quantum) index; image->colormap[i].green=(Quantum) index; image->colormap[i].blue=(Quantum) index; } } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE segment table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); stream_info->remaining=(size_t) ReadBlobLSBLong(image); if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) || (EOFBlob(image) != MagickFalse)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); stream_info->count=0; stream_info->segment_count=ReadBlobLSBLong(image); for (i=0; i < 15; i++) stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image); stream_info->remaining-=64; if (stream_info->segment_count > 1) { info.bytes_per_pixel=1; info.depth=8; if (stream_info->offset_count > 0) (void) SeekBlob(image,stream_info->offsets[0]+ stream_info->segments[0],SEEK_SET); } } if ((info.samples_per_pixel > 1) && (image->interlace == PlaneInterlace)) { register ssize_t x; register PixelPacket *q; ssize_t y; /* Convert Planar RGB DCM Medical image to pixel packets. */ for (i=0; i < (ssize_t) info.samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { switch ((int) i) { case 0: { SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image))); break; } case 1: { SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image))); break; } case 2: { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image))); break; } case 3: { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image))); break; } default: break; } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } } else { const char *option; /* Convert DCM Medical image to pixel packets. */ option=GetImageOption(image_info,"dcm:display-range"); if (option != (const char *) NULL) { if (LocaleCompare(option,"reset") == 0) info.window_width=0; } option=GetImageOption(image_info,"dcm:window"); if (option != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(option,&geometry_info); if (flags & RhoValue) info.window_center=geometry_info.rho; if (flags & SigmaValue) info.window_width=geometry_info.sigma; info.rescale=MagickTrue; } option=GetImageOption(image_info,"dcm:rescale"); if (option != (char *) NULL) info.rescale=IsStringTrue(option); if ((info.window_center != 0) && (info.window_width == 0)) info.window_width=info.window_center; status=ReadDCMPixels(image,&info,stream_info,MagickTrue,exception); if ((status != MagickFalse) && (stream_info->segment_count > 1)) { if (stream_info->offset_count > 0) (void) SeekBlob(image,stream_info->offsets[0]+ stream_info->segments[1],SEEK_SET); (void) ReadDCMPixels(image,&info,stream_info,MagickFalse,exception); } } if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (scene < (ssize_t) (number_scenes-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } /* Free resources. */ if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r D C M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterDCMImage() adds attributes for the DCM image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterDCMImage method is: % % size_t RegisterDCMImage(void) % */ ModuleExport size_t RegisterDCMImage(void) { MagickInfo *entry; static const char *DCMNote= { "DICOM is used by the medical community for images like X-rays. The\n" "specification, \"Digital Imaging and Communications in Medicine\n" "(DICOM)\", is available at http://medical.nema.org/. In particular,\n" "see part 5 which describes the image encoding (RLE, JPEG, JPEG-LS),\n" "and supplement 61 which adds JPEG-2000 encoding." }; entry=SetMagickInfo("DCM"); entry->decoder=(DecodeImageHandler *) ReadDCMImage; entry->magick=(IsImageFormatHandler *) IsDCM; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Digital Imaging and Communications in Medicine image"); entry->note=ConstantString(DCMNote); entry->module=ConstantString("DCM"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r D C M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterDCMImage() removes format registrations made by the % DCM module from the list of supported formats. % % The format of the UnregisterDCMImage method is: % % UnregisterDCMImage(void) % */ ModuleExport void UnregisterDCMImage(void) { (void) UnregisterMagickInfo("DCM"); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2615_0
crossvul-cpp_data_good_2557_0
/* * Copyright (C) 2015 Red Hat, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "virtgpu_drv.h" static void virtio_gpu_ttm_bo_destroy(struct ttm_buffer_object *tbo) { struct virtio_gpu_object *bo; struct virtio_gpu_device *vgdev; bo = container_of(tbo, struct virtio_gpu_object, tbo); vgdev = (struct virtio_gpu_device *)bo->gem_base.dev->dev_private; if (bo->hw_res_handle) virtio_gpu_cmd_unref_resource(vgdev, bo->hw_res_handle); if (bo->pages) virtio_gpu_object_free_sg_table(bo); drm_gem_object_release(&bo->gem_base); kfree(bo); } static void virtio_gpu_init_ttm_placement(struct virtio_gpu_object *vgbo, bool pinned) { u32 c = 1; u32 pflag = pinned ? TTM_PL_FLAG_NO_EVICT : 0; vgbo->placement.placement = &vgbo->placement_code; vgbo->placement.busy_placement = &vgbo->placement_code; vgbo->placement_code.fpfn = 0; vgbo->placement_code.lpfn = 0; vgbo->placement_code.flags = TTM_PL_MASK_CACHING | TTM_PL_FLAG_TT | pflag; vgbo->placement.num_placement = c; vgbo->placement.num_busy_placement = c; } int virtio_gpu_object_create(struct virtio_gpu_device *vgdev, unsigned long size, bool kernel, bool pinned, struct virtio_gpu_object **bo_ptr) { struct virtio_gpu_object *bo; enum ttm_bo_type type; size_t acc_size; int ret; if (kernel) type = ttm_bo_type_kernel; else type = ttm_bo_type_device; *bo_ptr = NULL; acc_size = ttm_bo_dma_acc_size(&vgdev->mman.bdev, size, sizeof(struct virtio_gpu_object)); bo = kzalloc(sizeof(struct virtio_gpu_object), GFP_KERNEL); if (bo == NULL) return -ENOMEM; size = roundup(size, PAGE_SIZE); ret = drm_gem_object_init(vgdev->ddev, &bo->gem_base, size); if (ret != 0) { kfree(bo); return ret; } bo->dumb = false; virtio_gpu_init_ttm_placement(bo, pinned); ret = ttm_bo_init(&vgdev->mman.bdev, &bo->tbo, size, type, &bo->placement, 0, !kernel, NULL, acc_size, NULL, NULL, &virtio_gpu_ttm_bo_destroy); /* ttm_bo_init failure will call the destroy */ if (ret != 0) return ret; *bo_ptr = bo; return 0; } int virtio_gpu_object_kmap(struct virtio_gpu_object *bo, void **ptr) { bool is_iomem; int r; if (bo->vmap) { if (ptr) *ptr = bo->vmap; return 0; } r = ttm_bo_kmap(&bo->tbo, 0, bo->tbo.num_pages, &bo->kmap); if (r) return r; bo->vmap = ttm_kmap_obj_virtual(&bo->kmap, &is_iomem); if (ptr) *ptr = bo->vmap; return 0; } int virtio_gpu_object_get_sg_table(struct virtio_gpu_device *qdev, struct virtio_gpu_object *bo) { int ret; struct page **pages = bo->tbo.ttm->pages; int nr_pages = bo->tbo.num_pages; /* wtf swapping */ if (bo->pages) return 0; if (bo->tbo.ttm->state == tt_unpopulated) bo->tbo.ttm->bdev->driver->ttm_tt_populate(bo->tbo.ttm); bo->pages = kmalloc(sizeof(struct sg_table), GFP_KERNEL); if (!bo->pages) goto out; ret = sg_alloc_table_from_pages(bo->pages, pages, nr_pages, 0, nr_pages << PAGE_SHIFT, GFP_KERNEL); if (ret) goto out; return 0; out: kfree(bo->pages); bo->pages = NULL; return -ENOMEM; } void virtio_gpu_object_free_sg_table(struct virtio_gpu_object *bo) { sg_free_table(bo->pages); kfree(bo->pages); bo->pages = NULL; } int virtio_gpu_object_wait(struct virtio_gpu_object *bo, bool no_wait) { int r; r = ttm_bo_reserve(&bo->tbo, true, no_wait, NULL); if (unlikely(r != 0)) return r; r = ttm_bo_wait(&bo->tbo, true, no_wait); ttm_bo_unreserve(&bo->tbo); return r; }
./CrossVul/dataset_final_sorted/CWE-772/c/good_2557_0
crossvul-cpp_data_bad_2623_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA L SSSSS % % C A A L SS % % C AAAAA L SSS % % C A A L SS % % CCCC A A LLLLL SSSSS % % % % % % Read/Write CALS Raster Group 1 Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The CALS raster format is a standard developed by the Computer Aided % Acquisition and Logistics Support (CALS) office of the United States % Department of Defense to standardize graphics data interchange for % electronic publishing, especially in the areas of technical graphics, % CAD/CAM, and image processing applications. % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/colorspace.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #if defined(MAGICKCORE_TIFF_DELEGATE) /* Forward declarations. */ static MagickBooleanType WriteCALSImage(const ImageInfo *,Image *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s C A L S % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsCALS() returns MagickTrue if the image format type, identified by the % magick string, is CALS Raster Group 1. % % The format of the IsCALS method is: % % MagickBooleanType IsCALS(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsCALS(const unsigned char *magick,const size_t length) { if (length < 128) return(MagickFalse); if (LocaleNCompare((const char *) magick,"version: MIL-STD-1840",21) == 0) return(MagickTrue); if (LocaleNCompare((const char *) magick,"srcdocid:",9) == 0) return(MagickTrue); if (LocaleNCompare((const char *) magick,"rorient:",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d C A L S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadCALSImage() reads an CALS Raster Group 1 image format image file and % returns it. It allocates the memory necessary for the new Image structure % and returns a pointer to the new image. % % The format of the ReadCALSImage method is: % % Image *ReadCALSImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadCALSImage(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MaxTextExtent], header[129], message[MaxTextExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register ssize_t i; unsigned long density, direction, height, orientation, pel_path, type, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read CALS header. */ (void) ResetMagickMemory(header,0,sizeof(header)); density=0; direction=0; orientation=1; pel_path=0; type=1; width=0; height=0; for (i=0; i < 16; i++) { if (ReadBlob(image,128,(unsigned char *) header) != 128) break; switch (*header) { case 'R': case 'r': { if (LocaleNCompare(header,"rdensty:",8) == 0) { (void) sscanf(header+8,"%lu",&density); break; } if (LocaleNCompare(header,"rpelcnt:",8) == 0) { (void) sscanf(header+8,"%lu,%lu",&width,&height); break; } if (LocaleNCompare(header,"rorient:",8) == 0) { (void) sscanf(header+8,"%lu,%lu",&pel_path,&direction); if (pel_path == 90) orientation=5; else if (pel_path == 180) orientation=3; else if (pel_path == 270) orientation=7; if (direction == 90) orientation++; break; } if (LocaleNCompare(header,"rtype:",6) == 0) { (void) sscanf(header+6,"%lu",&type); break; } break; } } } /* Read CALS pixels. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); while ((c=ReadBlobByte(image)) != EOF) (void) fputc(c,file); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"group4:%s", filename); (void) FormatLocaleString(message,MaxTextExtent,"%lux%lu",width,height); read_info->size=ConstantString(message); (void) FormatLocaleString(message,MaxTextExtent,"%lu",density); read_info->density=ConstantString(message); read_info->orientation=(OrientationType) orientation; image=ReadImage(read_info,exception); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick,"CALS",MaxTextExtent); } read_info=DestroyImageInfo(read_info); (void) RelinquishUniqueFileResource(filename); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r C A L S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterCALSImage() adds attributes for the CALS Raster Group 1 image file % image format to the list of supported formats. The attributes include the % image format tag, a method to read and/or write the format, whether the % format supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief description % of the format. % % The format of the RegisterCALSImage method is: % % size_t RegisterCALSImage(void) % */ ModuleExport size_t RegisterCALSImage(void) { MagickInfo *entry; static const char *CALSDescription= { "Continuous Acquisition and Life-cycle Support Type 1" }, *CALSNote= { "Specified in MIL-R-28002 and MIL-PRF-28002" }; entry=SetMagickInfo("CAL"); entry->decoder=(DecodeImageHandler *) ReadCALSImage; #if defined(MAGICKCORE_TIFF_DELEGATE) entry->encoder=(EncodeImageHandler *) WriteCALSImage; #endif entry->adjoin=MagickFalse; entry->magick=(IsImageFormatHandler *) IsCALS; entry->description=ConstantString(CALSDescription); entry->note=ConstantString(CALSNote); entry->module=ConstantString("CALS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("CALS"); entry->decoder=(DecodeImageHandler *) ReadCALSImage; #if defined(MAGICKCORE_TIFF_DELEGATE) entry->encoder=(EncodeImageHandler *) WriteCALSImage; #endif entry->adjoin=MagickFalse; entry->magick=(IsImageFormatHandler *) IsCALS; entry->description=ConstantString(CALSDescription); entry->note=ConstantString(CALSNote); entry->module=ConstantString("CALS"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r C A L S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterCALSImage() removes format registrations made by the % CALS module from the list of supported formats. % % The format of the UnregisterCALSImage method is: % % UnregisterCALSImage(void) % */ ModuleExport void UnregisterCALSImage(void) { (void) UnregisterMagickInfo("CAL"); (void) UnregisterMagickInfo("CALS"); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e C A L S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteCALSImage() writes an image to a file in CALS Raster Group 1 image % format. % % The format of the WriteCALSImage method is: % % MagickBooleanType WriteCALSImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static ssize_t WriteCALSRecord(Image *image,const char *data) { char pad[128]; register const char *p; register ssize_t i; ssize_t count; i=0; count=0; if (data != (const char *) NULL) { p=data; for (i=0; (i < 128) && (p[i] != '\0'); i++); count=WriteBlob(image,(size_t) i,(const unsigned char *) data); } if (i < 128) { i=128-i; (void) ResetMagickMemory(pad,' ',(size_t) i); count=WriteBlob(image,(size_t) i,(const unsigned char *) pad); } return(count); } static MagickBooleanType WriteCALSImage(const ImageInfo *image_info, Image *image) { char header[MaxTextExtent]; Image *group4_image; ImageInfo *write_info; MagickBooleanType status; register ssize_t i; size_t density, length, orient_x, orient_y; ssize_t count; unsigned char *group4; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Create standard CALS header. */ count=WriteCALSRecord(image,"srcdocid: NONE"); (void) count; count=WriteCALSRecord(image,"dstdocid: NONE"); count=WriteCALSRecord(image,"txtfilid: NONE"); count=WriteCALSRecord(image,"figid: NONE"); count=WriteCALSRecord(image,"srcgph: NONE"); count=WriteCALSRecord(image,"doccls: NONE"); count=WriteCALSRecord(image,"rtype: 1"); orient_x=0; orient_y=0; switch (image->orientation) { case TopRightOrientation: { orient_x=180; orient_y=270; break; } case BottomRightOrientation: { orient_x=180; orient_y=90; break; } case BottomLeftOrientation: { orient_y=90; break; } case LeftTopOrientation: { orient_x=270; break; } case RightTopOrientation: { orient_x=270; orient_y=180; break; } case RightBottomOrientation: { orient_x=90; orient_y=180; break; } case LeftBottomOrientation: { orient_x=90; break; } default: { orient_y=270; break; } } (void) FormatLocaleString(header,sizeof(header),"rorient: %03ld,%03ld", (long) orient_x,(long) orient_y); count=WriteCALSRecord(image,header); (void) FormatLocaleString(header,sizeof(header),"rpelcnt: %06lu,%06lu", (unsigned long) image->columns,(unsigned long) image->rows); count=WriteCALSRecord(image,header); density=200; if (image_info->density != (char *) NULL) { GeometryInfo geometry_info; (void) ParseGeometry(image_info->density,&geometry_info); density=(size_t) floor(geometry_info.rho+0.5); } (void) FormatLocaleString(header,sizeof(header),"rdensty: %04lu", (unsigned long) density); count=WriteCALSRecord(image,header); count=WriteCALSRecord(image,"notes: NONE"); (void) ResetMagickMemory(header,' ',128); for (i=0; i < 5; i++) (void) WriteBlob(image,128,(unsigned char *) header); /* Write CALS pixels. */ write_info=CloneImageInfo(image_info); (void) CopyMagickString(write_info->filename,"GROUP4:",MaxTextExtent); (void) CopyMagickString(write_info->magick,"GROUP4",MaxTextExtent); group4_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (group4_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length, &image->exception); group4_image=DestroyImage(group4_image); if (group4 == (unsigned char *) NULL) { (void) CloseBlob(image); return(MagickFalse); } write_info=DestroyImageInfo(write_info); if (WriteBlob(image,length,group4) != (ssize_t) length) status=MagickFalse; group4=(unsigned char *) RelinquishMagickMemory(group4); (void) CloseBlob(image); return(status); } #endif
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2623_0
crossvul-cpp_data_bad_3450_2
/* ruleset.c - rsyslog's ruleset object * * We have a two-way structure of linked lists: one global linked list * (llAllRulesets) hold alls rule sets that we know. Included in each * list is a list of rules (which contain a list of actions, but that's * a different story). * * Usually, only a single rule set is executed. However, there exist some * situations where all rules must be iterated over, for example on HUP. Thus, * we also provide interfaces to do that. * * Module begun 2009-06-10 by Rainer Gerhards * * Copyright 2009 Rainer Gerhards and Adiscon GmbH. * * This file is part of the rsyslog runtime library. * * The rsyslog runtime library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The rsyslog runtime library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the rsyslog runtime library. If not, see <http://www.gnu.org/licenses/>. * * A copy of the GPL can be found in the file "COPYING" in this distribution. * A copy of the LGPL can be found in the file "COPYING.LESSER" in this distribution. */ #include "config.h" #include <stdlib.h> #include <string.h> #include <assert.h> #include <ctype.h> #include "rsyslog.h" #include "obj.h" #include "cfsysline.h" #include "msg.h" #include "ruleset.h" #include "rule.h" #include "errmsg.h" #include "parser.h" #include "batch.h" #include "unicode-helper.h" #include "dirty.h" /* for main ruleset queue creation */ /* static data */ DEFobjStaticHelpers DEFobjCurrIf(errmsg) DEFobjCurrIf(rule) DEFobjCurrIf(parser) linkedList_t llRulesets; /* this is NOT a pointer - no typo here ;) */ ruleset_t *pCurrRuleset = NULL; /* currently "active" ruleset */ ruleset_t *pDfltRuleset = NULL; /* current default ruleset, e.g. for binding to actions which have no other */ /* forward definitions */ static rsRetVal processBatch(batch_t *pBatch); /* ---------- linked-list key handling functions ---------- */ /* destructor for linked list keys. */ static rsRetVal keyDestruct(void __attribute__((unused)) *pData) { free(pData); return RS_RET_OK; } /* ---------- END linked-list key handling functions ---------- */ /* driver to iterate over all of this ruleset actions */ typedef struct iterateAllActions_s { rsRetVal (*pFunc)(void*, void*); void *pParam; } iterateAllActions_t; DEFFUNC_llExecFunc(doIterateRulesetActions) { DEFiRet; rule_t* pRule = (rule_t*) pData; iterateAllActions_t *pMyParam = (iterateAllActions_t*) pParam; iRet = rule.IterateAllActions(pRule, pMyParam->pFunc, pMyParam->pParam); RETiRet; } /* iterate over all actions of THIS rule set. */ static rsRetVal iterateRulesetAllActions(ruleset_t *pThis, rsRetVal (*pFunc)(void*, void*), void* pParam) { iterateAllActions_t params; DEFiRet; assert(pFunc != NULL); params.pFunc = pFunc; params.pParam = pParam; CHKiRet(llExecFunc(&(pThis->llRules), doIterateRulesetActions, &params)); finalize_it: RETiRet; } /* driver to iterate over all actions */ DEFFUNC_llExecFunc(doIterateAllActions) { DEFiRet; ruleset_t* pThis = (ruleset_t*) pData; iterateAllActions_t *pMyParam = (iterateAllActions_t*) pParam; iRet = iterateRulesetAllActions(pThis, pMyParam->pFunc, pMyParam->pParam); RETiRet; } /* iterate over ALL actions present in the WHOLE system. * this is often needed, for example when HUP processing * must be done or a shutdown is pending. */ static rsRetVal iterateAllActions(rsRetVal (*pFunc)(void*, void*), void* pParam) { iterateAllActions_t params; DEFiRet; assert(pFunc != NULL); params.pFunc = pFunc; params.pParam = pParam; CHKiRet(llExecFunc(&llRulesets, doIterateAllActions, &params)); finalize_it: RETiRet; } /* helper to processBatch(), used to call the configured actions. It is * executed from within llExecFunc() of the action list. * rgerhards, 2007-08-02 */ DEFFUNC_llExecFunc(processBatchDoRules) { rsRetVal iRet; ISOBJ_TYPE_assert(pData, rule); dbgprintf("Processing next rule\n"); iRet = rule.ProcessBatch((rule_t*) pData, (batch_t*) pParam); dbgprintf("ruleset: get iRet %d from rule.ProcessMsg()\n", iRet); return iRet; } /* This function is similar to processBatch(), but works on a batch that * contains rules from multiple rulesets. In this case, we can not push * the whole batch through the ruleset. Instead, we examine it and * partition it into sub-rulesets which we then push through the system. * Note that when we evaluate which message must be processed, we do NOT need * to look at bFilterOK, because this value is only set in a later processing * stage. Doing so caused a bug during development ;) * rgerhards, 2010-06-15 */ static inline rsRetVal processBatchMultiRuleset(batch_t *pBatch) { ruleset_t *currRuleset; batch_t snglRuleBatch; int i; int iStart; /* start index of partial batch */ int iNew; /* index for new (temporary) batch */ DEFiRet; CHKiRet(batchInit(&snglRuleBatch, pBatch->nElem)); snglRuleBatch.pbShutdownImmediate = pBatch->pbShutdownImmediate; while(1) { /* loop broken inside */ /* search for first unprocessed element */ for(iStart = 0 ; iStart < pBatch->nElem && pBatch->pElem[iStart].state == BATCH_STATE_DISC ; ++iStart) /* just search, no action */; if(iStart == pBatch->nElem) FINALIZE; /* everything processed */ /* prepare temporary batch */ currRuleset = batchElemGetRuleset(pBatch, iStart); iNew = 0; for(i = iStart ; i < pBatch->nElem ; ++i) { if(batchElemGetRuleset(pBatch, i) == currRuleset) { batchCopyElem(&(snglRuleBatch.pElem[iNew++]), &(pBatch->pElem[i])); /* We indicate the element also as done, so it will not be processed again */ pBatch->pElem[i].state = BATCH_STATE_DISC; } } snglRuleBatch.nElem = iNew; /* was left just right by the for loop */ batchSetSingleRuleset(&snglRuleBatch, 1); /* process temp batch */ processBatch(&snglRuleBatch); } batchFree(&snglRuleBatch); finalize_it: RETiRet; } /* Process (consume) a batch of messages. Calls the actions configured. * If the whole batch uses a singel ruleset, we can process the batch as * a whole. Otherwise, we need to process it slower, on a message-by-message * basis (what can be optimized to a per-ruleset basis) * rgerhards, 2005-10-13 */ static rsRetVal processBatch(batch_t *pBatch) { ruleset_t *pThis; DEFiRet; assert(pBatch != NULL); dbgprintf("ZZZ: processBatch: batch of %d elements must be processed\n", pBatch->nElem); if(pBatch->bSingleRuleset) { pThis = batchGetRuleset(pBatch); if(pThis == NULL) pThis = pDfltRuleset; ISOBJ_TYPE_assert(pThis, ruleset); CHKiRet(llExecFunc(&pThis->llRules, processBatchDoRules, pBatch)); } else { CHKiRet(processBatchMultiRuleset(pBatch)); } finalize_it: dbgprintf("ruleset.ProcessMsg() returns %d\n", iRet); RETiRet; } /* return the ruleset-assigned parser list. NULL means use the default * parser list. * rgerhards, 2009-11-04 */ static parserList_t* GetParserList(msg_t *pMsg) { return (pMsg->pRuleset == NULL) ? pDfltRuleset->pParserLst : pMsg->pRuleset->pParserLst; } /* Add a new rule to the end of the current rule set. We do a number * of checks and ignore the rule if it does not pass them. */ static rsRetVal addRule(ruleset_t *pThis, rule_t **ppRule) { int iActionCnt; DEFiRet; ISOBJ_TYPE_assert(pThis, ruleset); ISOBJ_TYPE_assert(*ppRule, rule); CHKiRet(llGetNumElts(&(*ppRule)->llActList, &iActionCnt)); if(iActionCnt == 0) { errmsg.LogError(0, NO_ERRCODE, "warning: selector line without actions will be discarded"); rule.Destruct(ppRule); } else { CHKiRet(llAppend(&pThis->llRules, NULL, *ppRule)); dbgprintf("selector line successfully processed\n"); } finalize_it: RETiRet; } /* set name for ruleset */ static rsRetVal setName(ruleset_t *pThis, uchar *pszName) { DEFiRet; free(pThis->pszName); CHKmalloc(pThis->pszName = ustrdup(pszName)); finalize_it: RETiRet; } /* get current ruleset * We use a non-standard calling interface, as nothing can go wrong and it * is really much more natural to return the pointer directly. */ static ruleset_t* GetCurrent(void) { return pCurrRuleset; } /* get main queue associated with ruleset. If no ruleset-specifc main queue * is set, the primary main message queue is returned. * We use a non-standard calling interface, as nothing can go wrong and it * is really much more natural to return the pointer directly. */ static qqueue_t* GetRulesetQueue(ruleset_t *pThis) { ISOBJ_TYPE_assert(pThis, ruleset); return (pThis->pQueue == NULL) ? pMsgQueue : pThis->pQueue; } /* Find the ruleset with the given name and return a pointer to its object. */ static rsRetVal GetRuleset(ruleset_t **ppRuleset, uchar *pszName) { DEFiRet; assert(ppRuleset != NULL); assert(pszName != NULL); CHKiRet(llFind(&llRulesets, pszName, (void*) ppRuleset)); finalize_it: RETiRet; } /* Set a new default rule set. If the default can not be found, no change happens. */ static rsRetVal SetDefaultRuleset(uchar *pszName) { ruleset_t *pRuleset; DEFiRet; assert(pszName != NULL); CHKiRet(GetRuleset(&pRuleset, pszName)); pDfltRuleset = pRuleset; dbgprintf("default rule set changed to %p: '%s'\n", pRuleset, pszName); finalize_it: RETiRet; } /* Set a new current rule set. If the ruleset can not be found, no change happens. */ static rsRetVal SetCurrRuleset(uchar *pszName) { ruleset_t *pRuleset; DEFiRet; assert(pszName != NULL); CHKiRet(GetRuleset(&pRuleset, pszName)); pCurrRuleset = pRuleset; dbgprintf("current rule set changed to %p: '%s'\n", pRuleset, pszName); finalize_it: RETiRet; } /* destructor we need to destruct rules inside our linked list contents. */ static rsRetVal doRuleDestruct(void *pData) { rule_t *pRule = (rule_t *) pData; DEFiRet; rule.Destruct(&pRule); RETiRet; } /* Standard-Constructor */ BEGINobjConstruct(ruleset) /* be sure to specify the object type also in END macro! */ CHKiRet(llInit(&pThis->llRules, doRuleDestruct, NULL, NULL)); finalize_it: ENDobjConstruct(ruleset) /* ConstructionFinalizer * This also adds the rule set to the list of all known rulesets. */ static rsRetVal rulesetConstructFinalize(ruleset_t *pThis) { uchar *keyName; DEFiRet; ISOBJ_TYPE_assert(pThis, ruleset); /* we must duplicate our name, as the key destructer would also * free it, resulting in a double-free. It's also cleaner to have * two separate copies. */ CHKmalloc(keyName = ustrdup(pThis->pszName)); CHKiRet(llAppend(&llRulesets, keyName, pThis)); /* this now also is the new current ruleset */ pCurrRuleset = pThis; /* and also the default, if so far none has been set */ if(pDfltRuleset == NULL) pDfltRuleset = pThis; finalize_it: RETiRet; } /* destructor for the ruleset object */ BEGINobjDestruct(ruleset) /* be sure to specify the object type also in END and CODESTART macros! */ CODESTARTobjDestruct(ruleset) dbgprintf("destructing ruleset %p, name %p\n", pThis, pThis->pszName); if(pThis->pQueue != NULL) { qqueueDestruct(&pThis->pQueue); } if(pThis->pParserLst != NULL) { parser.DestructParserList(&pThis->pParserLst); } llDestroy(&pThis->llRules); free(pThis->pszName); ENDobjDestruct(ruleset) /* this is a special destructor for the linkedList class. LinkedList does NOT * provide a pointer to the pointer, but rather the raw pointer itself. So we * must map this, otherwise the destructor will abort. */ static rsRetVal rulesetDestructForLinkedList(void *pData) { ruleset_t *pThis = (ruleset_t*) pData; return rulesetDestruct(&pThis); } /* destruct ALL rule sets that reside in the system. This must * be callable before unloading this module as the module may * not be unloaded before unload of the actions is required. This is * kind of a left-over from previous logic and may be optimized one * everything runs stable again. -- rgerhards, 2009-06-10 */ static rsRetVal destructAllActions(void) { DEFiRet; CHKiRet(llDestroy(&llRulesets)); CHKiRet(llInit(&llRulesets, rulesetDestructForLinkedList, keyDestruct, strcasecmp)); pDfltRuleset = NULL; finalize_it: RETiRet; } /* helper for debugPrint(), initiates rule printing */ DEFFUNC_llExecFunc(doDebugPrintRule) { return rule.DebugPrint((rule_t*) pData); } /* debugprint for the ruleset object */ BEGINobjDebugPrint(ruleset) /* be sure to specify the object type also in END and CODESTART macros! */ CODESTARTobjDebugPrint(ruleset) dbgoprint((obj_t*) pThis, "rsyslog ruleset %s:\n", pThis->pszName); llExecFunc(&pThis->llRules, doDebugPrintRule, NULL); ENDobjDebugPrint(ruleset) /* helper for debugPrintAll(), prints a single ruleset */ DEFFUNC_llExecFunc(doDebugPrintAll) { return rulesetDebugPrint((ruleset_t*) pData); } /* debug print all rulesets */ static rsRetVal debugPrintAll(void) { DEFiRet; dbgprintf("All Rulesets:\n"); llExecFunc(&llRulesets, doDebugPrintAll, NULL); dbgprintf("End of Rulesets.\n"); RETiRet; } /* Create a ruleset-specific "main" queue for this ruleset. If one is already * defined, an error message is emitted but nothing else is done. * Note: we use the main message queue parameters for queue creation and access * syslogd.c directly to obtain these. This is far from being perfect, but * considered acceptable for the time being. * rgerhards, 2009-10-27 */ static rsRetVal rulesetCreateQueue(void __attribute__((unused)) *pVal, int *pNewVal) { DEFiRet; if(pCurrRuleset == NULL) { errmsg.LogError(0, RS_RET_NO_CURR_RULESET, "error: currently no specific ruleset specified, thus a " "queue can not be added to it"); ABORT_FINALIZE(RS_RET_NO_CURR_RULESET); } if(pCurrRuleset->pQueue != NULL) { errmsg.LogError(0, RS_RET_RULES_QUEUE_EXISTS, "error: ruleset already has a main queue, can not " "add another one"); ABORT_FINALIZE(RS_RET_RULES_QUEUE_EXISTS); } if(pNewVal == 0) FINALIZE; /* if it is turned off, we do not need to change anything ;) */ dbgprintf("adding a ruleset-specific \"main\" queue"); CHKiRet(createMainQueue(&pCurrRuleset->pQueue, UCHAR_CONSTANT("ruleset"))); finalize_it: RETiRet; } /* Add a ruleset specific parser to the ruleset. Note that adding the first * parser automatically disables the default parsers. If they are needed as well, * the must be added via explicit config directives. * Note: this is the only spot in the code that requires the parser object. In order * to solve some class init bootstrap sequence problems, we get the object handle here * instead of during module initialization. Note that objUse() is capable of being * called multiple times. * rgerhards, 2009-11-04 */ static rsRetVal rulesetAddParser(void __attribute__((unused)) *pVal, uchar *pName) { parser_t *pParser; DEFiRet; assert(pCurrRuleset != NULL); CHKiRet(objUse(parser, CORE_COMPONENT)); iRet = parser.FindParser(&pParser, pName); if(iRet == RS_RET_PARSER_NOT_FOUND) { errmsg.LogError(0, RS_RET_PARSER_NOT_FOUND, "error: parser '%s' unknown at this time " "(maybe defined too late in rsyslog.conf?)", pName); ABORT_FINALIZE(RS_RET_NO_CURR_RULESET); } else if(iRet != RS_RET_OK) { errmsg.LogError(0, iRet, "error trying to find parser '%s'\n", pName); FINALIZE; } CHKiRet(parser.AddParserToList(&pCurrRuleset->pParserLst, pParser)); dbgprintf("added parser '%s' to ruleset '%s'\n", pName, pCurrRuleset->pszName); RUNLOG_VAR("%p", pCurrRuleset->pParserLst); finalize_it: d_free(pName); /* no longer needed */ RETiRet; } /* queryInterface function * rgerhards, 2008-02-21 */ BEGINobjQueryInterface(ruleset) CODESTARTobjQueryInterface(ruleset) if(pIf->ifVersion != rulesetCURR_IF_VERSION) { /* check for current version, increment on each change */ ABORT_FINALIZE(RS_RET_INTERFACE_NOT_SUPPORTED); } /* ok, we have the right interface, so let's fill it * Please note that we may also do some backwards-compatibility * work here (if we can support an older interface version - that, * of course, also affects the "if" above). */ pIf->Construct = rulesetConstruct; pIf->ConstructFinalize = rulesetConstructFinalize; pIf->Destruct = rulesetDestruct; pIf->DebugPrint = rulesetDebugPrint; pIf->IterateAllActions = iterateAllActions; pIf->DestructAllActions = destructAllActions; pIf->AddRule = addRule; pIf->ProcessBatch = processBatch; pIf->SetName = setName; pIf->DebugPrintAll = debugPrintAll; pIf->GetCurrent = GetCurrent; pIf->GetRuleset = GetRuleset; pIf->SetDefaultRuleset = SetDefaultRuleset; pIf->SetCurrRuleset = SetCurrRuleset; pIf->GetRulesetQueue = GetRulesetQueue; pIf->GetParserList = GetParserList; finalize_it: ENDobjQueryInterface(ruleset) /* Exit the ruleset class. * rgerhards, 2009-04-06 */ BEGINObjClassExit(ruleset, OBJ_IS_CORE_MODULE) /* class, version */ llDestroy(&llRulesets); objRelease(errmsg, CORE_COMPONENT); objRelease(rule, CORE_COMPONENT); objRelease(parser, CORE_COMPONENT); ENDObjClassExit(ruleset) /* Initialize the ruleset class. Must be called as the very first method * before anything else is called inside this class. * rgerhards, 2008-02-19 */ BEGINObjClassInit(ruleset, 1, OBJ_IS_CORE_MODULE) /* class, version */ /* request objects we use */ CHKiRet(objUse(errmsg, CORE_COMPONENT)); CHKiRet(objUse(rule, CORE_COMPONENT)); /* set our own handlers */ OBJSetMethodHandler(objMethod_DEBUGPRINT, rulesetDebugPrint); OBJSetMethodHandler(objMethod_CONSTRUCTION_FINALIZER, rulesetConstructFinalize); /* prepare global data */ CHKiRet(llInit(&llRulesets, rulesetDestructForLinkedList, keyDestruct, strcasecmp)); /* config file handlers */ CHKiRet(regCfSysLineHdlr((uchar *)"rulesetparser", 0, eCmdHdlrGetWord, rulesetAddParser, NULL, NULL)); CHKiRet(regCfSysLineHdlr((uchar *)"rulesetcreatemainqueue", 0, eCmdHdlrBinary, rulesetCreateQueue, NULL, NULL)); ENDObjClassInit(ruleset) /* vi:set ai: */
./CrossVul/dataset_final_sorted/CWE-772/c/bad_3450_2
crossvul-cpp_data_bad_2574_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS CCCC RRRR EEEEE EEEEE N N SSSSS H H OOO TTTTT % % SS C R R E E NN N SS H H O O T % % SSS C RRRR EEE EEE N N N SSS HHHHH O O T % % SS C R R E E N NN SS H H O O T % % SSSSS CCCC R R EEEEE EEEEE N N SSSSS H H OOO T % % % % % % Takes a screenshot from the monitor(s). % % % % Software Design % % Dirk Lemstra % % April 2014 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #if defined(MAGICKCORE_WINGDI32_DELEGATE) # if defined(__CYGWIN__) # include <windows.h> # else /* All MinGW needs ... */ # include "magick/nt-base-private.h" # include <wingdi.h> # ifndef DISPLAY_DEVICE_ACTIVE # define DISPLAY_DEVICE_ACTIVE 0x00000001 # endif # endif #endif #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/nt-feature.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/token.h" #include "magick/utility.h" #include "magick/xwindow.h" #include "magick/xwindow-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d S C R E E N S H O T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadSCREENSHOTImage() Takes a screenshot from the monitor(s). % % The format of the ReadSCREENSHOTImage method is: % % Image *ReadXImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadSCREENSHOTImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=(Image *) NULL; #if defined(MAGICKCORE_WINGDI32_DELEGATE) { BITMAPINFO bmi; DISPLAY_DEVICE device; HBITMAP bitmap, bitmapOld; HDC bitmapDC, hDC; Image *screen; int i; MagickBooleanType status; register PixelPacket *q; register ssize_t x; RGBTRIPLE *p; ssize_t y; assert(image_info != (const ImageInfo *) NULL); i=0; device.cb = sizeof(device); image=(Image *) NULL; while(EnumDisplayDevices(NULL,i,&device,0) && ++i) { if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE) continue; hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL); if (hDC == (HDC) NULL) ThrowReaderException(CoderError,"UnableToCreateDC"); screen=AcquireImage(image_info); screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES); screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES); screen->storage_class=DirectClass; status=SetImageExtent(screen,screen->columns,screen->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image == (Image *) NULL) image=screen; else AppendImageToList(&image,screen); bitmapDC=CreateCompatibleDC(hDC); if (bitmapDC == (HDC) NULL) { DeleteDC(hDC); ThrowReaderException(CoderError,"UnableToCreateDC"); } (void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO)); bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth=(LONG) screen->columns; bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows; bmi.bmiHeader.biPlanes=1; bmi.bmiHeader.biBitCount=24; bmi.bmiHeader.biCompression=BI_RGB; bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0); if (bitmap == (HBITMAP) NULL) { DeleteDC(hDC); DeleteDC(bitmapDC); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap); if (bitmapOld == (HBITMAP) NULL) { DeleteDC(hDC); DeleteDC(bitmapDC); DeleteObject(bitmap); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0, SRCCOPY); (void) SelectObject(bitmapDC,bitmapOld); for (y=0; y < (ssize_t) screen->rows; y++) { q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) screen->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(p->rgbtRed)); SetPixelGreen(q,ScaleCharToQuantum(p->rgbtGreen)); SetPixelBlue(q,ScaleCharToQuantum(p->rgbtBlue)); SetPixelOpacity(q,OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(screen,exception) == MagickFalse) break; } DeleteDC(hDC); DeleteDC(bitmapDC); DeleteObject(bitmap); } } #elif defined(MAGICKCORE_X11_DELEGATE) { const char *option; XImportInfo ximage_info; (void) exception; XGetImportInfo(&ximage_info); option=GetImageOption(image_info,"x:screen"); if (option != (const char *) NULL) ximage_info.screen=IsMagickTrue(option); option=GetImageOption(image_info,"x:silent"); if (option != (const char *) NULL) ximage_info.silent=IsMagickTrue(option); image=XImportImage(image_info,&ximage_info); } #endif return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r S C R E E N S H O T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterSCREENSHOTImage() adds attributes for the screen shot format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterScreenShotImage method is: % % size_t RegisterScreenShotImage(void) % */ ModuleExport size_t RegisterSCREENSHOTImage(void) { MagickInfo *entry; entry=SetMagickInfo("SCREENSHOT"); entry->decoder=(DecodeImageHandler *) ReadSCREENSHOTImage; entry->format_type=ImplicitFormatType; entry->description=ConstantString("Screen shot"); entry->module=ConstantString("SCREENSHOT"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r S C R E E N S H O T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterScreenShotImage() removes format registrations made by the % screen shot module from the list of supported formats. % % The format of the UnregisterSCREENSHOTImage method is: % % UnregisterSCREENSHOTImage(void) % */ ModuleExport void UnregisterSCREENSHOTImage(void) { (void) UnregisterMagickInfo("SCREENSHOT"); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2574_0
crossvul-cpp_data_good_2829_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Y Y YYYC BBBB YYYC RRRR % % Y Y C B B C R R % % Y C BBBB C RRRR % % Y C B B C R R % % Y YYYC BBBB YYYC R R % % % % % % Read/Write Raw YCbCr Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colorspace.h" #include "MagickCore/constitute.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/utility.h" /* Forward declarations. */ static MagickBooleanType WriteYCBCRImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d Y C b C r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadYCBCRImage() reads an image of raw YCbCr or YCbCrA samples and returns % it. It allocates the memory necessary for the new Image structure and % returns a pointer to the new image. % % The format of the ReadYCBCRImage method is: % % Image *ReadYCBCRImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadYCBCRImage(const ImageInfo *image_info, ExceptionInfo *exception) { const unsigned char *pixels; Image *canvas_image, *image; MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register const Quantum *p; register ssize_t i, x; register Quantum *q; size_t length; ssize_t count, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); SetImageColorspace(image,YCbCrColorspace,exception); if (image_info->interlace != PartitionInterlace) { status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Create virtual canvas to support cropping (i.e. image.rgb[100x100+10+20]). */ canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse, exception); (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod, exception); quantum_info=AcquireQuantumInfo(image_info,canvas_image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); quantum_type=RGBQuantum; if (LocaleCompare(image_info->magick,"YCbCrA") == 0) { quantum_type=RGBAQuantum; image->alpha_trait=BlendPixelTrait; } pixels=(const unsigned char *) NULL; if (image_info->number_scenes != 0) while (image->scene < image_info->scene) { /* Skip to next image. */ image->scene++; length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) break; } } count=0; length=0; scene=0; do { /* Read pixels to virtual canvas image then push to image. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { quantum_info=DestroyQuantumInfo(quantum_info); canvas_image=DestroyImage(canvas_image); return(DestroyImageList(image)); } SetImageColorspace(image,YCbCrColorspace,exception); switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: YCbCrYCbCrYCbCrYCbCrYCbCrYCbCr... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=QueueAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,GetPixelRed(canvas_image,p),q); SetPixelGreen(image,GetPixelGreen(canvas_image,p),q); SetPixelBlue(image,GetPixelBlue(canvas_image,p),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,GetPixelAlpha(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } break; } case LineInterlace: { static QuantumType quantum_types[4] = { RedQuantum, GreenQuantum, BlueQuantum, OpacityQuantum }; /* Line interlacing: YYY...CbCbCb...CrCrCr...YYY...CbCbCb...CrCrCr... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { for (i=0; i < (image->alpha_trait != UndefinedPixelTrait ? 4 : 3); i++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } quantum_type=quantum_types[i]; q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { switch (quantum_type) { case RedQuantum: { SetPixelRed(image,GetPixelRed(canvas_image,p),q); break; } case GreenQuantum: { SetPixelGreen(image,GetPixelGreen(canvas_image,p),q); break; } case BlueQuantum: { SetPixelBlue(image,GetPixelBlue(canvas_image,p),q); break; } case OpacityQuantum: { SetPixelAlpha(image,GetPixelAlpha(canvas_image,p),q); break; } default: break; } p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: YYYYYY...CbCbCbCbCbCb...CrCrCrCrCrCr... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,GetPixelRed(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(image,GetPixelGreen(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,GetPixelBlue(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->alpha_trait != UndefinedPixelTrait) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(image,GetPixelAlpha(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: YYYYYY..., CbCbCbCbCbCb..., CrCrCrCrCrCr... */ AppendImageFormat("Y",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,GetPixelRed(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("Cb",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,GreenQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(image,GetPixelGreen(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("Cr",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,BlueQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,GetPixelBlue(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->alpha_trait != UndefinedPixelTrait) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(image,GetPixelAlpha(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } } SetQuantumImageType(image,quantum_type); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (count == (ssize_t) length) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } scene++; } while (count == (ssize_t) length); quantum_info=DestroyQuantumInfo(quantum_info); canvas_image=DestroyImage(canvas_image); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r Y C b C r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterYCBCRImage() adds attributes for the YCbCr or YCbCrA image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterYCBCRImage method is: % % size_t RegisterYCBCRImage(void) % */ ModuleExport size_t RegisterYCBCRImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("YCbCr","YCbCr","Raw Y, Cb, and Cr samples"); entry->decoder=(DecodeImageHandler *) ReadYCBCRImage; entry->encoder=(EncodeImageHandler *) WriteYCBCRImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("YCbCr","YCbCrA","Raw Y, Cb, Cr, and alpha samples"); entry->decoder=(DecodeImageHandler *) ReadYCBCRImage; entry->encoder=(EncodeImageHandler *) WriteYCBCRImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r Y C b C r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterYCBCRImage() removes format registrations made by the % YCbCr module from the list of supported formats. % % The format of the UnregisterYCBCRImage method is: % % UnregisterYCBCRImage(void) % */ ModuleExport void UnregisterYCBCRImage(void) { (void) UnregisterMagickInfo("YCbCr"); (void) UnregisterMagickInfo("YCbCrA"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e Y C b C r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteYCBCRImage() writes an image to a file in the YCbCr or YCbCrA % rasterfile format. % % The format of the WriteYCBCRImage method is: % % MagickBooleanType WriteYCBCRImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteYCBCRImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register const Quantum *p; size_t length; ssize_t count, y; unsigned char *pixels; /* Allocate memory for pixels. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image_info->interlace != PartitionInterlace) { /* Open output image file. */ assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); } quantum_type=RGBQuantum; if (LocaleCompare(image_info->magick,"YCbCrA") == 0) { quantum_type=RGBAQuantum; image->alpha_trait=BlendPixelTrait; } scene=0; do { /* Convert MIFF to YCbCr raster pixels. */ if (image->colorspace != YCbCrColorspace) (void) TransformImageColorspace(image,YCbCrColorspace,exception); if ((LocaleCompare(image_info->magick,"YCbCrA") == 0) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetQuantumPixels(quantum_info); switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: YCbCrYCbCrYCbCrYCbCrYCbCrYCbCr... */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case LineInterlace: { /* Line interlacing: YYY...CbCbCb...CrCrCr...YYY...CbCbCb...CrCrCr... */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; if (quantum_type == RGBAQuantum) { length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, AlphaQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: YYYYYY...CbCbCbCbCbCb...CrCrCrCrCrCr... */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,1,5); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,2,5); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,3,5); if (status == MagickFalse) break; } if (quantum_type == RGBAQuantum) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, AlphaQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } } if (image_info->interlace == PartitionInterlace) (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,5,5); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: YYYYYY..., CbCbCbCbCbCb..., CrCrCrCrCrCr... */ AppendImageFormat("Y",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("Cb",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("Cr",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,3,5); if (status == MagickFalse) break; } if (quantum_type == RGBAQuantum) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, AlphaQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,4,5); if (status == MagickFalse) break; } } (void) CloseBlob(image); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,5,5); if (status == MagickFalse) break; } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-772/c/good_2829_0
crossvul-cpp_data_good_1168_0
#include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include "../common/cmdline.h" #define TAG FREERDP_TAG("generate_argument_docbook") LPSTR tr_esc_str(LPCSTR arg, bool format) { LPSTR tmp = NULL; LPSTR tmp2 = NULL; size_t cs = 0, x, ds, len; size_t s; if (NULL == arg) return NULL; s = strlen(arg); /* Find trailing whitespaces */ while ((s > 0) && isspace(arg[s - 1])) s--; /* Prepare a initial buffer with the size of the result string. */ ds = s + 1; if (s) { tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; } if (NULL == tmp) { fprintf(stderr, "Could not allocate string buffer.\n"); exit(-2); } /* Copy character for character and check, if it is necessary to escape. */ memset(tmp, 0, ds * sizeof(CHAR)); for (x = 0; x < s; x++) { switch (arg[x]) { case '<': len = format ? 13 : 4; ds += len - 1; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-3); } if (format) /* coverity[buffer_size] */ strncpy(&tmp[cs], "<replaceable>", len); else /* coverity[buffer_size] */ strncpy(&tmp[cs], "&lt;", len); cs += len; break; case '>': len = format ? 14 : 4; ds += len - 1; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-4); } if (format) /* coverity[buffer_size] */ strncpy(&tmp[cs], "</replaceable>", len); else /* coverity[buffer_size] */ strncpy(&tmp[cs], "&lt;", len); cs += len; break; case '\'': ds += 5; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-5); } tmp[cs++] = '&'; tmp[cs++] = 'a'; tmp[cs++] = 'p'; tmp[cs++] = 'o'; tmp[cs++] = 's'; tmp[cs++] = ';'; break; case '"': ds += 5; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-6); } tmp[cs++] = '&'; tmp[cs++] = 'q'; tmp[cs++] = 'u'; tmp[cs++] = 'o'; tmp[cs++] = 't'; tmp[cs++] = ';'; break; case '&': ds += 4; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-7); } tmp[cs++] = '&'; tmp[cs++] = 'a'; tmp[cs++] = 'm'; tmp[cs++] = 'p'; tmp[cs++] = ';'; break; default: tmp[cs++] = arg[x]; break; } /* Assure, the string is '\0' terminated. */ tmp[ds - 1] = '\0'; } return tmp; } int main(int argc, char* argv[]) { size_t elements = sizeof(args) / sizeof(args[0]); size_t x; const char* fname = "xfreerdp-argument.1.xml"; FILE* fp = NULL; /* Open output file for writing, truncate if existing. */ fp = fopen(fname, "w"); if (NULL == fp) { fprintf(stderr, "Could not open '%s' for writing.\n", fname); return -1; } /* The tag used as header in the manpage */ fprintf(fp, "<refsect1>\n"); fprintf(fp, "\t<title>Options</title>\n"); fprintf(fp, "\t\t<variablelist>\n"); /* Iterate over argument struct and write data to docbook 4.5 * compatible XML */ if (elements < 2) { fprintf(stderr, "The argument array 'args' is empty, writing an empty file.\n"); elements = 1; } for (x = 0; x < elements - 1; x++) { const COMMAND_LINE_ARGUMENT_A* arg = &args[x]; char* name = tr_esc_str((LPSTR) arg->Name, FALSE); char* alias = tr_esc_str((LPSTR) arg->Alias, FALSE); char* format = tr_esc_str(arg->Format, TRUE); char* text = tr_esc_str((LPSTR) arg->Text, FALSE); fprintf(fp, "\t\t\t<varlistentry>\n"); do { fprintf(fp, "\t\t\t\t<term><option>"); if (arg->Flags == COMMAND_LINE_VALUE_BOOL) fprintf(fp, "%s", arg->Default ? "-" : "+"); else fprintf(fp, "/"); fprintf(fp, "%s</option>", name); if (format) { if (arg->Flags == COMMAND_LINE_VALUE_OPTIONAL) fprintf(fp, "["); fprintf(fp, ":%s", format); if (arg->Flags == COMMAND_LINE_VALUE_OPTIONAL) fprintf(fp, "]"); } fprintf(fp, "</term>\n"); if (alias == name) break; free(name); name = alias; } while (alias); if (text) { fprintf(fp, "\t\t\t\t<listitem>\n"); fprintf(fp, "\t\t\t\t\t<para>"); if (text) fprintf(fp, "%s", text); if (arg->Flags == COMMAND_LINE_VALUE_BOOL) fprintf(fp, " (default:%s)", arg->Default ? "on" : "off"); else if (arg->Default) { char* value = tr_esc_str((LPSTR) arg->Default, FALSE); fprintf(fp, " (default:%s)", value); free(value); } fprintf(fp, "</para>\n"); fprintf(fp, "\t\t\t\t</listitem>\n"); } fprintf(fp, "\t\t\t</varlistentry>\n"); free(name); free(format); free(text); } fprintf(fp, "\t\t</variablelist>\n"); fprintf(fp, "\t</refsect1>\n"); fclose(fp); return 0; }
./CrossVul/dataset_final_sorted/CWE-772/c/good_1168_0
crossvul-cpp_data_bad_1162_0
/* Copyright 2011-2014 Autronica Fire and Security AS * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * Author(s): * 2011-2014 Arvid Brodin, arvid.brodin@alten.se * * This file contains device methods for creating, using and destroying * virtual HSR devices. */ #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/etherdevice.h> #include <linux/rtnetlink.h> #include <linux/pkt_sched.h> #include "hsr_device.h" #include "hsr_slave.h" #include "hsr_framereg.h" #include "hsr_main.h" #include "hsr_forward.h" static bool is_admin_up(struct net_device *dev) { return dev && (dev->flags & IFF_UP); } static bool is_slave_up(struct net_device *dev) { return dev && is_admin_up(dev) && netif_oper_up(dev); } static void __hsr_set_operstate(struct net_device *dev, int transition) { write_lock_bh(&dev_base_lock); if (dev->operstate != transition) { dev->operstate = transition; write_unlock_bh(&dev_base_lock); netdev_state_change(dev); } else { write_unlock_bh(&dev_base_lock); } } static void hsr_set_operstate(struct hsr_port *master, bool has_carrier) { if (!is_admin_up(master->dev)) { __hsr_set_operstate(master->dev, IF_OPER_DOWN); return; } if (has_carrier) __hsr_set_operstate(master->dev, IF_OPER_UP); else __hsr_set_operstate(master->dev, IF_OPER_LOWERLAYERDOWN); } static bool hsr_check_carrier(struct hsr_port *master) { struct hsr_port *port; bool has_carrier; has_carrier = false; rcu_read_lock(); hsr_for_each_port(master->hsr, port) if ((port->type != HSR_PT_MASTER) && is_slave_up(port->dev)) { has_carrier = true; break; } rcu_read_unlock(); if (has_carrier) netif_carrier_on(master->dev); else netif_carrier_off(master->dev); return has_carrier; } static void hsr_check_announce(struct net_device *hsr_dev, unsigned char old_operstate) { struct hsr_priv *hsr; hsr = netdev_priv(hsr_dev); if ((hsr_dev->operstate == IF_OPER_UP) && (old_operstate != IF_OPER_UP)) { /* Went up */ hsr->announce_count = 0; hsr->announce_timer.expires = jiffies + msecs_to_jiffies(HSR_ANNOUNCE_INTERVAL); add_timer(&hsr->announce_timer); } if ((hsr_dev->operstate != IF_OPER_UP) && (old_operstate == IF_OPER_UP)) /* Went down */ del_timer(&hsr->announce_timer); } void hsr_check_carrier_and_operstate(struct hsr_priv *hsr) { struct hsr_port *master; unsigned char old_operstate; bool has_carrier; master = hsr_port_get_hsr(hsr, HSR_PT_MASTER); /* netif_stacked_transfer_operstate() cannot be used here since * it doesn't set IF_OPER_LOWERLAYERDOWN (?) */ old_operstate = master->dev->operstate; has_carrier = hsr_check_carrier(master); hsr_set_operstate(master, has_carrier); hsr_check_announce(master->dev, old_operstate); } int hsr_get_max_mtu(struct hsr_priv *hsr) { unsigned int mtu_max; struct hsr_port *port; mtu_max = ETH_DATA_LEN; rcu_read_lock(); hsr_for_each_port(hsr, port) if (port->type != HSR_PT_MASTER) mtu_max = min(port->dev->mtu, mtu_max); rcu_read_unlock(); if (mtu_max < HSR_HLEN) return 0; return mtu_max - HSR_HLEN; } static int hsr_dev_change_mtu(struct net_device *dev, int new_mtu) { struct hsr_priv *hsr; struct hsr_port *master; hsr = netdev_priv(dev); master = hsr_port_get_hsr(hsr, HSR_PT_MASTER); if (new_mtu > hsr_get_max_mtu(hsr)) { netdev_info(master->dev, "A HSR master's MTU cannot be greater than the smallest MTU of its slaves minus the HSR Tag length (%d octets).\n", HSR_HLEN); return -EINVAL; } dev->mtu = new_mtu; return 0; } static int hsr_dev_open(struct net_device *dev) { struct hsr_priv *hsr; struct hsr_port *port; char designation; hsr = netdev_priv(dev); designation = '\0'; rcu_read_lock(); hsr_for_each_port(hsr, port) { if (port->type == HSR_PT_MASTER) continue; switch (port->type) { case HSR_PT_SLAVE_A: designation = 'A'; break; case HSR_PT_SLAVE_B: designation = 'B'; break; default: designation = '?'; } if (!is_slave_up(port->dev)) netdev_warn(dev, "Slave %c (%s) is not up; please bring it up to get a fully working HSR network\n", designation, port->dev->name); } rcu_read_unlock(); if (designation == '\0') netdev_warn(dev, "No slave devices configured\n"); return 0; } static int hsr_dev_close(struct net_device *dev) { /* Nothing to do here. */ return 0; } static netdev_features_t hsr_features_recompute(struct hsr_priv *hsr, netdev_features_t features) { netdev_features_t mask; struct hsr_port *port; mask = features; /* Mask out all features that, if supported by one device, should be * enabled for all devices (see NETIF_F_ONE_FOR_ALL). * * Anything that's off in mask will not be enabled - so only things * that were in features originally, and also is in NETIF_F_ONE_FOR_ALL, * may become enabled. */ features &= ~NETIF_F_ONE_FOR_ALL; hsr_for_each_port(hsr, port) features = netdev_increment_features(features, port->dev->features, mask); return features; } static netdev_features_t hsr_fix_features(struct net_device *dev, netdev_features_t features) { struct hsr_priv *hsr = netdev_priv(dev); return hsr_features_recompute(hsr, features); } static int hsr_dev_xmit(struct sk_buff *skb, struct net_device *dev) { struct hsr_priv *hsr = netdev_priv(dev); struct hsr_port *master; master = hsr_port_get_hsr(hsr, HSR_PT_MASTER); skb->dev = master->dev; hsr_forward_skb(skb, master); return NETDEV_TX_OK; } static const struct header_ops hsr_header_ops = { .create = eth_header, .parse = eth_header_parse, }; static void send_hsr_supervision_frame(struct hsr_port *master, u8 type, u8 hsrVer) { struct sk_buff *skb; int hlen, tlen; struct hsr_tag *hsr_tag; struct hsr_sup_tag *hsr_stag; struct hsr_sup_payload *hsr_sp; unsigned long irqflags; hlen = LL_RESERVED_SPACE(master->dev); tlen = master->dev->needed_tailroom; skb = dev_alloc_skb( sizeof(struct hsr_tag) + sizeof(struct hsr_sup_tag) + sizeof(struct hsr_sup_payload) + hlen + tlen); if (skb == NULL) return; skb_reserve(skb, hlen); skb->dev = master->dev; skb->protocol = htons(hsrVer ? ETH_P_HSR : ETH_P_PRP); skb->priority = TC_PRIO_CONTROL; if (dev_hard_header(skb, skb->dev, (hsrVer ? ETH_P_HSR : ETH_P_PRP), master->hsr->sup_multicast_addr, skb->dev->dev_addr, skb->len) <= 0) goto out; skb_reset_mac_header(skb); if (hsrVer > 0) { hsr_tag = skb_put(skb, sizeof(struct hsr_tag)); hsr_tag->encap_proto = htons(ETH_P_PRP); set_hsr_tag_LSDU_size(hsr_tag, HSR_V1_SUP_LSDUSIZE); } hsr_stag = skb_put(skb, sizeof(struct hsr_sup_tag)); set_hsr_stag_path(hsr_stag, (hsrVer ? 0x0 : 0xf)); set_hsr_stag_HSR_Ver(hsr_stag, hsrVer); /* From HSRv1 on we have separate supervision sequence numbers. */ spin_lock_irqsave(&master->hsr->seqnr_lock, irqflags); if (hsrVer > 0) { hsr_stag->sequence_nr = htons(master->hsr->sup_sequence_nr); hsr_tag->sequence_nr = htons(master->hsr->sequence_nr); master->hsr->sup_sequence_nr++; master->hsr->sequence_nr++; } else { hsr_stag->sequence_nr = htons(master->hsr->sequence_nr); master->hsr->sequence_nr++; } spin_unlock_irqrestore(&master->hsr->seqnr_lock, irqflags); hsr_stag->HSR_TLV_Type = type; /* TODO: Why 12 in HSRv0? */ hsr_stag->HSR_TLV_Length = hsrVer ? sizeof(struct hsr_sup_payload) : 12; /* Payload: MacAddressA */ hsr_sp = skb_put(skb, sizeof(struct hsr_sup_payload)); ether_addr_copy(hsr_sp->MacAddressA, master->dev->dev_addr); if (skb_put_padto(skb, ETH_ZLEN + HSR_HLEN)) return; hsr_forward_skb(skb, master); return; out: WARN_ONCE(1, "HSR: Could not send supervision frame\n"); kfree_skb(skb); } /* Announce (supervision frame) timer function */ static void hsr_announce(struct timer_list *t) { struct hsr_priv *hsr; struct hsr_port *master; hsr = from_timer(hsr, t, announce_timer); rcu_read_lock(); master = hsr_port_get_hsr(hsr, HSR_PT_MASTER); if (hsr->announce_count < 3 && hsr->protVersion == 0) { send_hsr_supervision_frame(master, HSR_TLV_ANNOUNCE, hsr->protVersion); hsr->announce_count++; hsr->announce_timer.expires = jiffies + msecs_to_jiffies(HSR_ANNOUNCE_INTERVAL); } else { send_hsr_supervision_frame(master, HSR_TLV_LIFE_CHECK, hsr->protVersion); hsr->announce_timer.expires = jiffies + msecs_to_jiffies(HSR_LIFE_CHECK_INTERVAL); } if (is_admin_up(master->dev)) add_timer(&hsr->announce_timer); rcu_read_unlock(); } /* According to comments in the declaration of struct net_device, this function * is "Called from unregister, can be used to call free_netdev". Ok then... */ static void hsr_dev_destroy(struct net_device *hsr_dev) { struct hsr_priv *hsr; struct hsr_port *port; hsr = netdev_priv(hsr_dev); rtnl_lock(); hsr_for_each_port(hsr, port) hsr_del_port(port); rtnl_unlock(); del_timer_sync(&hsr->prune_timer); del_timer_sync(&hsr->announce_timer); synchronize_rcu(); } static const struct net_device_ops hsr_device_ops = { .ndo_change_mtu = hsr_dev_change_mtu, .ndo_open = hsr_dev_open, .ndo_stop = hsr_dev_close, .ndo_start_xmit = hsr_dev_xmit, .ndo_fix_features = hsr_fix_features, }; static struct device_type hsr_type = { .name = "hsr", }; void hsr_dev_setup(struct net_device *dev) { eth_hw_addr_random(dev); ether_setup(dev); dev->min_mtu = 0; dev->header_ops = &hsr_header_ops; dev->netdev_ops = &hsr_device_ops; SET_NETDEV_DEVTYPE(dev, &hsr_type); dev->priv_flags |= IFF_NO_QUEUE; dev->needs_free_netdev = true; dev->priv_destructor = hsr_dev_destroy; dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | NETIF_F_HIGHDMA | NETIF_F_GSO_MASK | NETIF_F_HW_CSUM | NETIF_F_HW_VLAN_CTAG_TX; dev->features = dev->hw_features; /* Prevent recursive tx locking */ dev->features |= NETIF_F_LLTX; /* VLAN on top of HSR needs testing and probably some work on * hsr_header_create() etc. */ dev->features |= NETIF_F_VLAN_CHALLENGED; /* Not sure about this. Taken from bridge code. netdev_features.h says * it means "Does not change network namespaces". */ dev->features |= NETIF_F_NETNS_LOCAL; } /* Return true if dev is a HSR master; return false otherwise. */ inline bool is_hsr_master(struct net_device *dev) { return (dev->netdev_ops->ndo_start_xmit == hsr_dev_xmit); } /* Default multicast address for HSR Supervision frames */ static const unsigned char def_multicast_addr[ETH_ALEN] __aligned(2) = { 0x01, 0x15, 0x4e, 0x00, 0x01, 0x00 }; int hsr_dev_finalize(struct net_device *hsr_dev, struct net_device *slave[2], unsigned char multicast_spec, u8 protocol_version) { struct hsr_priv *hsr; struct hsr_port *port; int res; hsr = netdev_priv(hsr_dev); INIT_LIST_HEAD(&hsr->ports); INIT_LIST_HEAD(&hsr->node_db); INIT_LIST_HEAD(&hsr->self_node_db); ether_addr_copy(hsr_dev->dev_addr, slave[0]->dev_addr); /* Make sure we recognize frames from ourselves in hsr_rcv() */ res = hsr_create_self_node(&hsr->self_node_db, hsr_dev->dev_addr, slave[1]->dev_addr); if (res < 0) return res; spin_lock_init(&hsr->seqnr_lock); /* Overflow soon to find bugs easier: */ hsr->sequence_nr = HSR_SEQNR_START; hsr->sup_sequence_nr = HSR_SUP_SEQNR_START; timer_setup(&hsr->announce_timer, hsr_announce, 0); timer_setup(&hsr->prune_timer, hsr_prune_nodes, 0); ether_addr_copy(hsr->sup_multicast_addr, def_multicast_addr); hsr->sup_multicast_addr[ETH_ALEN - 1] = multicast_spec; hsr->protVersion = protocol_version; /* FIXME: should I modify the value of these? * * - hsr_dev->flags - i.e. * IFF_MASTER/SLAVE? * - hsr_dev->priv_flags - i.e. * IFF_EBRIDGE? * IFF_TX_SKB_SHARING? * IFF_HSR_MASTER/SLAVE? */ /* Make sure the 1st call to netif_carrier_on() gets through */ netif_carrier_off(hsr_dev); res = hsr_add_port(hsr, hsr_dev, HSR_PT_MASTER); if (res) return res; res = register_netdevice(hsr_dev); if (res) goto fail; res = hsr_add_port(hsr, slave[0], HSR_PT_SLAVE_A); if (res) goto fail; res = hsr_add_port(hsr, slave[1], HSR_PT_SLAVE_B); if (res) goto fail; mod_timer(&hsr->prune_timer, jiffies + msecs_to_jiffies(PRUNE_PERIOD)); return 0; fail: hsr_for_each_port(hsr, port) hsr_del_port(port); return res; }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_1162_0
crossvul-cpp_data_good_3450_2
/* ruleset.c - rsyslog's ruleset object * * We have a two-way structure of linked lists: one global linked list * (llAllRulesets) hold alls rule sets that we know. Included in each * list is a list of rules (which contain a list of actions, but that's * a different story). * * Usually, only a single rule set is executed. However, there exist some * situations where all rules must be iterated over, for example on HUP. Thus, * we also provide interfaces to do that. * * Module begun 2009-06-10 by Rainer Gerhards * * Copyright 2009 Rainer Gerhards and Adiscon GmbH. * * This file is part of the rsyslog runtime library. * * The rsyslog runtime library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The rsyslog runtime library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the rsyslog runtime library. If not, see <http://www.gnu.org/licenses/>. * * A copy of the GPL can be found in the file "COPYING" in this distribution. * A copy of the LGPL can be found in the file "COPYING.LESSER" in this distribution. */ #include "config.h" #include <stdlib.h> #include <string.h> #include <assert.h> #include <ctype.h> #include "rsyslog.h" #include "obj.h" #include "cfsysline.h" #include "msg.h" #include "ruleset.h" #include "rule.h" #include "errmsg.h" #include "parser.h" #include "batch.h" #include "unicode-helper.h" #include "dirty.h" /* for main ruleset queue creation */ /* static data */ DEFobjStaticHelpers DEFobjCurrIf(errmsg) DEFobjCurrIf(rule) DEFobjCurrIf(parser) linkedList_t llRulesets; /* this is NOT a pointer - no typo here ;) */ ruleset_t *pCurrRuleset = NULL; /* currently "active" ruleset */ ruleset_t *pDfltRuleset = NULL; /* current default ruleset, e.g. for binding to actions which have no other */ /* forward definitions */ static rsRetVal processBatch(batch_t *pBatch); /* ---------- linked-list key handling functions ---------- */ /* destructor for linked list keys. */ static rsRetVal keyDestruct(void __attribute__((unused)) *pData) { free(pData); return RS_RET_OK; } /* ---------- END linked-list key handling functions ---------- */ /* driver to iterate over all of this ruleset actions */ typedef struct iterateAllActions_s { rsRetVal (*pFunc)(void*, void*); void *pParam; } iterateAllActions_t; DEFFUNC_llExecFunc(doIterateRulesetActions) { DEFiRet; rule_t* pRule = (rule_t*) pData; iterateAllActions_t *pMyParam = (iterateAllActions_t*) pParam; iRet = rule.IterateAllActions(pRule, pMyParam->pFunc, pMyParam->pParam); RETiRet; } /* iterate over all actions of THIS rule set. */ static rsRetVal iterateRulesetAllActions(ruleset_t *pThis, rsRetVal (*pFunc)(void*, void*), void* pParam) { iterateAllActions_t params; DEFiRet; assert(pFunc != NULL); params.pFunc = pFunc; params.pParam = pParam; CHKiRet(llExecFunc(&(pThis->llRules), doIterateRulesetActions, &params)); finalize_it: RETiRet; } /* driver to iterate over all actions */ DEFFUNC_llExecFunc(doIterateAllActions) { DEFiRet; ruleset_t* pThis = (ruleset_t*) pData; iterateAllActions_t *pMyParam = (iterateAllActions_t*) pParam; iRet = iterateRulesetAllActions(pThis, pMyParam->pFunc, pMyParam->pParam); RETiRet; } /* iterate over ALL actions present in the WHOLE system. * this is often needed, for example when HUP processing * must be done or a shutdown is pending. */ static rsRetVal iterateAllActions(rsRetVal (*pFunc)(void*, void*), void* pParam) { iterateAllActions_t params; DEFiRet; assert(pFunc != NULL); params.pFunc = pFunc; params.pParam = pParam; CHKiRet(llExecFunc(&llRulesets, doIterateAllActions, &params)); finalize_it: RETiRet; } /* helper to processBatch(), used to call the configured actions. It is * executed from within llExecFunc() of the action list. * rgerhards, 2007-08-02 */ DEFFUNC_llExecFunc(processBatchDoRules) { rsRetVal iRet; ISOBJ_TYPE_assert(pData, rule); dbgprintf("Processing next rule\n"); iRet = rule.ProcessBatch((rule_t*) pData, (batch_t*) pParam); dbgprintf("ruleset: get iRet %d from rule.ProcessMsg()\n", iRet); return iRet; } /* This function is similar to processBatch(), but works on a batch that * contains rules from multiple rulesets. In this case, we can not push * the whole batch through the ruleset. Instead, we examine it and * partition it into sub-rulesets which we then push through the system. * Note that when we evaluate which message must be processed, we do NOT need * to look at bFilterOK, because this value is only set in a later processing * stage. Doing so caused a bug during development ;) * rgerhards, 2010-06-15 */ static inline rsRetVal processBatchMultiRuleset(batch_t *pBatch) { ruleset_t *currRuleset; batch_t snglRuleBatch; int i; int iStart; /* start index of partial batch */ int iNew; /* index for new (temporary) batch */ int bHaveUnprocessed; /* do we (still) have unprocessed entries? (loop term predicate) */ DEFiRet; do { bHaveUnprocessed = 0; /* search for first unprocessed element */ for(iStart = 0 ; iStart < pBatch->nElem && pBatch->pElem[iStart].state == BATCH_STATE_DISC ; ++iStart) /* just search, no action */; if(iStart == pBatch->nElem) break; /* everything processed */ /* prepare temporary batch */ CHKiRet(batchInit(&snglRuleBatch, pBatch->nElem)); snglRuleBatch.pbShutdownImmediate = pBatch->pbShutdownImmediate; currRuleset = batchElemGetRuleset(pBatch, iStart); iNew = 0; for(i = iStart ; i < pBatch->nElem ; ++i) { if(batchElemGetRuleset(pBatch, i) == currRuleset) { /* for performance reasons, we copy only those members that we actually need */ snglRuleBatch.pElem[iNew].pUsrp = pBatch->pElem[i].pUsrp; snglRuleBatch.pElem[iNew].state = pBatch->pElem[i].state; ++iNew; /* We indicate the element also as done, so it will not be processed again */ pBatch->pElem[i].state = BATCH_STATE_DISC; } else { bHaveUnprocessed = 1; } } snglRuleBatch.nElem = iNew; /* was left just right by the for loop */ batchSetSingleRuleset(&snglRuleBatch, 1); /* process temp batch */ processBatch(&snglRuleBatch); batchFree(&snglRuleBatch); } while(bHaveUnprocessed == 1); finalize_it: RETiRet; } /* Process (consume) a batch of messages. Calls the actions configured. * If the whole batch uses a singel ruleset, we can process the batch as * a whole. Otherwise, we need to process it slower, on a message-by-message * basis (what can be optimized to a per-ruleset basis) * rgerhards, 2005-10-13 */ static rsRetVal processBatch(batch_t *pBatch) { ruleset_t *pThis; DEFiRet; assert(pBatch != NULL); dbgprintf("ZZZ: processBatch: batch of %d elements must be processed\n", pBatch->nElem); if(pBatch->bSingleRuleset) { pThis = batchGetRuleset(pBatch); if(pThis == NULL) pThis = pDfltRuleset; ISOBJ_TYPE_assert(pThis, ruleset); CHKiRet(llExecFunc(&pThis->llRules, processBatchDoRules, pBatch)); } else { CHKiRet(processBatchMultiRuleset(pBatch)); } finalize_it: dbgprintf("ruleset.ProcessMsg() returns %d\n", iRet); RETiRet; } /* return the ruleset-assigned parser list. NULL means use the default * parser list. * rgerhards, 2009-11-04 */ static parserList_t* GetParserList(msg_t *pMsg) { return (pMsg->pRuleset == NULL) ? pDfltRuleset->pParserLst : pMsg->pRuleset->pParserLst; } /* Add a new rule to the end of the current rule set. We do a number * of checks and ignore the rule if it does not pass them. */ static rsRetVal addRule(ruleset_t *pThis, rule_t **ppRule) { int iActionCnt; DEFiRet; ISOBJ_TYPE_assert(pThis, ruleset); ISOBJ_TYPE_assert(*ppRule, rule); CHKiRet(llGetNumElts(&(*ppRule)->llActList, &iActionCnt)); if(iActionCnt == 0) { errmsg.LogError(0, NO_ERRCODE, "warning: selector line without actions will be discarded"); rule.Destruct(ppRule); } else { CHKiRet(llAppend(&pThis->llRules, NULL, *ppRule)); dbgprintf("selector line successfully processed\n"); } finalize_it: RETiRet; } /* set name for ruleset */ static rsRetVal setName(ruleset_t *pThis, uchar *pszName) { DEFiRet; free(pThis->pszName); CHKmalloc(pThis->pszName = ustrdup(pszName)); finalize_it: RETiRet; } /* get current ruleset * We use a non-standard calling interface, as nothing can go wrong and it * is really much more natural to return the pointer directly. */ static ruleset_t* GetCurrent(void) { return pCurrRuleset; } /* get main queue associated with ruleset. If no ruleset-specifc main queue * is set, the primary main message queue is returned. * We use a non-standard calling interface, as nothing can go wrong and it * is really much more natural to return the pointer directly. */ static qqueue_t* GetRulesetQueue(ruleset_t *pThis) { ISOBJ_TYPE_assert(pThis, ruleset); return (pThis->pQueue == NULL) ? pMsgQueue : pThis->pQueue; } /* Find the ruleset with the given name and return a pointer to its object. */ static rsRetVal GetRuleset(ruleset_t **ppRuleset, uchar *pszName) { DEFiRet; assert(ppRuleset != NULL); assert(pszName != NULL); CHKiRet(llFind(&llRulesets, pszName, (void*) ppRuleset)); finalize_it: RETiRet; } /* Set a new default rule set. If the default can not be found, no change happens. */ static rsRetVal SetDefaultRuleset(uchar *pszName) { ruleset_t *pRuleset; DEFiRet; assert(pszName != NULL); CHKiRet(GetRuleset(&pRuleset, pszName)); pDfltRuleset = pRuleset; dbgprintf("default rule set changed to %p: '%s'\n", pRuleset, pszName); finalize_it: RETiRet; } /* Set a new current rule set. If the ruleset can not be found, no change happens. */ static rsRetVal SetCurrRuleset(uchar *pszName) { ruleset_t *pRuleset; DEFiRet; assert(pszName != NULL); CHKiRet(GetRuleset(&pRuleset, pszName)); pCurrRuleset = pRuleset; dbgprintf("current rule set changed to %p: '%s'\n", pRuleset, pszName); finalize_it: RETiRet; } /* destructor we need to destruct rules inside our linked list contents. */ static rsRetVal doRuleDestruct(void *pData) { rule_t *pRule = (rule_t *) pData; DEFiRet; rule.Destruct(&pRule); RETiRet; } /* Standard-Constructor */ BEGINobjConstruct(ruleset) /* be sure to specify the object type also in END macro! */ CHKiRet(llInit(&pThis->llRules, doRuleDestruct, NULL, NULL)); finalize_it: ENDobjConstruct(ruleset) /* ConstructionFinalizer * This also adds the rule set to the list of all known rulesets. */ static rsRetVal rulesetConstructFinalize(ruleset_t *pThis) { uchar *keyName; DEFiRet; ISOBJ_TYPE_assert(pThis, ruleset); /* we must duplicate our name, as the key destructer would also * free it, resulting in a double-free. It's also cleaner to have * two separate copies. */ CHKmalloc(keyName = ustrdup(pThis->pszName)); CHKiRet(llAppend(&llRulesets, keyName, pThis)); /* this now also is the new current ruleset */ pCurrRuleset = pThis; /* and also the default, if so far none has been set */ if(pDfltRuleset == NULL) pDfltRuleset = pThis; finalize_it: RETiRet; } /* destructor for the ruleset object */ BEGINobjDestruct(ruleset) /* be sure to specify the object type also in END and CODESTART macros! */ CODESTARTobjDestruct(ruleset) dbgprintf("destructing ruleset %p, name %p\n", pThis, pThis->pszName); if(pThis->pQueue != NULL) { qqueueDestruct(&pThis->pQueue); } if(pThis->pParserLst != NULL) { parser.DestructParserList(&pThis->pParserLst); } llDestroy(&pThis->llRules); free(pThis->pszName); ENDobjDestruct(ruleset) /* this is a special destructor for the linkedList class. LinkedList does NOT * provide a pointer to the pointer, but rather the raw pointer itself. So we * must map this, otherwise the destructor will abort. */ static rsRetVal rulesetDestructForLinkedList(void *pData) { ruleset_t *pThis = (ruleset_t*) pData; return rulesetDestruct(&pThis); } /* destruct ALL rule sets that reside in the system. This must * be callable before unloading this module as the module may * not be unloaded before unload of the actions is required. This is * kind of a left-over from previous logic and may be optimized one * everything runs stable again. -- rgerhards, 2009-06-10 */ static rsRetVal destructAllActions(void) { DEFiRet; CHKiRet(llDestroy(&llRulesets)); CHKiRet(llInit(&llRulesets, rulesetDestructForLinkedList, keyDestruct, strcasecmp)); pDfltRuleset = NULL; finalize_it: RETiRet; } /* helper for debugPrint(), initiates rule printing */ DEFFUNC_llExecFunc(doDebugPrintRule) { return rule.DebugPrint((rule_t*) pData); } /* debugprint for the ruleset object */ BEGINobjDebugPrint(ruleset) /* be sure to specify the object type also in END and CODESTART macros! */ CODESTARTobjDebugPrint(ruleset) dbgoprint((obj_t*) pThis, "rsyslog ruleset %s:\n", pThis->pszName); llExecFunc(&pThis->llRules, doDebugPrintRule, NULL); ENDobjDebugPrint(ruleset) /* helper for debugPrintAll(), prints a single ruleset */ DEFFUNC_llExecFunc(doDebugPrintAll) { return rulesetDebugPrint((ruleset_t*) pData); } /* debug print all rulesets */ static rsRetVal debugPrintAll(void) { DEFiRet; dbgprintf("All Rulesets:\n"); llExecFunc(&llRulesets, doDebugPrintAll, NULL); dbgprintf("End of Rulesets.\n"); RETiRet; } /* Create a ruleset-specific "main" queue for this ruleset. If one is already * defined, an error message is emitted but nothing else is done. * Note: we use the main message queue parameters for queue creation and access * syslogd.c directly to obtain these. This is far from being perfect, but * considered acceptable for the time being. * rgerhards, 2009-10-27 */ static rsRetVal rulesetCreateQueue(void __attribute__((unused)) *pVal, int *pNewVal) { DEFiRet; if(pCurrRuleset == NULL) { errmsg.LogError(0, RS_RET_NO_CURR_RULESET, "error: currently no specific ruleset specified, thus a " "queue can not be added to it"); ABORT_FINALIZE(RS_RET_NO_CURR_RULESET); } if(pCurrRuleset->pQueue != NULL) { errmsg.LogError(0, RS_RET_RULES_QUEUE_EXISTS, "error: ruleset already has a main queue, can not " "add another one"); ABORT_FINALIZE(RS_RET_RULES_QUEUE_EXISTS); } if(pNewVal == 0) FINALIZE; /* if it is turned off, we do not need to change anything ;) */ dbgprintf("adding a ruleset-specific \"main\" queue"); CHKiRet(createMainQueue(&pCurrRuleset->pQueue, UCHAR_CONSTANT("ruleset"))); finalize_it: RETiRet; } /* Add a ruleset specific parser to the ruleset. Note that adding the first * parser automatically disables the default parsers. If they are needed as well, * the must be added via explicit config directives. * Note: this is the only spot in the code that requires the parser object. In order * to solve some class init bootstrap sequence problems, we get the object handle here * instead of during module initialization. Note that objUse() is capable of being * called multiple times. * rgerhards, 2009-11-04 */ static rsRetVal rulesetAddParser(void __attribute__((unused)) *pVal, uchar *pName) { parser_t *pParser; DEFiRet; assert(pCurrRuleset != NULL); CHKiRet(objUse(parser, CORE_COMPONENT)); iRet = parser.FindParser(&pParser, pName); if(iRet == RS_RET_PARSER_NOT_FOUND) { errmsg.LogError(0, RS_RET_PARSER_NOT_FOUND, "error: parser '%s' unknown at this time " "(maybe defined too late in rsyslog.conf?)", pName); ABORT_FINALIZE(RS_RET_NO_CURR_RULESET); } else if(iRet != RS_RET_OK) { errmsg.LogError(0, iRet, "error trying to find parser '%s'\n", pName); FINALIZE; } CHKiRet(parser.AddParserToList(&pCurrRuleset->pParserLst, pParser)); dbgprintf("added parser '%s' to ruleset '%s'\n", pName, pCurrRuleset->pszName); RUNLOG_VAR("%p", pCurrRuleset->pParserLst); finalize_it: d_free(pName); /* no longer needed */ RETiRet; } /* queryInterface function * rgerhards, 2008-02-21 */ BEGINobjQueryInterface(ruleset) CODESTARTobjQueryInterface(ruleset) if(pIf->ifVersion != rulesetCURR_IF_VERSION) { /* check for current version, increment on each change */ ABORT_FINALIZE(RS_RET_INTERFACE_NOT_SUPPORTED); } /* ok, we have the right interface, so let's fill it * Please note that we may also do some backwards-compatibility * work here (if we can support an older interface version - that, * of course, also affects the "if" above). */ pIf->Construct = rulesetConstruct; pIf->ConstructFinalize = rulesetConstructFinalize; pIf->Destruct = rulesetDestruct; pIf->DebugPrint = rulesetDebugPrint; pIf->IterateAllActions = iterateAllActions; pIf->DestructAllActions = destructAllActions; pIf->AddRule = addRule; pIf->ProcessBatch = processBatch; pIf->SetName = setName; pIf->DebugPrintAll = debugPrintAll; pIf->GetCurrent = GetCurrent; pIf->GetRuleset = GetRuleset; pIf->SetDefaultRuleset = SetDefaultRuleset; pIf->SetCurrRuleset = SetCurrRuleset; pIf->GetRulesetQueue = GetRulesetQueue; pIf->GetParserList = GetParserList; finalize_it: ENDobjQueryInterface(ruleset) /* Exit the ruleset class. * rgerhards, 2009-04-06 */ BEGINObjClassExit(ruleset, OBJ_IS_CORE_MODULE) /* class, version */ llDestroy(&llRulesets); objRelease(errmsg, CORE_COMPONENT); objRelease(rule, CORE_COMPONENT); objRelease(parser, CORE_COMPONENT); ENDObjClassExit(ruleset) /* Initialize the ruleset class. Must be called as the very first method * before anything else is called inside this class. * rgerhards, 2008-02-19 */ BEGINObjClassInit(ruleset, 1, OBJ_IS_CORE_MODULE) /* class, version */ /* request objects we use */ CHKiRet(objUse(errmsg, CORE_COMPONENT)); CHKiRet(objUse(rule, CORE_COMPONENT)); /* set our own handlers */ OBJSetMethodHandler(objMethod_DEBUGPRINT, rulesetDebugPrint); OBJSetMethodHandler(objMethod_CONSTRUCTION_FINALIZER, rulesetConstructFinalize); /* prepare global data */ CHKiRet(llInit(&llRulesets, rulesetDestructForLinkedList, keyDestruct, strcasecmp)); /* config file handlers */ CHKiRet(regCfSysLineHdlr((uchar *)"rulesetparser", 0, eCmdHdlrGetWord, rulesetAddParser, NULL, NULL)); CHKiRet(regCfSysLineHdlr((uchar *)"rulesetcreatemainqueue", 0, eCmdHdlrBinary, rulesetCreateQueue, NULL, NULL)); ENDObjClassInit(ruleset) /* vi:set ai: */
./CrossVul/dataset_final_sorted/CWE-772/c/good_3450_2
crossvul-cpp_data_good_2621_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % M M AAA TTTTT L AAA BBBB % % MM MM A A T L A A B B % % M M M AAAAA T L AAAAA BBBB % % M M A A T L A A B B % % M M A A T LLLLL A A BBBB % % % % % % Read MATLAB Image Format % % % % Software Design % % Jaroslav Fojtik % % 2001-2008 % % % % % % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick is furnished to do so, subject to the following conditions: % % % % The above copyright notice and this permission notice shall be included in % % all copies or substantial portions of ImageMagick. % % % % The software is provided "as is", without warranty of any kind, express or % % implied, including but not limited to the warranties of merchantability, % % fitness for a particular purpose and noninfringement. In no event shall % % ImageMagick Studio be liable for any claim, damages or other liability, % % whether in an action of contract, tort or otherwise, arising from, out of % % or in connection with ImageMagick or the use or other dealings in % % ImageMagick. % % % % Except as contained in this notice, the name of the ImageMagick Studio % % shall not be used in advertising or otherwise to promote the sale, use or % % other dealings in ImageMagick without prior written authorization from the % % ImageMagick Studio. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace-private.h" #include "magick/distort.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/transform.h" #include "magick/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Forward declaration. */ static MagickBooleanType WriteMATImage(const ImageInfo *,Image *); /* Auto coloring method, sorry this creates some artefact inside data MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black MinReal+j*0 = white MaxReal+j*0 = black MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black */ typedef struct { char identific[124]; unsigned short Version; char EndianIndicator[2]; unsigned long DataType; unsigned int ObjectSize; unsigned long unknown1; unsigned long unknown2; unsigned short unknown5; unsigned char StructureFlag; unsigned char StructureClass; unsigned long unknown3; unsigned long unknown4; unsigned long DimFlag; unsigned long SizeX; unsigned long SizeY; unsigned short Flag1; unsigned short NameFlag; } MATHeader; static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; static const char *OsDesc= #if defined(MAGICKCORE_WINDOWS_SUPPORT) "PCWIN"; #else #ifdef __APPLE__ "MAC"; #else "LNX86"; #endif #endif typedef enum { miINT8 = 1, /* 8 bit signed */ miUINT8, /* 8 bit unsigned */ miINT16, /* 16 bit signed */ miUINT16, /* 16 bit unsigned */ miINT32, /* 32 bit signed */ miUINT32, /* 32 bit unsigned */ miSINGLE, /* IEEE 754 single precision float */ miRESERVE1, miDOUBLE, /* IEEE 754 double precision float */ miRESERVE2, miRESERVE3, miINT64, /* 64 bit signed */ miUINT64, /* 64 bit unsigned */ miMATRIX, /* MATLAB array */ miCOMPRESSED, /* Compressed Data */ miUTF8, /* Unicode UTF-8 Encoded Character Data */ miUTF16, /* Unicode UTF-16 Encoded Character Data */ miUTF32 /* Unicode UTF-32 Encoded Character Data */ } mat5_data_type; typedef enum { mxCELL_CLASS=1, /* cell array */ mxSTRUCT_CLASS, /* structure */ mxOBJECT_CLASS, /* object */ mxCHAR_CLASS, /* character array */ mxSPARSE_CLASS, /* sparse array */ mxDOUBLE_CLASS, /* double precision array */ mxSINGLE_CLASS, /* single precision floating point */ mxINT8_CLASS, /* 8 bit signed integer */ mxUINT8_CLASS, /* 8 bit unsigned integer */ mxINT16_CLASS, /* 16 bit signed integer */ mxUINT16_CLASS, /* 16 bit unsigned integer */ mxINT32_CLASS, /* 32 bit signed integer */ mxUINT32_CLASS, /* 32 bit unsigned integer */ mxINT64_CLASS, /* 64 bit signed integer */ mxUINT64_CLASS, /* 64 bit unsigned integer */ mxFUNCTION_CLASS /* Function handle */ } arrayclasstype; #define FLAG_COMPLEX 0x8 #define FLAG_GLOBAL 0x4 #define FLAG_LOGICAL 0x2 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum}; static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal, double MaxVal) { ExceptionInfo *exception; double f; int x; register PixelPacket *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; exception=(&image->exception); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q)); if (f + GetPixelRed(q) > QuantumRange) SetPixelRed(q,QuantumRange); else SetPixelRed(q,GetPixelRed(q)+(int) f); if ((int) f / 2.0 > GetPixelGreen(q)) { SetPixelGreen(q,0); SetPixelBlue(q,0); } else { SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelBlue(q)); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q)); if (f + GetPixelBlue(q) > QuantumRange) SetPixelBlue(q,QuantumRange); else SetPixelBlue(q,GetPixelBlue(q)+(int) f); if ((int) f / 2.0 > q->green) { SetPixelRed(q,0); SetPixelGreen(q,0); } else { SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelRed(q)); } } p++; q++; } if (!SyncAuthenticPixels(image,exception)) return; return; } static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal, double MaxVal) { ExceptionInfo *exception; double f; int x; register PixelPacket *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; exception=(&image->exception); q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception); if (q == (PixelPacket *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q)); if (f + GetPixelRed(q) > QuantumRange) SetPixelRed(q,QuantumRange); else SetPixelRed(q,GetPixelRed(q)+(int) f); if ((int) f / 2.0 > GetPixelGreen(q)) { SetPixelGreen(q,0); SetPixelBlue(q,0); } else { SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelBlue(q)); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q)); if (f + GetPixelBlue(q) > QuantumRange) SetPixelBlue(q,QuantumRange); else SetPixelBlue(q,GetPixelBlue(q)+(int) f); if ((int) f / 2.0 > q->green) { SetPixelGreen(q,0); SetPixelRed(q,0); } else { SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelRed(q)); } } p++; q++; } if (!SyncAuthenticPixels(image,exception)) return; return; } /************** READERS ******************/ /* This function reads one block of floats*/ static void ReadBlobFloatsLSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobFloatsMSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* This function reads one block of doubles*/ static void ReadBlobDoublesLSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobDoublesMSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* Calculate minimum and maximum from a given block of data */ static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max) { MagickOffsetType filepos; int i, x; void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); double *dblrow; float *fltrow; if (endian_indicator == LSBEndian) { ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; } else /* MI */ { ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; } filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */ for (i = 0; i < SizeY; i++) { if (CellType==miDOUBLE) { ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff); dblrow = (double *)BImgBuff; if (i == 0) { *Min = *Max = *dblrow; } for (x = 0; x < SizeX; x++) { if (*Min > *dblrow) *Min = *dblrow; if (*Max < *dblrow) *Max = *dblrow; dblrow++; } } if (CellType==miSINGLE) { ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff); fltrow = (float *)BImgBuff; if (i == 0) { *Min = *Max = *fltrow; } for (x = 0; x < (ssize_t) SizeX; x++) { if (*Min > *fltrow) *Min = *fltrow; if (*Max < *fltrow) *Max = *fltrow; fltrow++; } } } (void) SeekBlob(image, filepos, SEEK_SET); } static void FixSignedValues(PixelPacket *q, int y) { while(y-->0) { /* Please note that negative values will overflow Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255> <-1;-128> + 127+1 = <0; 127> */ SetPixelRed(q,GetPixelRed(q)+QuantumRange/2+1); SetPixelGreen(q,GetPixelGreen(q)+QuantumRange/2+1); SetPixelBlue(q,GetPixelBlue(q)+QuantumRange/2+1); q++; } } /** Fix whole row of logical/binary data. It means pack it. */ static void FixLogical(unsigned char *Buff,int ldblk) { unsigned char mask=128; unsigned char *BuffL = Buff; unsigned char val = 0; while(ldblk-->0) { if(*Buff++ != 0) val |= mask; mask >>= 1; if(mask==0) { *BuffL++ = val; val = 0; mask = 128; } } *BuffL = val; } #if defined(MAGICKCORE_ZLIB_DELEGATE) static voidpf AcquireZIPMemory(voidpf context,unsigned int items, unsigned int size) { (void) context; return((voidpf) AcquireQuantumMemory(items,size)); } static void RelinquishZIPMemory(voidpf context,voidpf memory) { (void) context; memory=RelinquishMagickMemory(memory); } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) /** This procedure decompreses an image block for a new MATLAB format. */ static Image *decompress_block(Image *orig, unsigned int *Size, ImageInfo *clone_info, ExceptionInfo *exception) { Image *image2; void *cache_block, *decompress_block; z_stream zip_info; FILE *mat_file; size_t magick_size; size_t extent; int file; int status; int zip_status; ssize_t TotalSize = 0; if(clone_info==NULL) return NULL; if(clone_info->file) /* Close file opened from previous transaction. */ { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } cache_block = AcquireQuantumMemory((size_t)(*Size< 16384) ? *Size: 16384,sizeof(unsigned char *)); if(cache_block==NULL) return NULL; decompress_block = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *)); if(decompress_block==NULL) { RelinquishMagickMemory(cache_block); return NULL; } mat_file=0; file = AcquireUniqueFileResource(clone_info->filename); if (file != -1) mat_file = fdopen(file,"w"); if(!mat_file) { RelinquishMagickMemory(cache_block); RelinquishMagickMemory(decompress_block); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Cannot create file stream for decompressed image"); return NULL; } zip_info.zalloc=AcquireZIPMemory; zip_info.zfree=RelinquishZIPMemory; zip_info.opaque = (voidpf) NULL; zip_status = inflateInit(&zip_info); if (zip_status != Z_OK) { RelinquishMagickMemory(cache_block); RelinquishMagickMemory(decompress_block); (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "UnableToUncompressImage","`%s'",clone_info->filename); (void) fclose(mat_file); RelinquishUniqueFileResource(clone_info->filename); return NULL; } /* zip_info.next_out = 8*4;*/ zip_info.avail_in = 0; zip_info.total_out = 0; while(*Size>0 && !EOFBlob(orig)) { magick_size = ReadBlob(orig, (*Size < 16384) ? *Size : 16384, (unsigned char *) cache_block); zip_info.next_in = (Bytef *) cache_block; zip_info.avail_in = (uInt) magick_size; while(zip_info.avail_in>0) { zip_info.avail_out = 4096; zip_info.next_out = (Bytef *) decompress_block; zip_status = inflate(&zip_info,Z_NO_FLUSH); if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END)) break; extent=fwrite(decompress_block, 4096-zip_info.avail_out, 1, mat_file); (void) extent; TotalSize += 4096-zip_info.avail_out; if(zip_status == Z_STREAM_END) goto DblBreak; } if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END)) break; *Size -= magick_size; } DblBreak: inflateEnd(&zip_info); (void)fclose(mat_file); RelinquishMagickMemory(cache_block); RelinquishMagickMemory(decompress_block); *Size = TotalSize; if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile; if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile; status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception); if (status == MagickFalse) { DeleteImageFromList(&image2); EraseFile: fclose(clone_info->file); clone_info->file = NULL; UnlinkFile: RelinquishUniqueFileResource(clone_info->filename); return NULL; } return image2; } #endif static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { typedef struct { unsigned char Type[4]; unsigned int nRows; unsigned int nCols; unsigned int imagf; unsigned int nameLen; } MAT4_HDR; long ldblk; EndianType endian; Image *rotate_image; MagickBooleanType status; MAT4_HDR HDR; QuantumInfo *quantum_info; QuantumFormatType format_type; register ssize_t i; ssize_t count, y; unsigned char *pixels; unsigned int depth; (void) SeekBlob(image,0,SEEK_SET); while (EOFBlob(image) != MagickFalse) { /* Object parser. */ ldblk=ReadBlobLSBLong(image); if (EOFBlob(image) != MagickFalse) break; if ((ldblk > 9999) || (ldblk < 0)) break; HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */ HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */ HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */ HDR.Type[0]=ldblk; /* M digit */ if (HDR.Type[3] != 0) break; /* Data format */ if (HDR.Type[2] != 0) break; /* Always 0 */ if (HDR.Type[0] == 0) { HDR.nRows=ReadBlobLSBLong(image); HDR.nCols=ReadBlobLSBLong(image); HDR.imagf=ReadBlobLSBLong(image); HDR.nameLen=ReadBlobLSBLong(image); endian=LSBEndian; } else { HDR.nRows=ReadBlobMSBLong(image); HDR.nCols=ReadBlobMSBLong(image); HDR.imagf=ReadBlobMSBLong(image); HDR.nameLen=ReadBlobMSBLong(image); endian=MSBEndian; } if ((HDR.imagf !=0) && (HDR.imagf !=1)) break; if (HDR.nameLen > 0xFFFF) break; for (i=0; i < (ssize_t) HDR.nameLen; i++) { int byte; /* Skip matrix name. */ byte=ReadBlobByte(image); if (byte == EOF) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } image->columns=(size_t) HDR.nRows; image->rows=(size_t) HDR.nCols; SetImageColorspace(image,GRAYColorspace); if (image_info->ping != MagickFalse) { Swap(image->columns,image->rows); return(image); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) return((Image *) NULL); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return((Image *) NULL); switch(HDR.Type[1]) { case 0: format_type=FloatingPointQuantumFormat; depth=64; break; case 1: format_type=FloatingPointQuantumFormat; depth=32; break; case 2: format_type=UnsignedQuantumFormat; depth=16; break; case 3: format_type=SignedQuantumFormat; depth=16; break; case 4: format_type=UnsignedQuantumFormat; depth=8; break; default: format_type=UnsignedQuantumFormat; depth=8; break; } image->depth=depth; if (HDR.Type[0] != 0) SetQuantumEndian(image,quantum_info,MSBEndian); status=SetQuantumFormat(image,quantum_info,format_type); status=SetQuantumDepth(image,quantum_info,depth); status=SetQuantumEndian(image,quantum_info,endian); SetQuantumScale(quantum_info,1.0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; count=ReadBlob(image,depth/8*image->columns,(unsigned char *) pixels); if (count == -1) break; q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3)) FixSignedValues(q,image->columns); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (HDR.imagf == 1) for (y=0; y < (ssize_t) image->rows; y++) { /* Read complex pixels. */ count=ReadBlob(image,depth/8*image->columns,(unsigned char *) pixels); if (count == -1) break; if (HDR.Type[1] == 0) InsertComplexDoubleRow((double *) pixels,y,image,0,0); else InsertComplexFloatRow((float *) pixels,y,image,0,0); } quantum_info=DestroyQuantumInfo(quantum_info); rotate_image=RotateImage(image,90.0,exception); if (rotate_image != (Image *) NULL) { image=DestroyImage(image); image=rotate_image; } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d M A T L A B i m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMATImage() reads an MAT X image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadMATImage method is: % % Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadMATImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; PixelPacket *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; size_t Unknown6; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ quantum_info=(QuantumInfo *) NULL; image = AcquireImage(image_info); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=(ImageInfo *) NULL; if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0) { image2=ReadMATImageV4(image_info,image,exception); if (image2 == NULL) goto MATLAB_KO; image=image2; goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) { MATLAB_KO: clone_info=DestroyImageInfo(clone_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; if(MATLAB_HDR.ObjectSize+filepos > GetBlobSize(image)) goto MATLAB_KO; filepos += MATLAB_HDR.ObjectSize + 4 + 4; clone_info=CloneImageInfo(image_info); image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ Unknown6 = ReadBlobXXXLong(image2); (void) Unknown6; if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); if (Frames == 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { SetImageColorspace(image,GRAYColorspace); image->type=GrayscaleType; } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double)); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (PixelPacket *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if(image2!=NULL) if(image2!=image) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) unlink(clone_info->filename); } } } } RelinquishMagickMemory(BImgBuff); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); END_OF_READING: if (clone_info) clone_info=DestroyImageInfo(clone_info); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method RegisterMATImage adds attributes for the MAT image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterMATImage method is: % % size_t RegisterMATImage(void) % */ ModuleExport size_t RegisterMATImage(void) { MagickInfo *entry; entry=SetMagickInfo("MAT"); entry->decoder=(DecodeImageHandler *) ReadMATImage; entry->encoder=(EncodeImageHandler *) WriteMATImage; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=AcquireString("MATLAB level 5 image format"); entry->module=AcquireString("MAT"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method UnregisterMATImage removes format registrations made by the % MAT module from the list of supported formats. % % The format of the UnregisterMATImage method is: % % UnregisterMATImage(void) % */ ModuleExport void UnregisterMATImage(void) { (void) UnregisterMagickInfo("MAT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M A T L A B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function WriteMATImage writes an Matlab matrix to a file. % % The format of the WriteMATImage method is: % % unsigned int WriteMATImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o status: Function WriteMATImage return True if the image is written. % False is returned is there is a memory shortage or if the image file % fails to write. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o image: A pointer to an Image structure. % */ static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image) { char MATLAB_HDR[0x80]; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType scene; struct tm local_time; time_t current_time; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(MagickFalse); image->depth=8; current_time=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&current_time,&local_time); #else (void) memcpy(&local_time,localtime(&current_time),sizeof(local_time)); #endif (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124)); FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR), "MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d", OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon], local_time.tm_mday,local_time.tm_hour,local_time.tm_min, local_time.tm_sec,local_time.tm_year+1900); MATLAB_HDR[0x7C]=0; MATLAB_HDR[0x7D]=1; MATLAB_HDR[0x7E]='I'; MATLAB_HDR[0x7F]='M'; (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR); scene=0; do { char padding; MagickBooleanType is_gray; QuantumInfo *quantum_info; size_t data_size; unsigned char *pixels; unsigned int z; (void) TransformImageColorspace(image,sRGBColorspace); is_gray=SetImageGray(image,&image->exception); z=(is_gray != MagickFalse) ? 0 : 3; /* Store MAT header. */ data_size=image->rows*image->columns; if (is_gray == MagickFalse) data_size*=3; padding=((unsigned char)(data_size-1) & 0x7) ^ 0x7; (void) WriteBlobLSBLong(image,miMATRIX); (void) WriteBlobLSBLong(image,(unsigned int) data_size+padding+ ((is_gray != MagickFalse) ? 48 : 56)); (void) WriteBlobLSBLong(image,0x6); /* 0x88 */ (void) WriteBlobLSBLong(image,0x8); /* 0x8C */ (void) WriteBlobLSBLong(image,0x6); /* 0x90 */ (void) WriteBlobLSBLong(image,0); (void) WriteBlobLSBLong(image,0x5); /* 0x98 */ (void) WriteBlobLSBLong(image,(is_gray != MagickFalse) ? 0x8 : 0xC); /* 0x9C - DimFlag */ (void) WriteBlobLSBLong(image,(unsigned int) image->rows); /* x: 0xA0 */ (void) WriteBlobLSBLong(image,(unsigned int) image->columns); /* y: 0xA4 */ if (is_gray == MagickFalse) { (void) WriteBlobLSBLong(image,3); /* z: 0xA8 */ (void) WriteBlobLSBLong(image,0); } (void) WriteBlobLSBShort(image,1); /* 0xB0 */ (void) WriteBlobLSBShort(image,1); /* 0xB2 */ (void) WriteBlobLSBLong(image,'M'); /* 0xB4 */ (void) WriteBlobLSBLong(image,0x2); /* 0xB8 */ (void) WriteBlobLSBLong(image,(unsigned int) data_size); /* 0xBC */ /* Store image data. */ exception=(&image->exception); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); do { const PixelPacket *p; ssize_t y; for (y=0; y < (ssize_t)image->columns; y++) { p=GetVirtualPixels(image,y,0,1,image->rows,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, z2qtype[z],pixels,exception); (void) WriteBlob(image,image->rows,pixels); } if (!SyncAuthenticPixels(image,exception)) break; } while (z-- >= 2); while (padding-- > 0) (void) WriteBlobByte(image,0); quantum_info=DestroyQuantumInfo(quantum_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-772/c/good_2621_0
crossvul-cpp_data_good_2623_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA L SSSSS % % C A A L SS % % C AAAAA L SSS % % C A A L SS % % CCCC A A LLLLL SSSSS % % % % % % Read/Write CALS Raster Group 1 Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The CALS raster format is a standard developed by the Computer Aided % Acquisition and Logistics Support (CALS) office of the United States % Department of Defense to standardize graphics data interchange for % electronic publishing, especially in the areas of technical graphics, % CAD/CAM, and image processing applications. % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/colorspace.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #if defined(MAGICKCORE_TIFF_DELEGATE) /* Forward declarations. */ static MagickBooleanType WriteCALSImage(const ImageInfo *,Image *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s C A L S % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsCALS() returns MagickTrue if the image format type, identified by the % magick string, is CALS Raster Group 1. % % The format of the IsCALS method is: % % MagickBooleanType IsCALS(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsCALS(const unsigned char *magick,const size_t length) { if (length < 128) return(MagickFalse); if (LocaleNCompare((const char *) magick,"version: MIL-STD-1840",21) == 0) return(MagickTrue); if (LocaleNCompare((const char *) magick,"srcdocid:",9) == 0) return(MagickTrue); if (LocaleNCompare((const char *) magick,"rorient:",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d C A L S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadCALSImage() reads an CALS Raster Group 1 image format image file and % returns it. It allocates the memory necessary for the new Image structure % and returns a pointer to the new image. % % The format of the ReadCALSImage method is: % % Image *ReadCALSImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadCALSImage(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MaxTextExtent], header[129], message[MaxTextExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register ssize_t i; unsigned long density, direction, height, orientation, pel_path, type, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read CALS header. */ (void) ResetMagickMemory(header,0,sizeof(header)); density=0; direction=0; orientation=1; pel_path=0; type=1; width=0; height=0; for (i=0; i < 16; i++) { if (ReadBlob(image,128,(unsigned char *) header) != 128) break; switch (*header) { case 'R': case 'r': { if (LocaleNCompare(header,"rdensty:",8) == 0) { (void) sscanf(header+8,"%lu",&density); break; } if (LocaleNCompare(header,"rpelcnt:",8) == 0) { (void) sscanf(header+8,"%lu,%lu",&width,&height); break; } if (LocaleNCompare(header,"rorient:",8) == 0) { (void) sscanf(header+8,"%lu,%lu",&pel_path,&direction); if (pel_path == 90) orientation=5; else if (pel_path == 180) orientation=3; else if (pel_path == 270) orientation=7; if (direction == 90) orientation++; break; } if (LocaleNCompare(header,"rtype:",6) == 0) { (void) sscanf(header+6,"%lu",&type); break; } break; } } } /* Read CALS pixels. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); while ((c=ReadBlobByte(image)) != EOF) (void) fputc(c,file); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"group4:%s", filename); (void) FormatLocaleString(message,MaxTextExtent,"%lux%lu",width,height); read_info->size=ConstantString(message); (void) FormatLocaleString(message,MaxTextExtent,"%lu",density); read_info->density=ConstantString(message); read_info->orientation=(OrientationType) orientation; image=ReadImage(read_info,exception); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick,"CALS",MaxTextExtent); } read_info=DestroyImageInfo(read_info); (void) RelinquishUniqueFileResource(filename); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r C A L S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterCALSImage() adds attributes for the CALS Raster Group 1 image file % image format to the list of supported formats. The attributes include the % image format tag, a method to read and/or write the format, whether the % format supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief description % of the format. % % The format of the RegisterCALSImage method is: % % size_t RegisterCALSImage(void) % */ ModuleExport size_t RegisterCALSImage(void) { MagickInfo *entry; static const char *CALSDescription= { "Continuous Acquisition and Life-cycle Support Type 1" }, *CALSNote= { "Specified in MIL-R-28002 and MIL-PRF-28002" }; entry=SetMagickInfo("CAL"); entry->decoder=(DecodeImageHandler *) ReadCALSImage; #if defined(MAGICKCORE_TIFF_DELEGATE) entry->encoder=(EncodeImageHandler *) WriteCALSImage; #endif entry->adjoin=MagickFalse; entry->magick=(IsImageFormatHandler *) IsCALS; entry->description=ConstantString(CALSDescription); entry->note=ConstantString(CALSNote); entry->module=ConstantString("CALS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("CALS"); entry->decoder=(DecodeImageHandler *) ReadCALSImage; #if defined(MAGICKCORE_TIFF_DELEGATE) entry->encoder=(EncodeImageHandler *) WriteCALSImage; #endif entry->adjoin=MagickFalse; entry->magick=(IsImageFormatHandler *) IsCALS; entry->description=ConstantString(CALSDescription); entry->note=ConstantString(CALSNote); entry->module=ConstantString("CALS"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r C A L S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterCALSImage() removes format registrations made by the % CALS module from the list of supported formats. % % The format of the UnregisterCALSImage method is: % % UnregisterCALSImage(void) % */ ModuleExport void UnregisterCALSImage(void) { (void) UnregisterMagickInfo("CAL"); (void) UnregisterMagickInfo("CALS"); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e C A L S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteCALSImage() writes an image to a file in CALS Raster Group 1 image % format. % % The format of the WriteCALSImage method is: % % MagickBooleanType WriteCALSImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static ssize_t WriteCALSRecord(Image *image,const char *data) { char pad[128]; register const char *p; register ssize_t i; ssize_t count; i=0; count=0; if (data != (const char *) NULL) { p=data; for (i=0; (i < 128) && (p[i] != '\0'); i++); count=WriteBlob(image,(size_t) i,(const unsigned char *) data); } if (i < 128) { i=128-i; (void) ResetMagickMemory(pad,' ',(size_t) i); count=WriteBlob(image,(size_t) i,(const unsigned char *) pad); } return(count); } static MagickBooleanType WriteCALSImage(const ImageInfo *image_info, Image *image) { char header[MaxTextExtent]; Image *group4_image; ImageInfo *write_info; MagickBooleanType status; register ssize_t i; size_t density, length, orient_x, orient_y; ssize_t count; unsigned char *group4; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Create standard CALS header. */ count=WriteCALSRecord(image,"srcdocid: NONE"); (void) count; count=WriteCALSRecord(image,"dstdocid: NONE"); count=WriteCALSRecord(image,"txtfilid: NONE"); count=WriteCALSRecord(image,"figid: NONE"); count=WriteCALSRecord(image,"srcgph: NONE"); count=WriteCALSRecord(image,"doccls: NONE"); count=WriteCALSRecord(image,"rtype: 1"); orient_x=0; orient_y=0; switch (image->orientation) { case TopRightOrientation: { orient_x=180; orient_y=270; break; } case BottomRightOrientation: { orient_x=180; orient_y=90; break; } case BottomLeftOrientation: { orient_y=90; break; } case LeftTopOrientation: { orient_x=270; break; } case RightTopOrientation: { orient_x=270; orient_y=180; break; } case RightBottomOrientation: { orient_x=90; orient_y=180; break; } case LeftBottomOrientation: { orient_x=90; break; } default: { orient_y=270; break; } } (void) FormatLocaleString(header,sizeof(header),"rorient: %03ld,%03ld", (long) orient_x,(long) orient_y); count=WriteCALSRecord(image,header); (void) FormatLocaleString(header,sizeof(header),"rpelcnt: %06lu,%06lu", (unsigned long) image->columns,(unsigned long) image->rows); count=WriteCALSRecord(image,header); density=200; if (image_info->density != (char *) NULL) { GeometryInfo geometry_info; (void) ParseGeometry(image_info->density,&geometry_info); density=(size_t) floor(geometry_info.rho+0.5); } (void) FormatLocaleString(header,sizeof(header),"rdensty: %04lu", (unsigned long) density); count=WriteCALSRecord(image,header); count=WriteCALSRecord(image,"notes: NONE"); (void) ResetMagickMemory(header,' ',128); for (i=0; i < 5; i++) (void) WriteBlob(image,128,(unsigned char *) header); /* Write CALS pixels. */ write_info=CloneImageInfo(image_info); (void) CopyMagickString(write_info->filename,"GROUP4:",MaxTextExtent); (void) CopyMagickString(write_info->magick,"GROUP4",MaxTextExtent); group4_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (group4_image == (Image *) NULL) { write_info=DestroyImageInfo(write_info); (void) CloseBlob(image); return(MagickFalse); } group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length, &image->exception); group4_image=DestroyImage(group4_image); if (group4 == (unsigned char *) NULL) { write_info=DestroyImageInfo(write_info); (void) CloseBlob(image); return(MagickFalse); } write_info=DestroyImageInfo(write_info); if (WriteBlob(image,length,group4) != (ssize_t) length) status=MagickFalse; group4=(unsigned char *) RelinquishMagickMemory(group4); (void) CloseBlob(image); return(status); } #endif
./CrossVul/dataset_final_sorted/CWE-772/c/good_2623_0
crossvul-cpp_data_good_2741_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % M M AAA TTTTT L AAA BBBB % % MM MM A A T L A A B B % % M M M AAAAA T L AAAAA BBBB % % M M A A T L A A B B % % M M A A T LLLLL A A BBBB % % % % % % Read MATLAB Image Format % % % % Software Design % % Jaroslav Fojtik % % 2001-2008 % % % % % % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick is furnished to do so, subject to the following conditions: % % % % The above copyright notice and this permission notice shall be included in % % all copies or substantial portions of ImageMagick. % % % % The software is provided "as is", without warranty of any kind, express or % % implied, including but not limited to the warranties of merchantability, % % fitness for a particular purpose and noninfringement. In no event shall % % ImageMagick Studio be liable for any claim, damages or other liability, % % whether in an action of contract, tort or otherwise, arising from, out of % % or in connection with ImageMagick or the use or other dealings in % % ImageMagick. % % % % Except as contained in this notice, the name of the ImageMagick Studio % % shall not be used in advertising or otherwise to promote the sale, use or % % other dealings in ImageMagick without prior written authorization from the % % ImageMagick Studio. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace-private.h" #include "magick/distort.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/transform.h" #include "magick/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Forward declaration. */ static MagickBooleanType WriteMATImage(const ImageInfo *,Image *); /* Auto coloring method, sorry this creates some artefact inside data MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black MinReal+j*0 = white MaxReal+j*0 = black MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black */ typedef struct { char identific[124]; unsigned short Version; char EndianIndicator[2]; unsigned long DataType; unsigned long ObjectSize; unsigned long unknown1; unsigned long unknown2; unsigned short unknown5; unsigned char StructureFlag; unsigned char StructureClass; unsigned long unknown3; unsigned long unknown4; unsigned long DimFlag; unsigned long SizeX; unsigned long SizeY; unsigned short Flag1; unsigned short NameFlag; } MATHeader; static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; static const char *OsDesc= #if defined(MAGICKCORE_WINDOWS_SUPPORT) "PCWIN"; #else #ifdef __APPLE__ "MAC"; #else "LNX86"; #endif #endif typedef enum { miINT8 = 1, /* 8 bit signed */ miUINT8, /* 8 bit unsigned */ miINT16, /* 16 bit signed */ miUINT16, /* 16 bit unsigned */ miINT32, /* 32 bit signed */ miUINT32, /* 32 bit unsigned */ miSINGLE, /* IEEE 754 single precision float */ miRESERVE1, miDOUBLE, /* IEEE 754 double precision float */ miRESERVE2, miRESERVE3, miINT64, /* 64 bit signed */ miUINT64, /* 64 bit unsigned */ miMATRIX, /* MATLAB array */ miCOMPRESSED, /* Compressed Data */ miUTF8, /* Unicode UTF-8 Encoded Character Data */ miUTF16, /* Unicode UTF-16 Encoded Character Data */ miUTF32 /* Unicode UTF-32 Encoded Character Data */ } mat5_data_type; typedef enum { mxCELL_CLASS=1, /* cell array */ mxSTRUCT_CLASS, /* structure */ mxOBJECT_CLASS, /* object */ mxCHAR_CLASS, /* character array */ mxSPARSE_CLASS, /* sparse array */ mxDOUBLE_CLASS, /* double precision array */ mxSINGLE_CLASS, /* single precision floating point */ mxINT8_CLASS, /* 8 bit signed integer */ mxUINT8_CLASS, /* 8 bit unsigned integer */ mxINT16_CLASS, /* 16 bit signed integer */ mxUINT16_CLASS, /* 16 bit unsigned integer */ mxINT32_CLASS, /* 32 bit signed integer */ mxUINT32_CLASS, /* 32 bit unsigned integer */ mxINT64_CLASS, /* 64 bit signed integer */ mxUINT64_CLASS, /* 64 bit unsigned integer */ mxFUNCTION_CLASS /* Function handle */ } arrayclasstype; #define FLAG_COMPLEX 0x8 #define FLAG_GLOBAL 0x4 #define FLAG_LOGICAL 0x2 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum}; static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal, double MaxVal) { ExceptionInfo *exception; double f; int x; register PixelPacket *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; exception=(&image->exception); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q)); if (f + GetPixelRed(q) > QuantumRange) SetPixelRed(q,QuantumRange); else SetPixelRed(q,GetPixelRed(q)+(int) f); if ((int) f / 2.0 > GetPixelGreen(q)) { SetPixelGreen(q,0); SetPixelBlue(q,0); } else { SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelBlue(q)); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q)); if (f + GetPixelBlue(q) > QuantumRange) SetPixelBlue(q,QuantumRange); else SetPixelBlue(q,GetPixelBlue(q)+(int) f); if ((int) f / 2.0 > q->green) { SetPixelRed(q,0); SetPixelGreen(q,0); } else { SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelRed(q)); } } p++; q++; } if (!SyncAuthenticPixels(image,exception)) return; return; } static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal, double MaxVal) { ExceptionInfo *exception; double f; int x; register PixelPacket *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; exception=(&image->exception); q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception); if (q == (PixelPacket *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q)); if (f + GetPixelRed(q) > QuantumRange) SetPixelRed(q,QuantumRange); else SetPixelRed(q,GetPixelRed(q)+(int) f); if ((int) f / 2.0 > GetPixelGreen(q)) { SetPixelGreen(q,0); SetPixelBlue(q,0); } else { SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelBlue(q)); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q)); if (f + GetPixelBlue(q) > QuantumRange) SetPixelBlue(q,QuantumRange); else SetPixelBlue(q,GetPixelBlue(q)+(int) f); if ((int) f / 2.0 > q->green) { SetPixelGreen(q,0); SetPixelRed(q,0); } else { SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelRed(q)); } } p++; q++; } if (!SyncAuthenticPixels(image,exception)) return; return; } /************** READERS ******************/ /* This function reads one block of floats*/ static void ReadBlobFloatsLSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobFloatsMSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* This function reads one block of doubles*/ static void ReadBlobDoublesLSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobDoublesMSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* Calculate minimum and maximum from a given block of data */ static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max) { MagickOffsetType filepos; int i, x; void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); double *dblrow; float *fltrow; if (endian_indicator == LSBEndian) { ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; } else /* MI */ { ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; } filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */ for (i = 0; i < SizeY; i++) { if (CellType==miDOUBLE) { ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff); dblrow = (double *)BImgBuff; if (i == 0) { *Min = *Max = *dblrow; } for (x = 0; x < SizeX; x++) { if (*Min > *dblrow) *Min = *dblrow; if (*Max < *dblrow) *Max = *dblrow; dblrow++; } } if (CellType==miSINGLE) { ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff); fltrow = (float *)BImgBuff; if (i == 0) { *Min = *Max = *fltrow; } for (x = 0; x < (ssize_t) SizeX; x++) { if (*Min > *fltrow) *Min = *fltrow; if (*Max < *fltrow) *Max = *fltrow; fltrow++; } } } (void) SeekBlob(image, filepos, SEEK_SET); } static void FixSignedValues(PixelPacket *q, int y) { while(y-->0) { /* Please note that negative values will overflow Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255> <-1;-128> + 127+1 = <0; 127> */ SetPixelRed(q,GetPixelRed(q)+QuantumRange/2+1); SetPixelGreen(q,GetPixelGreen(q)+QuantumRange/2+1); SetPixelBlue(q,GetPixelBlue(q)+QuantumRange/2+1); q++; } } /** Fix whole row of logical/binary data. It means pack it. */ static void FixLogical(unsigned char *Buff,int ldblk) { unsigned char mask=128; unsigned char *BuffL = Buff; unsigned char val = 0; while(ldblk-->0) { if(*Buff++ != 0) val |= mask; mask >>= 1; if(mask==0) { *BuffL++ = val; val = 0; mask = 128; } } *BuffL = val; } #if defined(MAGICKCORE_ZLIB_DELEGATE) static voidpf AcquireZIPMemory(voidpf context,unsigned int items, unsigned int size) { (void) context; return((voidpf) AcquireQuantumMemory(items,size)); } static void RelinquishZIPMemory(voidpf context,voidpf memory) { (void) context; memory=RelinquishMagickMemory(memory); } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) /** This procedure decompreses an image block for a new MATLAB format. */ static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception) { Image *image2; void *CacheBlock, *DecompressBlock; z_stream zip_info; FILE *mat_file; size_t magick_size; size_t extent; int file; int status; int zip_status; if(clone_info==NULL) return NULL; if(clone_info->file) /* Close file opened from previous transaction. */ { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *)); if(CacheBlock==NULL) return NULL; DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *)); if(DecompressBlock==NULL) { RelinquishMagickMemory(CacheBlock); return NULL; } mat_file=0; file = AcquireUniqueFileResource(clone_info->filename); if (file != -1) mat_file = fdopen(file,"w"); if(!mat_file) { RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Cannot create file stream for decompressed image"); return NULL; } zip_info.zalloc=AcquireZIPMemory; zip_info.zfree=RelinquishZIPMemory; zip_info.opaque = (voidpf) NULL; zip_status = inflateInit(&zip_info); if (zip_status != Z_OK) { RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "UnableToUncompressImage","`%s'",clone_info->filename); (void) fclose(mat_file); RelinquishUniqueFileResource(clone_info->filename); return NULL; } /* zip_info.next_out = 8*4;*/ zip_info.avail_in = 0; zip_info.total_out = 0; while(Size>0 && !EOFBlob(orig)) { magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock); zip_info.next_in = (Bytef *) CacheBlock; zip_info.avail_in = (uInt) magick_size; while(zip_info.avail_in>0) { zip_info.avail_out = 4096; zip_info.next_out = (Bytef *) DecompressBlock; zip_status = inflate(&zip_info,Z_NO_FLUSH); if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END)) break; extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file); (void) extent; if(zip_status == Z_STREAM_END) goto DblBreak; } if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END)) break; Size -= magick_size; } DblBreak: inflateEnd(&zip_info); (void)fclose(mat_file); RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile; if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile; status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception); if (status == MagickFalse) { DeleteImageFromList(&image2); EraseFile: fclose(clone_info->file); clone_info->file = NULL; UnlinkFile: RelinquishUniqueFileResource(clone_info->filename); return NULL; } return image2; } #endif static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { typedef struct { unsigned char Type[4]; unsigned int nRows; unsigned int nCols; unsigned int imagf; unsigned int nameLen; } MAT4_HDR; long ldblk; EndianType endian; Image *rotate_image; MagickBooleanType status; MAT4_HDR HDR; QuantumInfo *quantum_info; QuantumFormatType format_type; register ssize_t i; ssize_t count, y; unsigned char *pixels; unsigned int depth; (void) SeekBlob(image,0,SEEK_SET); while (EOFBlob(image) != MagickFalse) { /* Object parser. */ ldblk=ReadBlobLSBLong(image); if (EOFBlob(image) != MagickFalse) break; if ((ldblk > 9999) || (ldblk < 0)) break; HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */ HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */ HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */ HDR.Type[0]=ldblk; /* M digit */ if (HDR.Type[3] != 0) break; /* Data format */ if (HDR.Type[2] != 0) break; /* Always 0 */ if (HDR.Type[0] == 0) { HDR.nRows=ReadBlobLSBLong(image); HDR.nCols=ReadBlobLSBLong(image); HDR.imagf=ReadBlobLSBLong(image); HDR.nameLen=ReadBlobLSBLong(image); endian=LSBEndian; } else { HDR.nRows=ReadBlobMSBLong(image); HDR.nCols=ReadBlobMSBLong(image); HDR.imagf=ReadBlobMSBLong(image); HDR.nameLen=ReadBlobMSBLong(image); endian=MSBEndian; } if ((HDR.imagf !=0) && (HDR.imagf !=1)) break; if (HDR.nameLen > 0xFFFF) break; for (i=0; i < (ssize_t) HDR.nameLen; i++) { int byte; /* Skip matrix name. */ byte=ReadBlobByte(image); if (byte == EOF) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } image->columns=(size_t) HDR.nRows; image->rows=(size_t) HDR.nCols; SetImageColorspace(image,GRAYColorspace); if (image_info->ping != MagickFalse) { Swap(image->columns,image->rows); return(image); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) return((Image *) NULL); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return((Image *) NULL); switch(HDR.Type[1]) { case 0: format_type=FloatingPointQuantumFormat; depth=64; break; case 1: format_type=FloatingPointQuantumFormat; depth=32; break; case 2: format_type=UnsignedQuantumFormat; depth=16; break; case 3: format_type=SignedQuantumFormat; depth=16; break; case 4: format_type=UnsignedQuantumFormat; depth=8; break; default: format_type=UnsignedQuantumFormat; depth=8; break; } image->depth=depth; if (HDR.Type[0] != 0) SetQuantumEndian(image,quantum_info,MSBEndian); status=SetQuantumFormat(image,quantum_info,format_type); status=SetQuantumDepth(image,quantum_info,depth); status=SetQuantumEndian(image,quantum_info,endian); SetQuantumScale(quantum_info,1.0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; count=ReadBlob(image,depth/8*image->columns,(unsigned char *) pixels); if (count == -1) break; q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3)) FixSignedValues(q,image->columns); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (HDR.imagf == 1) for (y=0; y < (ssize_t) image->rows; y++) { /* Read complex pixels. */ count=ReadBlob(image,depth/8*image->columns,(unsigned char *) pixels); if (count == -1) break; if (HDR.Type[1] == 0) InsertComplexDoubleRow((double *) pixels,y,image,0,0); else InsertComplexFloatRow((float *) pixels,y,image,0,0); } quantum_info=DestroyQuantumInfo(quantum_info); rotate_image=RotateImage(image,90.0,exception); if (rotate_image != (Image *) NULL) { image=DestroyImage(image); image=rotate_image; } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d M A T L A B i m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMATImage() reads an MAT X image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadMATImage method is: % % Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadMATImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; PixelPacket *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; size_t Unknown6; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ quantum_info=(QuantumInfo *) NULL; image = AcquireImage(image_info); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0) { image2=ReadMATImageV4(image_info,image,exception); if (image2 == NULL) goto MATLAB_KO; image=image2; goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ Unknown6 = ReadBlobXXXLong(image2); (void) Unknown6; if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); if (Frames == 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { SetImageColorspace(image,GRAYColorspace); image->type=GrayscaleType; } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double)); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (PixelPacket *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if(image2!=NULL) if(image2!=image) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) unlink(clone_info->filename); } } } } RelinquishMagickMemory(BImgBuff); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); END_OF_READING: clone_info=DestroyImageInfo(clone_info); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method RegisterMATImage adds attributes for the MAT image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterMATImage method is: % % size_t RegisterMATImage(void) % */ ModuleExport size_t RegisterMATImage(void) { MagickInfo *entry; entry=SetMagickInfo("MAT"); entry->decoder=(DecodeImageHandler *) ReadMATImage; entry->encoder=(EncodeImageHandler *) WriteMATImage; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=AcquireString("MATLAB level 5 image format"); entry->module=AcquireString("MAT"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method UnregisterMATImage removes format registrations made by the % MAT module from the list of supported formats. % % The format of the UnregisterMATImage method is: % % UnregisterMATImage(void) % */ ModuleExport void UnregisterMATImage(void) { (void) UnregisterMagickInfo("MAT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M A T L A B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function WriteMATImage writes an Matlab matrix to a file. % % The format of the WriteMATImage method is: % % unsigned int WriteMATImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o status: Function WriteMATImage return True if the image is written. % False is returned is there is a memory shortage or if the image file % fails to write. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o image: A pointer to an Image structure. % */ static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image) { ExceptionInfo *exception; ssize_t y; unsigned z; const PixelPacket *p; unsigned int status; int logging; size_t DataSize; char padding; char MATLAB_HDR[0x80]; time_t current_time; struct tm local_time; unsigned char *pixels; int is_gray; MagickOffsetType scene; QuantumInfo *quantum_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT"); (void) logging; status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(MagickFalse); image->depth=8; current_time=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&current_time,&local_time); #else (void) memcpy(&local_time,localtime(&current_time),sizeof(local_time)); #endif (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124)); FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR), "MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d", OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon], local_time.tm_mday,local_time.tm_hour,local_time.tm_min, local_time.tm_sec,local_time.tm_year+1900); MATLAB_HDR[0x7C]=0; MATLAB_HDR[0x7D]=1; MATLAB_HDR[0x7E]='I'; MATLAB_HDR[0x7F]='M'; (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR); scene=0; do { (void) TransformImageColorspace(image,sRGBColorspace); is_gray = SetImageGray(image,&image->exception); z = is_gray ? 0 : 3; /* Store MAT header. */ DataSize = image->rows /*Y*/ * image->columns /*X*/; if(!is_gray) DataSize *= 3 /*Z*/; padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7; (void) WriteBlobLSBLong(image, miMATRIX); (void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56)); (void) WriteBlobLSBLong(image, 0x6); /* 0x88 */ (void) WriteBlobLSBLong(image, 0x8); /* 0x8C */ (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */ (void) WriteBlobLSBLong(image, 0); (void) WriteBlobLSBLong(image, 0x5); /* 0x98 */ (void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */ (void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */ (void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */ if(!is_gray) { (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */ (void) WriteBlobLSBLong(image, 0); } (void) WriteBlobLSBShort(image, 1); /* 0xB0 */ (void) WriteBlobLSBShort(image, 1); /* 0xB2 */ (void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */ (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */ (void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */ /* Store image data. */ exception=(&image->exception); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); do { for (y=0; y < (ssize_t)image->columns; y++) { p=GetVirtualPixels(image,y,0,1,image->rows,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, z2qtype[z],pixels,exception); (void) WriteBlob(image,image->rows,pixels); } if (!SyncAuthenticPixels(image,exception)) break; } while(z-- >= 2); while(padding-->0) (void) WriteBlobByte(image,0); quantum_info=DestroyQuantumInfo(quantum_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-772/c/good_2741_0
crossvul-cpp_data_good_2567_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N GGGG % % P P NN N G % % PPPP N N N G GG % % P N NN G G % % P N N GGG % % % % % % Read/Write Portable Network Graphics Image Format % % % % Software Design % % Cristy % % Glenn Randers-Pehrson % % November 1997 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ #define IM /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/MagickCore.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_PNG_DELEGATE) /* Suppress libpng pedantic warnings that were added in * libpng-1.2.41 and libpng-1.4.0. If you are working on * migration to libpng-1.5, remove these defines and then * fix any code that generates warnings. */ /* #define PNG_DEPRECATED Use of this function is deprecated */ /* #define PNG_USE_RESULT The result of this function must be checked */ /* #define PNG_NORETURN This function does not return */ /* #define PNG_ALLOCATED The result of the function is new memory */ /* #define PNG_DEPSTRUCT Access to this struct member is deprecated */ /* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */ #define PNG_PTR_NORETURN #include "png.h" #include "zlib.h" /* ImageMagick differences */ #define first_scene scene #if PNG_LIBPNG_VER > 10011 /* Optional declarations. Define or undefine them as you like. */ /* #define PNG_DEBUG -- turning this on breaks VisualC compiling */ /* After eXIf chunk has been approved: #define eXIf_SUPPORTED */ /* Experimental; define one or both of these: #define exIf_SUPPORTED */ /* Features under construction. Define these to work on them. */ #undef MNG_OBJECT_BUFFERS #undef MNG_BASI_SUPPORTED #define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */ #define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */ #if defined(MAGICKCORE_JPEG_DELEGATE) # define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */ #endif #if !defined(RGBColorMatchExact) #define IsPNGColorEqual(color,target) \ (((color).red == (target).red) && \ ((color).green == (target).green) && \ ((color).blue == (target).blue)) #endif /* Table of recognized sRGB ICC profiles */ struct sRGB_info_struct { png_uint_32 len; png_uint_32 crc; png_byte intent; }; const struct sRGB_info_struct sRGB_info[] = { /* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */ { 3048, 0x3b8772b9UL, 0}, /* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */ { 3052, 0x427ebb21UL, 1}, /* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */ {60988, 0x306fd8aeUL, 0}, /* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */ {60960, 0xbbef7812UL, 0}, /* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */ { 3024, 0x5d5129ceUL, 1}, /* HP-Microsoft sRGB v2 perceptual */ { 3144, 0x182ea552UL, 0}, /* HP-Microsoft sRGB v2 media-relative */ { 3144, 0xf29e526dUL, 1}, /* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */ { 524, 0xd4938c39UL, 0}, /* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */ { 3212, 0x034af5a1UL, 0}, /* Not recognized */ { 0, 0x00000000UL, 0}, }; /* Macros for left-bit-replication to ensure that pixels * and PixelInfos all have the same image->depth, and for use * in PNG8 quantization. */ /* LBR01: Replicate top bit */ #define LBR01PacketRed(pixelpacket) \ (pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketGreen(pixelpacket) \ (pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketBlue(pixelpacket) \ (pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketAlpha(pixelpacket) \ (pixelpacket).alpha=(ScaleQuantumToChar((pixelpacket).alpha) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketRGB(pixelpacket) \ { \ LBR01PacketRed((pixelpacket)); \ LBR01PacketGreen((pixelpacket)); \ LBR01PacketBlue((pixelpacket)); \ } #define LBR01PacketRGBO(pixelpacket) \ { \ LBR01PacketRGB((pixelpacket)); \ LBR01PacketAlpha((pixelpacket)); \ } #define LBR01PixelRed(pixel) \ (SetPixelRed(image, \ ScaleQuantumToChar(GetPixelRed(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelGreen(pixel) \ (SetPixelGreen(image, \ ScaleQuantumToChar(GetPixelGreen(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelBlue(pixel) \ (SetPixelBlue(image, \ ScaleQuantumToChar(GetPixelBlue(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelAlpha(pixel) \ (SetPixelAlpha(image, \ ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelRGB(pixel) \ { \ LBR01PixelRed((pixel)); \ LBR01PixelGreen((pixel)); \ LBR01PixelBlue((pixel)); \ } #define LBR01PixelRGBA(pixel) \ { \ LBR01PixelRGB((pixel)); \ LBR01PixelAlpha((pixel)); \ } /* LBR02: Replicate top 2 bits */ #define LBR02PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketAlpha(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).alpha) & 0xc0; \ (pixelpacket).alpha=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketRGB(pixelpacket) \ { \ LBR02PacketRed((pixelpacket)); \ LBR02PacketGreen((pixelpacket)); \ LBR02PacketBlue((pixelpacket)); \ } #define LBR02PacketRGBO(pixelpacket) \ { \ LBR02PacketRGB((pixelpacket)); \ LBR02PacketAlpha((pixelpacket)); \ } #define LBR02PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \ & 0xc0; \ SetPixelRed(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel)); \ } #define LBR02PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\ & 0xc0; \ SetPixelGreen(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel)); \ } #define LBR02PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue(image,(pixel))) & 0xc0; \ SetPixelBlue(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel)); \ } #define LBR02PixelAlpha(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) & 0xc0; \ SetPixelAlpha(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel) ); \ } #define LBR02PixelRGB(pixel) \ { \ LBR02PixelRed((pixel)); \ LBR02PixelGreen((pixel)); \ LBR02PixelBlue((pixel)); \ } #define LBR02PixelRGBA(pixel) \ { \ LBR02PixelRGB((pixel)); \ LBR02PixelAlpha((pixel)); \ } /* LBR03: Replicate top 3 bits (only used with opaque pixels during PNG8 quantization) */ #define LBR03PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketRGB(pixelpacket) \ { \ LBR03PacketRed((pixelpacket)); \ LBR03PacketGreen((pixelpacket)); \ LBR03PacketBlue((pixelpacket)); \ } #define LBR03PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \ & 0xe0; \ SetPixelRed(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \ } #define LBR03Green(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\ & 0xe0; \ SetPixelGreen(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \ } #define LBR03Blue(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue(image,(pixel))) \ & 0xe0; \ SetPixelBlue(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \ } #define LBR03RGB(pixel) \ { \ LBR03PixelRed((pixel)); \ LBR03Green((pixel)); \ LBR03Blue((pixel)); \ } /* LBR04: Replicate top 4 bits */ #define LBR04PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \ (pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \ (pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \ (pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketAlpha(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).alpha) & 0xf0; \ (pixelpacket).alpha=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketRGB(pixelpacket) \ { \ LBR04PacketRed((pixelpacket)); \ LBR04PacketGreen((pixelpacket)); \ LBR04PacketBlue((pixelpacket)); \ } #define LBR04PacketRGBO(pixelpacket) \ { \ LBR04PacketRGB((pixelpacket)); \ LBR04PacketAlpha((pixelpacket)); \ } #define LBR04PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \ & 0xf0; \ SetPixelRed(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\ & 0xf0; \ SetPixelGreen(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue(image,(pixel))) & 0xf0; \ SetPixelBlue(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelAlpha(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) & 0xf0; \ SetPixelAlpha(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelRGB(pixel) \ { \ LBR04PixelRed((pixel)); \ LBR04PixelGreen((pixel)); \ LBR04PixelBlue((pixel)); \ } #define LBR04PixelRGBA(pixel) \ { \ LBR04PixelRGB((pixel)); \ LBR04PixelAlpha((pixel)); \ } /* Establish thread safety. setjmp/longjmp is claimed to be safe on these platforms: setjmp/longjmp is alleged to be unsafe on these platforms: */ #ifdef PNG_SETJMP_SUPPORTED # ifndef IMPNG_SETJMP_IS_THREAD_SAFE # define IMPNG_SETJMP_NOT_THREAD_SAFE # endif # ifdef IMPNG_SETJMP_NOT_THREAD_SAFE static SemaphoreInfo *ping_semaphore = (SemaphoreInfo *) NULL; # endif #endif /* This temporary until I set up malloc'ed object attributes array. Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but waste more memory. */ #define MNG_MAX_OBJECTS 256 /* If this not defined, spec is interpreted strictly. If it is defined, an attempt will be made to recover from some errors, including o global PLTE too short */ #undef MNG_LOOSE /* Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8, PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here. PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and will be enabled by default in libpng-1.2.0. */ #ifdef PNG_MNG_FEATURES_SUPPORTED # ifndef PNG_READ_EMPTY_PLTE_SUPPORTED # define PNG_READ_EMPTY_PLTE_SUPPORTED # endif # ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED # define PNG_WRITE_EMPTY_PLTE_SUPPORTED # endif #endif /* Maximum valid size_t in PNG/MNG chunks is (2^31)-1 This macro is only defined in libpng-1.0.3 and later. Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6 */ #ifndef PNG_UINT_31_MAX #define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL #endif /* Constant strings for known chunk types. If you need to add a chunk, add a string holding the name here. To make the code more portable, we use ASCII numbers like this, not characters. */ /* until registration of eXIf use exIf */ static const png_byte mng_exIf[5]={101, 120, 73, 102, (png_byte) '\0'}; /* after registration of eXIf */ static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'}; static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'}; static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'}; static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'}; static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'}; static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'}; static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'}; static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'}; static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'}; static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'}; static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'}; static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'}; static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'}; static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'}; static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'}; static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'}; static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'}; static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'}; static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'}; static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'}; static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'}; static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'}; static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'}; static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'}; static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'}; static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'}; static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'}; static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'}; static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'}; static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'}; #if defined(JNG_SUPPORTED) static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'}; static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'}; static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'}; static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'}; #endif #if 0 /* Other known chunks that are not yet supported by ImageMagick: */ static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'}; static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'}; static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'}; static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'}; static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'}; static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'}; static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'}; #endif typedef struct _MngBox { long left, right, top, bottom; } MngBox; typedef struct _MngPair { volatile long a, b; } MngPair; #ifdef MNG_OBJECT_BUFFERS typedef struct _MngBuffer { size_t height, width; Image *image; png_color plte[256]; int reference_count; unsigned char alpha_sample_depth, compression_method, color_type, concrete, filter_method, frozen, image_type, interlace_method, pixel_sample_depth, plte_length, sample_depth, viewable; } MngBuffer; #endif typedef struct _MngInfo { #ifdef MNG_OBJECT_BUFFERS MngBuffer *ob[MNG_MAX_OBJECTS]; #endif Image * image; RectangleInfo page; int adjoin, #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED bytes_in_read_buffer, found_empty_plte, #endif equal_backgrounds, equal_chrms, equal_gammas, #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) equal_palettes, #endif equal_physs, equal_srgbs, framing_mode, have_global_bkgd, have_global_chrm, have_global_gama, have_global_phys, have_global_sbit, have_global_srgb, have_saved_bkgd_index, have_write_global_chrm, have_write_global_gama, have_write_global_plte, have_write_global_srgb, need_fram, object_id, old_framing_mode, saved_bkgd_index; int new_number_colors; ssize_t image_found, loop_count[256], loop_iteration[256], scenes_found, x_off[MNG_MAX_OBJECTS], y_off[MNG_MAX_OBJECTS]; MngBox clip, frame, image_box, object_clip[MNG_MAX_OBJECTS]; unsigned char /* These flags could be combined into one byte */ exists[MNG_MAX_OBJECTS], frozen[MNG_MAX_OBJECTS], loop_active[256], invisible[MNG_MAX_OBJECTS], viewable[MNG_MAX_OBJECTS]; MagickOffsetType loop_jump[256]; png_colorp global_plte; png_color_8 global_sbit; png_byte #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED read_buffer[8], #endif global_trns[256]; float global_gamma; ChromaticityInfo global_chrm; RenderingIntent global_srgb_intent; unsigned int delay, global_plte_length, global_trns_length, global_x_pixels_per_unit, global_y_pixels_per_unit, mng_width, mng_height, ticks_per_second; MagickBooleanType need_blob; unsigned int IsPalette, global_phys_unit_type, basi_warning, clon_warning, dhdr_warning, jhdr_warning, magn_warning, past_warning, phyg_warning, phys_warning, sbit_warning, show_warning, mng_type, write_mng, write_png_colortype, write_png_depth, write_png_compression_level, write_png_compression_strategy, write_png_compression_filter, write_png8, write_png24, write_png32, write_png48, write_png64; #ifdef MNG_BASI_SUPPORTED size_t basi_width, basi_height; unsigned int basi_depth, basi_color_type, basi_compression_method, basi_filter_type, basi_interlace_method, basi_red, basi_green, basi_blue, basi_alpha, basi_viewable; #endif png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; PixelInfo mng_global_bkgd; /* Added at version 6.6.6-7 */ MagickBooleanType ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, ping_exclude_eXIf, ping_exclude_EXIF, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tRNS, ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, /* Added at version 6.8.5-7 */ ping_preserve_iCCP, /* Added at version 6.8.9-9 */ ping_exclude_tIME; } MngInfo; #endif /* VER */ /* Forward declarations. */ static MagickBooleanType WritePNGImage(const ImageInfo *,Image *,ExceptionInfo *); static MagickBooleanType WriteMNGImage(const ImageInfo *,Image *,ExceptionInfo *); #if defined(JNG_SUPPORTED) static MagickBooleanType WriteJNGImage(const ImageInfo *,Image *,ExceptionInfo *); #endif #if PNG_LIBPNG_VER > 10011 #if (MAGICKCORE_QUANTUM_DEPTH >= 16) static MagickBooleanType LosslessReduceDepthOK(Image *image,ExceptionInfo *exception) { /* Reduce bit depth if it can be reduced losslessly from 16+ to 8. * * This is true if the high byte and the next highest byte of * each sample of the image, the colormap, and the background color * are equal to each other. We check this by seeing if the samples * are unchanged when we scale them down to 8 and back up to Quantum. * * We don't use the method GetImageDepth() because it doesn't check * background and doesn't handle PseudoClass specially. */ #define QuantumToCharToQuantumEqQuantum(quantum) \ ((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum) MagickBooleanType ok_to_reduce=MagickFalse; if (image->depth >= 16) { const Quantum *p; ok_to_reduce= QuantumToCharToQuantumEqQuantum(image->background_color.red) && QuantumToCharToQuantumEqQuantum(image->background_color.green) && QuantumToCharToQuantumEqQuantum(image->background_color.blue) ? MagickTrue : MagickFalse; if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass) { int indx; for (indx=0; indx < (ssize_t) image->colors; indx++) { ok_to_reduce=( QuantumToCharToQuantumEqQuantum( image->colormap[indx].red) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].green) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].blue)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; } } if ((ok_to_reduce != MagickFalse) && (image->storage_class != PseudoClass)) { ssize_t y; register ssize_t x; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { ok_to_reduce = MagickFalse; break; } for (x=(ssize_t) image->columns-1; x >= 0; x--) { ok_to_reduce= QuantumToCharToQuantumEqQuantum(GetPixelRed(image,p)) && QuantumToCharToQuantumEqQuantum(GetPixelGreen(image,p)) && QuantumToCharToQuantumEqQuantum(GetPixelBlue(image,p)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; p+=GetPixelChannels(image); } if (x >= 0) break; } } if (ok_to_reduce != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " OK to reduce PNG bit depth to 8 without loss of info"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Not OK to reduce PNG bit depth to 8 without losing info"); } } return ok_to_reduce; } #endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */ static const char* PngColorTypeToString(const unsigned int color_type) { const char *result = "Unknown"; switch (color_type) { case PNG_COLOR_TYPE_GRAY: result = "Gray"; break; case PNG_COLOR_TYPE_GRAY_ALPHA: result = "Gray+Alpha"; break; case PNG_COLOR_TYPE_PALETTE: result = "Palette"; break; case PNG_COLOR_TYPE_RGB: result = "RGB"; break; case PNG_COLOR_TYPE_RGB_ALPHA: result = "RGB+Alpha"; break; } return result; } static int Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent) { switch (intent) { case PerceptualIntent: return 0; case RelativeIntent: return 1; case SaturationIntent: return 2; case AbsoluteIntent: return 3; default: return -1; } } static RenderingIntent Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return PerceptualIntent; case 1: return RelativeIntent; case 2: return SaturationIntent; case 3: return AbsoluteIntent; default: return UndefinedIntent; } } static const char * Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return "Perceptual Intent"; case 1: return "Relative Intent"; case 2: return "Saturation Intent"; case 3: return "Absolute Intent"; default: return "Undefined Intent"; } } static const char * Magick_ColorType_from_PNG_ColorType(const int ping_colortype) { switch (ping_colortype) { case 0: return "Grayscale"; case 2: return "Truecolor"; case 3: return "Indexed"; case 4: return "GrayAlpha"; case 6: return "RGBA"; default: return "UndefinedColorType"; } } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* MAGICKCORE_PNG_DELEGATE */ /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMNG() returns MagickTrue if the image format type, identified by the % magick string, is MNG. % % The format of the IsMNG method is: % % MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJNG() returns MagickTrue if the image format type, identified by the % magick string, is JNG. % % The format of the IsJNG method is: % % MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNG() returns MagickTrue if the image format type, identified by the % magick string, is PNG. % % The format of the IsPNG method is: % % MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_PNG_DELEGATE) #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if (PNG_LIBPNG_VER > 10011) static size_t WriteBlobMSBULong(Image *image,const size_t value) { unsigned char buffer[4]; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; return((size_t) WriteBlob(image,4,buffer)); } static void PNGLong(png_bytep p,png_uint_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGsLong(png_bytep p,png_int_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGShort(png_bytep p,png_uint_16 value) { *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGType(png_bytep p,const png_byte *type) { (void) CopyMagickMemory(p,type,4*sizeof(png_byte)); } static void LogPNGChunk(MagickBooleanType logging, const png_byte *type, size_t length) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing %c%c%c%c chunk, length: %.20g", type[0],type[1],type[2],type[3],(double) length); } #endif /* PNG_LIBPNG_VER > 10011 */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNGImage() reads a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image or set of images. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadPNGImage method is: % % Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % % To do, more or less in chronological order (as of version 5.5.2, % November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage): % % Get 16-bit cheap transparency working. % % (At this point, PNG decoding is supposed to be in full MNG-LC compliance) % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % (At this point, PNG encoding should be in full MNG compliance) % % Provide options for choice of background to use when the MNG BACK % chunk is not present or is not mandatory (i.e., leave transparent, % user specified, MNG BACK, PNG bKGD) % % Implement LOOP/ENDL [done, but could do discretionary loops more % efficiently by linking in the duplicate frames.]. % % Decode and act on the MHDR simplicity profile (offer option to reject % files or attempt to process them anyway when the profile isn't LC or VLC). % % Upgrade to full MNG without Delta-PNG. % % o BACK [done a while ago except for background image ID] % o MOVE [done 15 May 1999] % o CLIP [done 15 May 1999] % o DISC [done 19 May 1999] % o SAVE [partially done 19 May 1999 (marks objects frozen)] % o SEEK [partially done 19 May 1999 (discard function only)] % o SHOW % o PAST % o BASI % o MNG-level tEXt/iTXt/zTXt % o pHYg % o pHYs % o sBIT % o bKGD % o iTXt (wait for libpng implementation). % % Use the scene signature to discover when an identical scene is % being reused, and just point to the original image->exception instead % of storing another set of pixels. This not specific to MNG % but could be applied generally. % % Upgrade to full MNG with Delta-PNG. % % JNG tEXt/iTXt/zTXt % % We will not attempt to read files containing the CgBI chunk. % They are really Xcode files meant for display on the iPhone. % These are not valid PNG files and it is impossible to recover % the original PNG from files that have been converted to Xcode-PNG, % since irretrievable loss of color data has occurred due to the % use of premultiplied alpha. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* This the function that does the actual reading of data. It is the same as the one supplied in libpng, except that it receives the datastream from the ReadBlob() function instead of standard input. */ static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) ReadBlob(image,(size_t) length,data); if (check != length) { char msg[MagickPathExtent]; (void) FormatLocaleString(msg,MagickPathExtent, "Expected %.20g bytes; found %.20g bytes",(double) length, (double) check); png_warning(png_ptr,msg); png_error(png_ptr,"Read Exception"); } } } #if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \ !defined(PNG_MNG_FEATURES_SUPPORTED) /* We use mng_get_data() instead of png_get_data() if we have a libpng * older than libpng-1.0.3a, which was the first to allow the empty * PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was * ifdef'ed out. Earlier versions would crash if the bKGD chunk was * encountered after an empty PLTE, so we have to look ahead for bKGD * chunks and remove them from the datastream that is passed to libpng, * and store their contents for later use. */ static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { MngInfo *mng_info; Image *image; png_size_t check; register ssize_t i; i=0; mng_info=(MngInfo *) png_get_io_ptr(png_ptr); image=(Image *) mng_info->image; while (mng_info->bytes_in_read_buffer && length) { data[i]=mng_info->read_buffer[i]; mng_info->bytes_in_read_buffer--; length--; i++; } if (length != 0) { check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data); if (check != length) png_error(png_ptr,"Read Exception"); if (length == 4) { if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 0)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0) mng_info->found_empty_plte=MagickTrue; if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0) { mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; } } if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 1)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0) if (mng_info->found_empty_plte) { /* Skip the bKGD data byte and CRC. */ check=(png_size_t) ReadBlob(image,5,(char *) mng_info->read_buffer); check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->saved_bkgd_index=mng_info->read_buffer[0]; mng_info->have_saved_bkgd_index=MagickTrue; mng_info->bytes_in_read_buffer=0; } } } } } #endif static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) WriteBlob(image,(size_t) length,data); if (check != length) png_error(png_ptr,"WriteBlob Failed"); } } static void png_flush_data(png_structp png_ptr) { (void) png_ptr; } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED static int PalettesAreEqual(Image *a,Image *b) { ssize_t i; if ((a == (Image *) NULL) || (b == (Image *) NULL)) return((int) MagickFalse); if (a->storage_class != PseudoClass || b->storage_class != PseudoClass) return((int) MagickFalse); if (a->colors != b->colors) return((int) MagickFalse); for (i=0; i < (ssize_t) a->colors; i++) { if ((a->colormap[i].red != b->colormap[i].red) || (a->colormap[i].green != b->colormap[i].green) || (a->colormap[i].blue != b->colormap[i].blue)) return((int) MagickFalse); } return((int) MagickTrue); } #endif static void MngInfoDiscardObject(MngInfo *mng_info,int i) { if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) && mng_info->exists[i] && !mng_info->frozen[i]) { #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) { if (mng_info->ob[i]->reference_count > 0) mng_info->ob[i]->reference_count--; if (mng_info->ob[i]->reference_count == 0) { if (mng_info->ob[i]->image != (Image *) NULL) mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image); mng_info->ob[i]=DestroyString(mng_info->ob[i]); } } mng_info->ob[i]=(MngBuffer *) NULL; #endif mng_info->exists[i]=MagickFalse; mng_info->invisible[i]=MagickFalse; mng_info->viewable[i]=MagickFalse; mng_info->frozen[i]=MagickFalse; mng_info->x_off[i]=0; mng_info->y_off[i]=0; mng_info->object_clip[i].left=0; mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].top=0; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } } static MngInfo *MngInfoFreeStruct(MngInfo *mng_info) { register ssize_t i; if (mng_info == (MngInfo *) NULL) return((MngInfo *) NULL); for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); if (mng_info->global_plte != (png_colorp) NULL) mng_info->global_plte=(png_colorp) RelinquishMagickMemory(mng_info->global_plte); return((MngInfo *) RelinquishMagickMemory(mng_info)); } static MngBox mng_minimum_box(MngBox box1,MngBox box2) { MngBox box; box=box1; if (box.left < box2.left) box.left=box2.left; if (box.top < box2.top) box.top=box2.top; if (box.right > box2.right) box.right=box2.right; if (box.bottom > box2.bottom) box.bottom=box2.bottom; return box; } static MngBox mng_read_box(MngBox previous_box,char delta_type, unsigned char *p) { MngBox box; /* Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk. */ box.left=(ssize_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); box.right=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); box.top=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); box.bottom=(ssize_t) ((p[12] << 24) | (p[13] << 16) | (p[14] << 8) | p[15]); if (delta_type != 0) { box.left+=previous_box.left; box.right+=previous_box.right; box.top+=previous_box.top; box.bottom+=previous_box.bottom; } return(box); } static MngPair mng_read_pair(MngPair previous_pair,int delta_type, unsigned char *p) { MngPair pair; /* Read two ssize_ts from CLON, MOVE or PAST chunk */ pair.a=(long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); pair.b=(long) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (delta_type != 0) { pair.a+=previous_pair.a; pair.b+=previous_pair.b; } return(pair); } static long mng_get_long(unsigned char *p) { return((long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3])); } typedef struct _PNGErrorInfo { Image *image; ExceptionInfo *exception; } PNGErrorInfo; static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message) { ExceptionInfo *exception; Image *image; PNGErrorInfo *error_info; error_info=(PNGErrorInfo *) png_get_error_ptr(ping); image=error_info->image; exception=error_info->exception; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s error: %s", png_get_libpng_ver(NULL),message); (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message, "`%s'",image->filename); #if (PNG_LIBPNG_VER < 10500) /* A warning about deprecated use of jmpbuf here is unavoidable if you * are building with libpng-1.4.x and can be ignored. */ longjmp(ping->jmpbuf,1); #else png_longjmp(ping,1); #endif } static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message) { ExceptionInfo *exception; Image *image; PNGErrorInfo *error_info; if (LocaleCompare(message, "Missing PLTE before tRNS") == 0) png_error(ping, message); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); image=error_info->image; exception=error_info->exception; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s warning: %s", png_get_libpng_ver(NULL),message); (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'",image->filename); } #ifdef PNG_USER_MEM_SUPPORTED #if PNG_LIBPNG_VER >= 10400 static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size) #else static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size) #endif { (void) png_ptr; return((png_voidp) AcquireMagickMemory((size_t) size)); } /* Free a pointer. It is removed from the list at the same time. */ static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr) { (void) png_ptr; ptr=RelinquishMagickMemory(ptr); return((png_free_ptr) NULL); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static int Magick_png_read_raw_profile(png_struct *ping,Image *image, const ImageInfo *image_info, png_textp text,int ii,ExceptionInfo *exception) { register ssize_t i; register unsigned char *dp; register png_charp sp; png_uint_32 length, nibbles; StringInfo *profile; const unsigned char unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12, 13,14,15}; sp=text[ii].text+1; /* look for newline */ while (*sp != '\n') sp++; /* look for length */ while (*sp == '\0' || *sp == ' ' || *sp == '\n') sp++; length=(png_uint_32) StringToLong(sp); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu",(unsigned long) length); while (*sp != ' ' && *sp != '\n') sp++; /* allocate space */ if (length == 0) { png_warning(ping,"invalid profile length"); return(MagickFalse); } profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { png_warning(ping, "unable to copy profile"); return(MagickFalse); } /* copy profile, skipping white space and column 1 "=" signs */ dp=GetStringInfoDatum(profile); nibbles=length*2; for (i=0; i < (ssize_t) nibbles; i++) { while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f') { if (*sp == '\0') { png_warning(ping, "ran out of profile data"); profile=DestroyStringInfo(profile); return(MagickFalse); } sp++; } if (i%2 == 0) *dp=(unsigned char) (16*unhex[(int) *sp++]); else (*dp++)+=unhex[(int) *sp++]; } /* We have already read "Raw profile type. */ (void) SetImageProfile(image,&text[ii].key[17],profile,exception); profile=DestroyStringInfo(profile); if (image_info->verbose) (void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]); return MagickTrue; } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk) { Image *image; /* The unknown chunk structure contains the chunk data: png_byte name[5]; png_byte *data; png_size_t size; Note that libpng has already taken care of the CRC handling. Returns one of the following: return(-n); chunk had an error return(0); did not recognize return(n); success */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read_user_chunk: found %c%c%c%c chunk", chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]); if (chunk->name[0] == 101 && (chunk->name[1] == 88 || chunk->name[1] == 120 ) && chunk->name[2] == 73 && chunk-> name[3] == 102) { /* process eXIf or exIf chunk */ PNGErrorInfo *error_info; StringInfo *profile; unsigned char *p; png_byte *s; size_t i; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " recognized eXIf|exIf chunk"); image=(Image *) png_get_user_chunk_ptr(ping); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); profile=BlobToStringInfo((const void *) NULL,chunk->size+6); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(error_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); return(-1); } p=GetStringInfoDatum(profile); if (*p != 'E') { /* Initialize profile with "Exif\0\0" if it is not already present by accident */ *p++ ='E'; *p++ ='x'; *p++ ='i'; *p++ ='f'; *p++ ='\0'; *p++ ='\0'; } else { if (p[1] != 'x' || p[2] != 'i' || p[3] != 'f' || p[4] != '\0' || p[5] != '\0') { /* Chunk is malformed */ profile=DestroyStringInfo(profile); return(-1); } } /* copy chunk->data to profile */ s=chunk->data; for (i=0; i<chunk->size; i++) *p++ = *s++; error_info=(PNGErrorInfo *) png_get_error_ptr(ping); (void) SetImageProfile(image,"exif",profile, error_info->exception); profile=DestroyStringInfo(profile); return(1); } /* vpAg (deprecated, replaced by caNv) */ if (chunk->name[0] == 118 && chunk->name[1] == 112 && chunk->name[2] == 65 && chunk->name[3] == 103) { /* recognized vpAg */ if (chunk->size != 9) return(-1); /* Error return */ if (chunk->data[8] != 0) return(0); /* ImageMagick requires pixel units */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); return(1); } /* caNv */ if (chunk->name[0] == 99 && chunk->name[1] == 97 && chunk->name[2] == 78 && chunk->name[3] == 118) { /* recognized caNv */ if (chunk->size != 16) return(-1); /* Error return */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); image->page.x=(size_t) ((chunk->data[8] << 24) | (chunk->data[9] << 16) | (chunk->data[10] << 8) | chunk->data[11]); image->page.y=(size_t) ((chunk->data[12] << 24) | (chunk->data[13] << 16) | (chunk->data[14] << 8) | chunk->data[15]); return(1); } return(0); /* Did not recognize */ } #endif /* PNG_UNKNOWN_CHUNKS_SUPPORTED */ #if defined(PNG_tIME_SUPPORTED) static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info, ExceptionInfo *exception) { png_timep time; if (png_get_tIME(ping,info,&time)) { char timestamp[21]; FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ", time->year,time->month,time->day,time->hour,time->minute,time->second); SetImageProperty(image,"png:tIME",timestamp,exception); } } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the ReadOnePNGImage method is: % % Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { /* Read one PNG image */ /* To do: Read the tEXt/Creation Time chunk into the date:create property */ Image *image; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; int intent, /* "PNG Rendering intent", which is ICC intent + 1 */ num_raw_profiles, num_text, num_text_total, num_passes, number_colors, pass, ping_bit_depth, ping_color_type, ping_file_depth, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans, unit_type; double file_gamma; MagickBooleanType logging, ping_found_cHRM, ping_found_gAMA, ping_found_iCCP, ping_found_sRGB, ping_found_sRGB_cHRM, ping_preserve_iCCP, status; MemoryInfo *volatile pixel_info; PixelInfo transparent_color; PNGErrorInfo error_info; png_bytep ping_trans_alpha; png_color_16p ping_background, ping_trans_color; png_info *end_info, *ping_info; png_struct *ping; png_textp text; png_uint_32 ping_height, ping_width, x_resolution, y_resolution; QuantumInfo *quantum_info; ssize_t ping_rowbytes, y; register unsigned char *p; register ssize_t i, x; register Quantum *q; size_t length, row_offset; ssize_t j; unsigned char *ping_pixels; #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED png_byte unused_chunks[]= { 104, 73, 83, 84, (png_byte) '\0', /* hIST */ 105, 84, 88, 116, (png_byte) '\0', /* iTXt */ 112, 67, 65, 76, (png_byte) '\0', /* pCAL */ 115, 67, 65, 76, (png_byte) '\0', /* sCAL */ 115, 80, 76, 84, (png_byte) '\0', /* sPLT */ #if !defined(PNG_tIME_SUPPORTED) 116, 73, 77, 69, (png_byte) '\0', /* tIME */ #endif #ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */ /* ignore the APNG chunks */ 97, 99, 84, 76, (png_byte) '\0', /* acTL */ 102, 99, 84, 76, (png_byte) '\0', /* fcTL */ 102, 100, 65, 84, (png_byte) '\0', /* fdAT */ #endif }; #endif /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,32); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,32); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOnePNGImage()\n" " IM version = %s\n" " Libpng version = %s", im_vers, libpng_vers); if (logging != MagickFalse) { if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif #if (PNG_LIBPNG_VER >= 10400) # ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */ if (image_info->verbose) { printf("Your PNG library (libpng-%s) is an old beta version.\n", PNG_LIBPNG_VER_STRING); printf("Please update it.\n"); } # endif #endif quantum_info = (QuantumInfo *) NULL; image=mng_info->image; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before reading:\n" " image->alpha_trait=%d" " image->rendering_intent=%d\n" " image->colorspace=%d\n" " image->gamma=%f", (int) image->alpha_trait, (int) image->rendering_intent, (int) image->colorspace, image->gamma); } intent= Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent); /* Set to an out-of-range color unless tRNS chunk is present */ transparent_color.red=65537; transparent_color.green=65537; transparent_color.blue=65537; transparent_color.alpha=65537; number_colors=0; num_text = 0; num_text_total = 0; num_raw_profiles = 0; ping_found_cHRM = MagickFalse; ping_found_gAMA = MagickFalse; ping_found_iCCP = MagickFalse; ping_found_sRGB = MagickFalse; ping_found_sRGB_cHRM = MagickFalse; ping_preserve_iCCP = MagickFalse; /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler, NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } end_info=png_create_info_struct(ping); if (end_info == (png_info *) NULL) { png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG image is corrupt. */ printf(" destroy_read_struct\n"); png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() with error."); return(GetFirstImageInList(image)); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for reading. */ mng_info->image_found++; png_set_sig_bytes(ping,8); if (LocaleCompare(image_info->magick,"MNG") == 0) { #if defined(PNG_MNG_FEATURES_SUPPORTED) (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); png_set_read_fn(ping,image,png_get_data); #else #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) png_permit_empty_plte(ping,MagickTrue); png_set_read_fn(ping,image,png_get_data); #else mng_info->image=image; mng_info->bytes_in_read_buffer=0; mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; png_set_read_fn(ping,mng_info,mng_get_data); #endif #endif } else png_set_read_fn(ping,image,png_get_data); { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",value) == MagickFalse) { value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) ping_preserve_iCCP=MagickTrue; #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) /* Don't let libpng check for ICC/sRGB profile because we're going * to do that anyway. This feature was added at libpng-1.6.12. * If logging, go ahead and check and issue a warning as appropriate. */ if (logging == MagickFalse) png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) else { png_set_keep_unknown_chunks(ping, 1, (png_bytep) mng_iCCP, 1); } #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* Ignore unused chunks and all unknown chunks except for eXIf, caNv, and vpAg */ # if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */ png_set_keep_unknown_chunks(ping, 2, NULL, 0); # else png_set_keep_unknown_chunks(ping, 1, NULL, 0); # endif png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_eXIf, 1); png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_caNv, 1); png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_vpAg, 1); png_set_keep_unknown_chunks(ping, 1, unused_chunks, (int)sizeof(unused_chunks)/5); /* Callback for other unknown chunks */ png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED # if (PNG_LIBPNG_VER >= 10400) /* Limit the size of the chunk storage cache used for sPLT, text, * and unknown chunks. */ png_set_chunk_cache_max(ping, 32767); # endif #endif #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature */ png_set_check_for_invalid_index (ping, 0); #endif #if (PNG_LIBPNG_VER < 10400) # if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \ (PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__) /* Disable thread-unsafe features of pnggccrd */ if (png_access_version_number() >= 10200) { png_uint_32 mmx_disable_mask=0; png_uint_32 asm_flags; mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \ | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \ | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \ | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ); asm_flags=png_get_asm_flags(ping); png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask); } # endif #endif png_read_info(ping,ping_info); png_get_IHDR(ping,ping_info,&ping_width,&ping_height, &ping_bit_depth,&ping_color_type, &ping_interlace_method,&ping_compression_method, &ping_filter_method); ping_file_depth = ping_bit_depth; /* Swap bytes if requested */ if (ping_file_depth == 16) { const char *value; value=GetImageOption(image_info,"png:swap-bytes"); if (value == NULL) value=GetImageArtifact(image,"png:swap-bytes"); if (value != NULL) png_set_swap(ping); } /* Save bit-depth and color-type in case we later want to write a PNG00 */ { char msg[MagickPathExtent]; (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) ping_color_type); (void) SetImageProperty(image,"png:IHDR.color-type-orig",msg,exception); (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) ping_bit_depth); (void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg,exception); } (void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans, &ping_trans_color); (void) png_get_bKGD(ping, ping_info, &ping_background); if (ping_bit_depth < 8) { png_set_packing(ping); ping_bit_depth = 8; } image->depth=ping_bit_depth; image->depth=GetImageQuantumDepth(image,MagickFalse); image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { image->rendering_intent=UndefinedIntent; intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent); (void) ResetMagickMemory(&image->chromaticity,0, sizeof(image->chromaticity)); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG width: %.20g, height: %.20g\n" " PNG color_type: %d, bit_depth: %d\n" " PNG compression_method: %d\n" " PNG interlace_method: %d, filter_method: %d", (double) ping_width, (double) ping_height, ping_color_type, ping_bit_depth, ping_compression_method, ping_interlace_method,ping_filter_method); } if (png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_gAMA)) { ping_found_gAMA=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG gAMA chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { ping_found_cHRM=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG cHRM chunk."); } if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { ping_found_sRGB=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG sRGB chunk."); } #ifdef PNG_READ_iCCP_SUPPORTED if (ping_found_iCCP !=MagickTrue && ping_found_sRGB != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_iCCP)) { int compression; #if (PNG_LIBPNG_VER < 10500) png_charp info; #else png_bytep info; #endif png_charp name; png_uint_32 profile_length; (void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info, &profile_length); if (profile_length != 0) { StringInfo *profile; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG iCCP chunk."); profile=BlobToStringInfo(info,profile_length); if (profile == (StringInfo *) NULL) { png_warning(ping, "ICC profile is NULL"); profile=DestroyStringInfo(profile); } else { if (ping_preserve_iCCP == MagickFalse) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } break; } } } if (sRGB_info[icheck].len == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); (void) SetImageProfile(image,"icc",profile,exception); } } else /* Preserve-iCCP */ { (void) SetImageProfile(image,"icc",profile,exception); } profile=DestroyStringInfo(profile); } } } #endif #if defined(PNG_READ_sRGB_SUPPORTED) { if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { if (png_get_sRGB(ping,ping_info,&intent)) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (intent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG sRGB chunk: rendering_intent: %d",intent); } } else if (mng_info->have_global_srgb) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (mng_info->global_srgb_intent); } } #endif { if (!png_get_gAMA(ping,ping_info,&file_gamma)) if (mng_info->have_global_gama) png_set_gAMA(ping,ping_info,mng_info->global_gamma); if (png_get_gAMA(ping,ping_info,&file_gamma)) { image->gamma=(float) file_gamma; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG gAMA chunk: gamma: %f",file_gamma); } } if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { if (mng_info->have_global_chrm != MagickFalse) { (void) png_set_cHRM(ping,ping_info, mng_info->global_chrm.white_point.x, mng_info->global_chrm.white_point.y, mng_info->global_chrm.red_primary.x, mng_info->global_chrm.red_primary.y, mng_info->global_chrm.green_primary.x, mng_info->global_chrm.green_primary.y, mng_info->global_chrm.blue_primary.x, mng_info->global_chrm.blue_primary.y); } } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { (void) png_get_cHRM(ping,ping_info, &image->chromaticity.white_point.x, &image->chromaticity.white_point.y, &image->chromaticity.red_primary.x, &image->chromaticity.red_primary.y, &image->chromaticity.green_primary.x, &image->chromaticity.green_primary.y, &image->chromaticity.blue_primary.x, &image->chromaticity.blue_primary.y); ping_found_cHRM=MagickTrue; if (image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f) ping_found_sRGB_cHRM=MagickTrue; } if (image->rendering_intent != UndefinedIntent) { if (ping_found_sRGB != MagickTrue && (ping_found_gAMA != MagickTrue || (image->gamma > .45 && image->gamma < .46)) && (ping_found_cHRM != MagickTrue || ping_found_sRGB_cHRM != MagickFalse) && ping_found_iCCP != MagickTrue) { png_set_sRGB(ping,ping_info, Magick_RenderingIntent_to_PNG_RenderingIntent (image->rendering_intent)); file_gamma=1.000f/2.200f; ping_found_sRGB=MagickTrue; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting sRGB as if in input"); } } #if defined(PNG_oFFs_SUPPORTED) if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info); image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info); if (logging != MagickFalse) if (image->page.x || image->page.y) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double) image->page.x,(double) image->page.y); } #endif #if defined(PNG_pHYs_SUPPORTED) if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { if (mng_info->have_global_phys) { png_set_pHYs(ping,ping_info, mng_info->global_x_pixels_per_unit, mng_info->global_y_pixels_per_unit, mng_info->global_phys_unit_type); } } x_resolution=0; y_resolution=0; unit_type=0; if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { /* Set image resolution. */ (void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution, &unit_type); image->resolution.x=(double) x_resolution; image->resolution.y=(double) y_resolution; if (unit_type == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->resolution.x=(double) x_resolution/100.0; image->resolution.y=(double) y_resolution/100.0; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) x_resolution,(double) y_resolution,unit_type); } #endif if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); if ((number_colors == 0) && ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)) { if (mng_info->global_plte_length) { png_set_PLTE(ping,ping_info,mng_info->global_plte, (int) mng_info->global_plte_length); if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { if (mng_info->global_trns_length) { png_warning(ping, "global tRNS has more entries than global PLTE"); } else { png_set_tRNS(ping,ping_info,mng_info->global_trns, (int) mng_info->global_trns_length,NULL); } } #ifdef PNG_READ_bKGD_SUPPORTED if ( #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED mng_info->have_saved_bkgd_index || #endif png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { png_color_16 background; #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED if (mng_info->have_saved_bkgd_index) background.index=mng_info->saved_bkgd_index; #endif if (png_get_valid(ping, ping_info, PNG_INFO_bKGD)) background.index=ping_background->index; background.red=(png_uint_16) mng_info->global_plte[background.index].red; background.green=(png_uint_16) mng_info->global_plte[background.index].green; background.blue=(png_uint_16) mng_info->global_plte[background.index].blue; background.gray=(png_uint_16) mng_info->global_plte[background.index].green; png_set_bKGD(ping,ping_info,&background); } #endif } else png_error(ping,"No global PLTE in file"); } } #ifdef PNG_READ_bKGD_SUPPORTED if (mng_info->have_global_bkgd && (!png_get_valid(ping,ping_info,PNG_INFO_bKGD))) image->background_color=mng_info->mng_global_bkgd; if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { unsigned int bkgd_scale; /* Set image background color. * Scale background components to 16-bit, then scale * to quantum depth */ bkgd_scale = 1; if (ping_file_depth == 1) bkgd_scale = 255; else if (ping_file_depth == 2) bkgd_scale = 85; else if (ping_file_depth == 4) bkgd_scale = 17; if (ping_file_depth <= 8) bkgd_scale *= 257; ping_background->red *= bkgd_scale; ping_background->green *= bkgd_scale; ping_background->blue *= bkgd_scale; if (logging != MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d)\n" " bkgd_scale=%d. ping_background=(%d,%d,%d)", ping_background->red,ping_background->green, ping_background->blue, bkgd_scale,ping_background->red, ping_background->green,ping_background->blue); } image->background_color.red= ScaleShortToQuantum(ping_background->red); image->background_color.green= ScaleShortToQuantum(ping_background->green); image->background_color.blue= ScaleShortToQuantum(ping_background->blue); image->background_color.alpha=OpaqueAlpha; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->background_color=(%.20g,%.20g,%.20g).", (double) image->background_color.red, (double) image->background_color.green, (double) image->background_color.blue); } #endif /* PNG_READ_bKGD_SUPPORTED */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { /* Image has a tRNS chunk. */ int max_sample; size_t one=1; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG tRNS chunk."); max_sample = (int) ((one << ping_file_depth) - 1); if ((ping_color_type == PNG_COLOR_TYPE_GRAY && (int)ping_trans_color->gray > max_sample) || (ping_color_type == PNG_COLOR_TYPE_RGB && ((int)ping_trans_color->red > max_sample || (int)ping_trans_color->green > max_sample || (int)ping_trans_color->blue > max_sample))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Ignoring PNG tRNS chunk with out-of-range sample."); png_free_data(ping, ping_info, PNG_FREE_TRNS, 0); png_set_invalid(ping,ping_info,PNG_INFO_tRNS); image->alpha_trait=UndefinedPixelTrait; } else { int scale_to_short; scale_to_short = 65535L/((1UL << ping_file_depth)-1); /* Scale transparent_color to short */ transparent_color.red= scale_to_short*ping_trans_color->red; transparent_color.green= scale_to_short*ping_trans_color->green; transparent_color.blue= scale_to_short*ping_trans_color->blue; transparent_color.alpha= scale_to_short*ping_trans_color->gray; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Raw tRNS graylevel = %d, scaled graylevel = %d.", (int) ping_trans_color->gray,(int) transparent_color.alpha); } transparent_color.red=transparent_color.alpha; transparent_color.green=transparent_color.alpha; transparent_color.blue=transparent_color.alpha; } } } #if defined(PNG_READ_sBIT_SUPPORTED) if (mng_info->have_global_sbit) { if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT)) png_set_sBIT(ping,ping_info,&mng_info->global_sbit); } #endif num_passes=png_set_interlace_handling(ping); png_read_update_info(ping,ping_info); ping_rowbytes=png_get_rowbytes(ping,ping_info); /* Initialize image structure. */ mng_info->image_box.left=0; mng_info->image_box.right=(ssize_t) ping_width; mng_info->image_box.top=0; mng_info->image_box.bottom=(ssize_t) ping_height; if (mng_info->mng_type == 0) { mng_info->mng_width=ping_width; mng_info->mng_height=ping_height; mng_info->frame=mng_info->image_box; mng_info->clip=mng_info->image_box; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } image->compression=ZipCompression; image->columns=ping_width; image->rows=ping_height; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { double image_gamma = image->gamma; (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%f",(float) image_gamma); if (image_gamma > 0.75) { /* Set image->rendering_intent to Undefined, * image->colorspace to GRAY, and reset image->chromaticity. */ image->intensity = Rec709LuminancePixelIntensityMethod; SetImageColorspace(image,GRAYColorspace,exception); } else { RenderingIntent save_rendering_intent = image->rendering_intent; ChromaticityInfo save_chromaticity = image->chromaticity; SetImageColorspace(image,GRAYColorspace,exception); image->rendering_intent = save_rendering_intent; image->chromaticity = save_chromaticity; } image->gamma = image_gamma; } (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace=%d",(int) image->colorspace); if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || ((int) ping_bit_depth < 16 && (int) ping_color_type == PNG_COLOR_TYPE_GRAY)) { size_t one; image->storage_class=PseudoClass; one=1; image->colors=one << ping_file_depth; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->colors > 256) image->colors=256; #else if (image->colors > 65536L) image->colors=65536L; #endif if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); image->colors=(size_t) number_colors; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG PLTE chunk: number_colors: %d.",number_colors); } } if (image->storage_class == PseudoClass) { /* Initialize image colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) png_error(ping,"Memory allocation failed"); if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); for (i=0; i < (ssize_t) number_colors; i++) { image->colormap[i].red=ScaleCharToQuantum(palette[i].red); image->colormap[i].green=ScaleCharToQuantum(palette[i].green); image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue); } for ( ; i < (ssize_t) image->colors; i++) { image->colormap[i].red=0; image->colormap[i].green=0; image->colormap[i].blue=0; } } else { Quantum scale; scale = (Quantum) (65535.0/((1UL << ping_file_depth)-1.0)); #if (MAGICKCORE_QUANTUM_DEPTH > 16) scale = ScaleShortToQuantum(scale); #endif for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(Quantum) (i*scale); image->colormap[i].green=(Quantum) (i*scale); image->colormap[i].blue=(Quantum) (i*scale); } } } /* Set some properties for reporting by "identify" */ { char msg[MagickPathExtent]; /* encode ping_width, ping_height, ping_file_depth, ping_color_type, ping_interlace_method in value */ (void) FormatLocaleString(msg,MagickPathExtent, "%d, %d",(int) ping_width, (int) ping_height); (void) SetImageProperty(image,"png:IHDR.width,height",msg,exception); (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) ping_file_depth); (void) SetImageProperty(image,"png:IHDR.bit_depth",msg,exception); (void) FormatLocaleString(msg,MagickPathExtent,"%d (%s)", (int) ping_color_type, Magick_ColorType_from_PNG_ColorType((int)ping_color_type)); (void) SetImageProperty(image,"png:IHDR.color_type",msg,exception); if (ping_interlace_method == 0) { (void) FormatLocaleString(msg,MagickPathExtent,"%d (Not interlaced)", (int) ping_interlace_method); } else if (ping_interlace_method == 1) { (void) FormatLocaleString(msg,MagickPathExtent,"%d (Adam7 method)", (int) ping_interlace_method); } else { (void) FormatLocaleString(msg,MagickPathExtent,"%d (Unknown method)", (int) ping_interlace_method); } (void) SetImageProperty(image,"png:IHDR.interlace_method", msg,exception); if (number_colors != 0) { (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) number_colors); (void) SetImageProperty(image,"png:PLTE.number_colors",msg, exception); } } #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,ping_info,exception); #endif /* Read image scanlines. */ if (image->delay != 0) mng_info->scenes_found++; if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || ( (image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)))) { /* This happens later in non-ping decodes */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) image->storage_class=DirectClass; image->alpha_trait= (((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? BlendPixelTrait : UndefinedPixelTrait; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping PNG image data for scene %.20g",(double) mng_info->scenes_found-1); png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()."); return(image); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG IDAT chunk(s)"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (num_passes > 1) pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes* sizeof(*ping_pixels)); else pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Memory allocation failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting PNG pixels to pixel packets"); /* Convert PNG pixels to pixel packets. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Failed to allocate quantum_info"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); { MagickBooleanType found_transparent_pixel; found_transparent_pixel=MagickFalse; if (image->storage_class == DirectClass) { for (pass=0; pass < num_passes; pass++) { /* Convert image to DirectClass pixel packets. */ image->alpha_trait= (((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? BlendPixelTrait : UndefinedPixelTrait; for (y=0; y < (ssize_t) image->rows; y++) { if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayAlphaQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBAQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, IndexQuantum,ping_pixels+row_offset,exception); else /* ping_color_type == PNG_COLOR_TYPE_RGB */ (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBQuantum,ping_pixels+row_offset,exception); if (found_transparent_pixel == MagickFalse) { /* Is there a transparent pixel in the row? */ if (y== 0 && logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Looking for cheap transparent pixel"); for (x=(ssize_t) image->columns-1; x >= 0; x--) { if ((ping_color_type == PNG_COLOR_TYPE_RGBA || ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) && (GetPixelAlpha(image,q) != OpaqueAlpha)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } if ((ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_GRAY) && (ScaleQuantumToShort(GetPixelRed(image,q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(image,q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(image,q)) == transparent_color.blue)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } q+=GetPixelChannels(image); } } if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag, (MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } } } else /* image->storage_class != DirectClass */ for (pass=0; pass < num_passes; pass++) { Quantum *quantum_scanline; register Quantum *r; /* Convert grayscale image to PseudoClass pixel packets. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting grayscale pixels to pixel packets"); image->alpha_trait=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ? BlendPixelTrait : UndefinedPixelTrait; quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns, (image->alpha_trait == BlendPixelTrait? 2 : 1)* sizeof(*quantum_scanline)); if (quantum_scanline == (Quantum *) NULL) png_error(ping,"Memory allocation failed"); for (y=0; y < (ssize_t) image->rows; y++) { Quantum alpha; if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=ping_pixels+row_offset; r=quantum_scanline; switch (ping_bit_depth) { case 8: { if (ping_color_type == 4) for (x=(ssize_t) image->columns-1; x >= 0; x--) { *r++=*p++; alpha=ScaleCharToQuantum((unsigned char)*p++); SetPixelAlpha(image,alpha,q); if (alpha != OpaqueAlpha) found_transparent_pixel = MagickTrue; q+=GetPixelChannels(image); } else for (x=(ssize_t) image->columns-1; x >= 0; x--) *r++=*p++; break; } case 16: { for (x=(ssize_t) image->columns-1; x >= 0; x--) { #if (MAGICKCORE_QUANTUM_DEPTH >= 16) unsigned short quantum; if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); *r=ScaleShortToQuantum(quantum); r++; if (ping_color_type == 4) { if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); alpha=ScaleShortToQuantum(quantum); SetPixelAlpha(image,alpha,q); if (alpha != OpaqueAlpha) found_transparent_pixel = MagickTrue; q+=GetPixelChannels(image); } #else /* MAGICKCORE_QUANTUM_DEPTH == 8 */ *r++=(*p++); p++; /* strip low byte */ if (ping_color_type == 4) { SetPixelAlpha(image,*p++,q); if (GetPixelAlpha(image,q) != OpaqueAlpha) found_transparent_pixel = MagickTrue; p++; q+=GetPixelChannels(image); } #endif } break; } default: break; } /* Transfer image scanline. */ r=quantum_scanline; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*r++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline); } image->alpha_trait=found_transparent_pixel ? BlendPixelTrait : UndefinedPixelTrait; if (logging != MagickFalse) { if (found_transparent_pixel != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found transparent pixel"); else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No transparent pixel was found"); ping_color_type&=0x03; } } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->storage_class == PseudoClass) { PixelTrait alpha_trait; alpha_trait=image->alpha_trait; image->alpha_trait=UndefinedPixelTrait; (void) SyncImage(image,exception); image->alpha_trait=alpha_trait; } png_read_end(ping,end_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=%d\n",(int) image->storage_class); } if (image_info->number_scenes != 0 && mng_info->scenes_found-1 < (ssize_t) image_info->first_scene && image->delay != 0) { png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); image->colors=2; (void) SetImageBackgroundColor(image,exception); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() early."); return(image); } if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { ClassType storage_class; /* Image has a transparent background. */ storage_class=image->storage_class; image->alpha_trait=BlendPixelTrait; /* Balfour fix from imagemagick discourse server, 5 Feb 2010 */ if (storage_class == PseudoClass) { if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { for (x=0; x < ping_num_trans; x++) { image->colormap[x].alpha_trait=BlendPixelTrait; image->colormap[x].alpha = ScaleCharToQuantum((unsigned char)ping_trans_alpha[x]); } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY) { for (x=0; x < (int) image->colors; x++) { if (ScaleQuantumToShort(image->colormap[x].red) == transparent_color.alpha) { image->colormap[x].alpha_trait=BlendPixelTrait; image->colormap[x].alpha = (Quantum) TransparentAlpha; } } } (void) SyncImage(image,exception); } #if 1 /* Should have already been done above, but glennrp problem P10 * needs this. */ else { for (y=0; y < (ssize_t) image->rows; y++) { image->storage_class=storage_class; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; /* Caution: on a Q8 build, this does not distinguish between * 16-bit colors that differ only in the low byte */ for (x=(ssize_t) image->columns-1; x >= 0; x--) { if (ScaleQuantumToShort(GetPixelRed(image,q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(image,q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(image,q)) == transparent_color.blue) { SetPixelAlpha(image,TransparentAlpha,q); } #if 0 /* I have not found a case where this is needed. */ else { SetPixelAlpha(image,q)=(Quantum) OpaqueAlpha; } #endif q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif image->storage_class=DirectClass; } for (j = 0; j < 2; j++) { if (j == 0) status = png_get_text(ping,ping_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; else status = png_get_text(ping,end_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) for (i=0; i < (ssize_t) num_text; i++) { /* Check for a profile */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG text chunk"); if (strlen(text[i].key) > 16 && memcmp(text[i].key, "Raw profile type ",17) == 0) { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember(text[i].key+17,value) == MagickFalse) { (void) Magick_png_read_raw_profile(ping,image,image_info,text, (int) i,exception); num_raw_profiles++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Read raw profile %s",text[i].key+17); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping raw profile %s",text[i].key+17); } } else { char *value; length=text[i].text_length; value=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*value)); if (value == (char *) NULL) { png_error(ping,"Memory allocation failed"); break; } *value='\0'; (void) ConcatenateMagickString(value,text[i].text,length+2); /* Don't save "density" or "units" property if we have a pHYs * chunk */ if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) || (LocaleCompare(text[i].key,"density") != 0 && LocaleCompare(text[i].key,"units") != 0)) (void) SetImageProperty(image,text[i].key,value,exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu\n" " Keyword: %s", (unsigned long) length, text[i].key); } value=DestroyString(value); } } num_text_total += num_text; } #ifdef MNG_OBJECT_BUFFERS /* Store the object if necessary. */ if (object_id && !mng_info->frozen[object_id]) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) { /* create a new object buffer. */ mng_info->ob[object_id]=(MngBuffer *) AcquireMagickMemory(sizeof(MngBuffer)); if (mng_info->ob[object_id] != (MngBuffer *) NULL) { mng_info->ob[object_id]->image=(Image *) NULL; mng_info->ob[object_id]->reference_count=1; } } if ((mng_info->ob[object_id] == (MngBuffer *) NULL) || mng_info->ob[object_id]->frozen) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) png_error(ping,"Memory allocation failed"); if (mng_info->ob[object_id]->frozen) png_error(ping,"Cannot overwrite frozen MNG object buffer"); } else { if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image=DestroyImage (mng_info->ob[object_id]->image); mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue, exception); if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image->file=(FILE *) NULL; else png_error(ping, "Cloning image for object buffer failed"); if (ping_width > 250000L || ping_height > 250000L) png_error(ping,"PNG Image dimensions are too large."); mng_info->ob[object_id]->width=ping_width; mng_info->ob[object_id]->height=ping_height; mng_info->ob[object_id]->color_type=ping_color_type; mng_info->ob[object_id]->sample_depth=ping_bit_depth; mng_info->ob[object_id]->interlace_method=ping_interlace_method; mng_info->ob[object_id]->compression_method= ping_compression_method; mng_info->ob[object_id]->filter_method=ping_filter_method; if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp plte; /* Copy the PLTE to the object buffer. */ png_get_PLTE(ping,ping_info,&plte,&number_colors); mng_info->ob[object_id]->plte_length=number_colors; for (i=0; i < number_colors; i++) { mng_info->ob[object_id]->plte[i]=plte[i]; } } else mng_info->ob[object_id]->plte_length=0; } } #endif /* Set image->alpha_trait to MagickTrue if the input colortype supports * alpha or if a valid tRNS chunk is present, no matter whether there * is actual transparency present. */ image->alpha_trait=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? BlendPixelTrait : UndefinedPixelTrait; #if 0 /* I'm not sure what's wrong here but it does not work. */ if (image->alpha_trait != UndefinedPixelTrait) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) SetImageType(image,GrayscaleAlphaType,exception); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteAlphaType,exception); else (void) SetImageType(image,TrueColorAlphaType,exception); } else { if (ping_color_type == PNG_COLOR_TYPE_GRAY) (void) SetImageType(image,GrayscaleType,exception); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteType,exception); else (void) SetImageType(image,TrueColorType,exception); } #endif /* Set more properties for identify to retrieve */ { char msg[MagickPathExtent]; if (num_text_total != 0) { /* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */ (void) FormatLocaleString(msg,MagickPathExtent, "%d tEXt/zTXt/iTXt chunks were found", num_text_total); (void) SetImageProperty(image,"png:text",msg, exception); } if (num_raw_profiles != 0) { (void) FormatLocaleString(msg,MagickPathExtent, "%d were found", num_raw_profiles); (void) SetImageProperty(image,"png:text-encoded profiles",msg, exception); } /* cHRM chunk: */ if (ping_found_cHRM != MagickFalse) { (void) FormatLocaleString(msg,MagickPathExtent,"%s", "chunk was found (see Chromaticity, above)"); (void) SetImageProperty(image,"png:cHRM",msg, exception); } /* bKGD chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { (void) FormatLocaleString(msg,MagickPathExtent,"%s", "chunk was found (see Background color, above)"); (void) SetImageProperty(image,"png:bKGD",msg, exception); } (void) FormatLocaleString(msg,MagickPathExtent,"%s", "chunk was found"); #if defined(PNG_iCCP_SUPPORTED) /* iCCP chunk: */ if (ping_found_iCCP != MagickFalse) (void) SetImageProperty(image,"png:iCCP",msg, exception); #endif if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) (void) SetImageProperty(image,"png:tRNS",msg, exception); #if defined(PNG_sRGB_SUPPORTED) /* sRGB chunk: */ if (ping_found_sRGB != MagickFalse) { (void) FormatLocaleString(msg,MagickPathExtent, "intent=%d (%s)", (int) intent, Magick_RenderingIntentString_from_PNG_RenderingIntent(intent)); (void) SetImageProperty(image,"png:sRGB",msg, exception); } #endif /* gAMA chunk: */ if (ping_found_gAMA != MagickFalse) { (void) FormatLocaleString(msg,MagickPathExtent, "gamma=%.8g (See Gamma, above)", file_gamma); (void) SetImageProperty(image,"png:gAMA",msg, exception); } #if defined(PNG_pHYs_SUPPORTED) /* pHYs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { (void) FormatLocaleString(msg,MagickPathExtent, "x_res=%.10g, y_res=%.10g, units=%d", (double) x_resolution,(double) y_resolution, unit_type); (void) SetImageProperty(image,"png:pHYs",msg, exception); } #endif #if defined(PNG_oFFs_SUPPORTED) /* oFFs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { (void) FormatLocaleString(msg,MagickPathExtent, "x_off=%.20g, y_off=%.20g", (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:oFFs",msg, exception); } #endif #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,end_info,exception); #endif /* caNv chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || (image->page.x != 0 || image->page.y != 0)) { (void) FormatLocaleString(msg,MagickPathExtent, "width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:caNv",msg, exception); } /* vpAg chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { (void) FormatLocaleString(msg,MagickPathExtent, "width=%.20g, height=%.20g", (double) image->page.width,(double) image->page.height); (void) SetImageProperty(image,"png:vpAg",msg, exception); } } /* Relinquish resources. */ png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block, revert to * Throwing an Exception when an error occurs. */ return(image); /* end of reading one PNG image */ } static Image *ReadPNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MagickPathExtent]; ssize_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()"); image=AcquireImage(image_info,exception); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) ThrowReaderException(FileOpenError,"UnableToOpenFile"); /* Verify PNG signature. */ count=ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOnePNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if ((image->columns == 0) || (image->rows == 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if ((IssRGBColorspace(image->colorspace) != MagickFalse) && ((image->gamma < .45) || (image->gamma > .46)) && !(image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f)) { SetImageColorspace(image,RGBColorspace,exception); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace: %d", (int) image->colorspace); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()"); return(image); } #if defined(JNG_SUPPORTED) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadOneJNGImage method is: % % Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const Quantum *s; register ssize_t i, x; register Quantum *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MagickPathExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MagickPathExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) chunk[i]=(unsigned char) ReadBlobByte(image); p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError, "NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info,exception); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); (void) AcquireUniqueFilename(color_image->filename); status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info,exception); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->resolution.x=(double) mng_get_long(p); image->resolution.y=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->resolution.x=image->resolution.x/100.0f; image->resolution.y=image->resolution.y/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into alpha samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MagickPathExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->rows=jng_height; image->columns=jng_width; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelRed(image,GetPixelRed(jng_image,s),q); SetPixelGreen(image,GetPixelGreen(jng_image,s),q); SetPixelBlue(image,GetPixelBlue(jng_image,s),q); q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) CloseBlob(alpha_image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading alpha from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MagickPathExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->alpha_trait != UndefinedPixelTrait) for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelAlpha(image,GetPixelRed(jng_image,s),q); q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } else for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelAlpha(image,GetPixelRed(jng_image,s),q); if (GetPixelAlpha(image,q) != OpaqueAlpha) image->alpha_trait=BlendPixelTrait; q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage()"); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJNGImage() reads a JPEG Network Graphics (JNG) image file % (including the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadJNGImage method is: % % Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo % *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MagickPathExtent]; size_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()"); image=AcquireImage(image_info,exception); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); if (LocaleCompare(image_info->magick,"JNG") != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify JNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneJNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (image->columns == 0 || image->rows == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); ThrowReaderException(CorruptImageError,"CorruptImage"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()"); return(image); } #endif static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MagickPathExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False during convert or mogrify */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MagickPathExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) chunk[i]=(unsigned char) ReadBlobByte(image); p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length < 2) { if (chunk) chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream","`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 13) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 15) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 17) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { /* Interpolate */ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelChannel() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } /* To do: Rewrite using Get/Set***PixelChannel() */ else { /* Interpolate */ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { /* Interpolate */ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneMNGImage();"); return(image); } static Image *ReadMNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()"); image=AcquireImage(image_info,exception); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneMNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadMNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()"); return(GetFirstImageInList(image)); } #else /* PNG_LIBPNG_VER > 10011 */ static Image *ReadPNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "PNG library is too old","`%s'",image_info->filename); return(Image *) NULL; } static Image *ReadMNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { return(ReadPNGImage(image_info,exception)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNGImage() adds properties for the PNG image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNGImage method is: % % size_t RegisterPNGImage(void) % */ ModuleExport size_t RegisterPNGImage(void) { char version[MagickPathExtent]; MagickInfo *entry; static const char *PNGNote= { "See http://www.libpng.org/ for details about the PNG format." }, *JNGNote= { "See http://www.libpng.org/pub/mng/ for details about the JNG\n" "format." }, *MNGNote= { "See http://www.libpng.org/pub/mng/ for details about the MNG\n" "format." }; *version='\0'; #if defined(PNG_LIBPNG_VER_STRING) (void) ConcatenateMagickString(version,"libpng ",MagickPathExtent); (void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING, MagickPathExtent); if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0) { (void) ConcatenateMagickString(version,",",MagickPathExtent); (void) ConcatenateMagickString(version,png_get_libpng_ver(NULL), MagickPathExtent); } #endif entry=AcquireMagickInfo("PNG","MNG","Multiple-image Network Graphics"); entry->flags|=CoderSeekableStreamFlag; /* To do: eliminate this. */ #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMNGImage; entry->encoder=(EncodeImageHandler *) WriteMNGImage; #endif entry->magick=(IsImageFormatHandler *) IsMNG; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("video/x-mng"); entry->note=ConstantString(MNGNote); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG","Portable Network Graphics"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); if (*version != '\0') entry->version=ConstantString(version); entry->note=ConstantString(PNGNote); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG8", "8-bit indexed with optional binary transparency"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG24", "opaque or binary transparent 24-bit RGB"); *version='\0'; #if defined(ZLIB_VERSION) (void) ConcatenateMagickString(version,"zlib ",MagickPathExtent); (void) ConcatenateMagickString(version,ZLIB_VERSION,MagickPathExtent); if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0) { (void) ConcatenateMagickString(version,",",MagickPathExtent); (void) ConcatenateMagickString(version,zlib_version,MagickPathExtent); } #endif if (*version != '\0') entry->version=ConstantString(version); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG32","opaque or transparent 32-bit RGBA"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG48", "opaque or binary transparent 48-bit RGB"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG64","opaque or transparent 64-bit RGBA"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG00", "PNG inheriting bit-depth, color-type from original, if possible"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","JNG","JPEG Network Graphics"); #if defined(JNG_SUPPORTED) #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJNGImage; entry->encoder=(EncodeImageHandler *) WriteJNGImage; #endif #endif entry->magick=(IsImageFormatHandler *) IsJNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/x-jng"); entry->note=ConstantString(JNGNote); (void) RegisterMagickInfo(entry); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE ping_semaphore=AcquireSemaphoreInfo(); #endif return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNGImage() removes format registrations made by the % PNG module from the list of supported formats. % % The format of the UnregisterPNGImage method is: % % UnregisterPNGImage(void) % */ ModuleExport void UnregisterPNGImage(void) { (void) UnregisterMagickInfo("MNG"); (void) UnregisterMagickInfo("PNG"); (void) UnregisterMagickInfo("PNG8"); (void) UnregisterMagickInfo("PNG24"); (void) UnregisterMagickInfo("PNG32"); (void) UnregisterMagickInfo("PNG48"); (void) UnregisterMagickInfo("PNG64"); (void) UnregisterMagickInfo("PNG00"); (void) UnregisterMagickInfo("JNG"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE if (ping_semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&ping_semaphore); #endif } #if defined(MAGICKCORE_PNG_DELEGATE) #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMNGImage() writes an image in the Portable Network Graphics % Group's "Multiple-image Network Graphics" encoded image format. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteMNGImage method is: % % MagickBooleanType WriteMNGImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % % To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also % "To do" under ReadPNGImage): % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % Write the iCCP chunk at MNG level when (icc profile length > 0) % % Improve selection of color type (use indexed-colour or indexed-colour % with tRNS when 256 or fewer unique RGBA values are present). % % Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3) % This will be complicated if we limit ourselves to generating MNG-LC % files. For now we ignore disposal method 3 and simply overlay the next % image on it. % % Check for identical PLTE's or PLTE/tRNS combinations and use a % global MNG PLTE or PLTE/tRNS combination when appropriate. % [mostly done 15 June 1999 but still need to take care of tRNS] % % Check for identical sRGB and replace with a global sRGB (and remove % gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and % replace with global gAMA/cHRM (or with sRGB if appropriate; replace % local gAMA/cHRM with local sRGB if appropriate). % % Check for identical sBIT chunks and write global ones. % % Provide option to skip writing the signature tEXt chunks. % % Use signatures to detect identical objects and reuse the first % instance of such objects instead of writing duplicate objects. % % Use a smaller-than-32k value of compression window size when % appropriate. % % Encode JNG datastreams. Mostly done as of 5.5.2; need to write % ancillary text chunks and save profiles. % % Provide an option to force LC files (to ensure exact framing rate) % instead of VLC. % % Provide an option to force VLC files instead of LC, even when offsets % are present. This will involve expanding the embedded images with a % transparent region at the top and/or left. */ static void Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping, png_info *ping_info, unsigned char *profile_type, unsigned char *profile_description, unsigned char *profile_data, png_uint_32 length) { png_textp text; register ssize_t i; unsigned char *sp; png_charp dp; png_uint_32 allocated_length, description_length; unsigned char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0) return; if (image_info->verbose) { (void) printf("writing raw profile: type=%s, length=%.20g\n", (char *) profile_type, (double) length); } #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif description_length=(png_uint_32) strlen((const char *) profile_description); allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20 + description_length); #if PNG_LIBPNG_VER >= 10400 text[0].text=(png_charp) png_malloc(ping, (png_alloc_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80); #else text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80); #endif text[0].key[0]='\0'; (void) ConcatenateMagickString(text[0].key, "Raw profile type ",MagickPathExtent); (void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62); sp=profile_data; dp=text[0].text; *dp++='\n'; (void) CopyMagickString(dp,(const char *) profile_description, allocated_length); dp+=description_length; *dp++='\n'; (void) FormatLocaleString(dp,allocated_length- (png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length); dp+=8; for (i=0; i < (ssize_t) length; i++) { if (i%36 == 0) *dp++='\n'; *(dp++)=(char) hex[((*sp >> 4) & 0x0f)]; *(dp++)=(char) hex[((*sp++ ) & 0x0f)]; } *dp++='\n'; *dp='\0'; text[0].text_length=(png_size_t) (dp-text[0].text); text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? -1 : 0; if (text[0].text_length <= allocated_length) png_set_text(ping,ping_info,text,1); png_free(ping,text[0].text); png_free(ping,text[0].key); png_free(ping,text); } static MagickBooleanType Magick_png_write_chunk_from_profile(Image *image, const char *string, MagickBooleanType logging) { char *name; const StringInfo *profile; unsigned char *data; png_uint_32 length; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (const StringInfo *) NULL) { StringInfo *ping_profile; if (LocaleNCompare(name,string,11) == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found %s profile",name); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); data[4]=data[3]; data[3]=data[2]; data[2]=data[1]; data[1]=data[0]; (void) WriteBlobMSBULong(image,length-5); /* data length */ (void) WriteBlob(image,length-1,data+1); (void) WriteBlobMSBULong(image,crc32(0,data+1,(uInt) length-1)); ping_profile=DestroyStringInfo(ping_profile); } } name=GetNextImageProfile(image); } return(MagickTrue); } static inline MagickBooleanType Magick_png_color_equal(const Image *image, const Quantum *p, const PixelInfo *q) { MagickRealType value; value=(MagickRealType) p[image->channel_map[RedPixelChannel].offset]; if (AbsolutePixelValue(value-q->red) >= MagickEpsilon) return(MagickFalse); value=(MagickRealType) p[image->channel_map[GreenPixelChannel].offset]; if (AbsolutePixelValue(value-q->green) >= MagickEpsilon) return(MagickFalse); value=(MagickRealType) p[image->channel_map[BluePixelChannel].offset]; if (AbsolutePixelValue(value-q->blue) >= MagickEpsilon) return(MagickFalse); return(MagickTrue); } #if defined(PNG_tIME_SUPPORTED) static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info, const char *date,ExceptionInfo *exception) { unsigned int day, hour, minute, month, second, year; png_time ptime; time_t ttime; if (date != (const char *) NULL) { if (sscanf(date,"%d-%d-%dT%d:%d:%dZ",&year,&month,&day,&hour,&minute, &second) != 6) { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "Invalid date format specified for png:tIME","`%s'", image->filename); return; } ptime.year=(png_uint_16) year; ptime.month=(png_byte) month; ptime.day=(png_byte) day; ptime.hour=(png_byte) hour; ptime.minute=(png_byte) minute; ptime.second=(png_byte) second; } else { time(&ttime); png_convert_from_time_t(&ptime,ttime); } png_set_tIME(ping,info,&ptime); } #endif /* Write one PNG image */ static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char s[2]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, #ifdef exIf_SUPPORTED ping_have_eXIf, #endif ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ #ifdef exIf_SUPPORTED ping_exclude_eXIf, #endif ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); image = CloneImage(IMimage,0,0,MagickFalse,exception); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); if (image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; #ifdef exIf_SUPPORTED ping_have_eXIf=MagickTrue; #endif ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; #ifdef exIf_SUPPORTED /* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; */ ping_exclude_eXIf=mng_info->ping_exclude_eXIf; #endif ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_vpAg=mng_info->ping_exclude_vpAg; ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *s; register Quantum *q, *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->alpha_trait=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,q) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image, q, opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (Magick_png_color_equal(image,q,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image, q, opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,q) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image, q, transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,q); ping_trans_color.green=(unsigned short) GetPixelGreen(image,q); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,q); ping_trans_color.gray=(unsigned short) GetPixelGray(image,q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (Magick_png_color_equal(image,q,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,q,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,q,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (Magick_png_color_equal(image,q,semitransparent+i) && GetPixelAlpha(image,q) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image, q, semitransparent+i); } } } q+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != GetPixelGreen(image,s) || GetPixelRed(image,s) != GetPixelBlue(image,s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != 0 && GetPixelRed(image,s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) < OpaqueAlpha/2) { SetPixelViaPixelInfo(image,&image->background_color,r); SetPixelAlpha(image,TransparentAlpha,r); } else SetPixelAlpha(image,OpaqueAlpha,r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha/2 ? TransparentAlpha : OpaqueAlpha); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR04PixelRGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR03RGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR02PixelBlue(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 && GetPixelAlpha(image,r) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),r); } r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",IMimage->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates "-define png:compression-strategy", etc. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { /* Add an opaque matte channel */ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { /* Do not write hex-encoded ICC chunk */ name=GetNextImageProfile(image); continue; } } #endif /* WRITE_iCCP */ #if defined(eXIf_SUPPORTED) || defined(exIf_SUPPORTED) if (LocaleCompare(name,"exif") == 0) { /* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk */ name=GetNextImageProfile(image); continue; } #endif (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXt chunk with uuencoded %s profile", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } /* write any png-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging); png_write_info(ping,ping_info); /* write any PNG-chunk-m profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging); ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif /* write vpAg chunk (deprecated, replaced by caNv) */ if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { unsigned char chunk[14]; (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } } #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const Quantum *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write any PNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging); #ifdef exIf_SUPPORTED /* write exIf profile */ #ifdef IM if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) #endif { #ifdef GM ImageProfileIterator *profile_iterator; profile_iterator=AllocateImageProfileIterator(image); if (profile_iterator) { const char *profile_name; const unsigned char *profile_info; size_t profile_length; while (NextImageProfile(profile_iterator,&profile_name,&profile_info, &profile_length) != MagickFail) { if (LocaleCompare(profile_name,"exif") == 0) { #else /* IM */ char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #endif /* GM */ png_uint_32 length; unsigned char chunk[4], *data; #ifdef IM StringInfo *ping_profile; #endif (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); #ifdef GM data=profile_info; length=(png_uint_32) profile_length; #else /* IM */ ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); #endif /* GM */ #if 0 /* eXIf chunk is registered */ PNGType(chunk,mng_eXIf); #else /* eXIf chunk not yet registered; write exIf instead */ PNGType(chunk,mng_exIf); #endif if (length < 7) break; /* othewise crashes */ /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data+6); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data+6, (uInt) length)); break; #ifdef IM name=GetNextImageProfile(image); #endif } } } } #endif /* exIf_SUPPORTED */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNGImage() writes a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WritePNGImage method is: % % MagickBooleanType WritePNGImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % % Returns MagickTrue on success, MagickFalse on failure. % % Communicating with the PNG encoder: % % While the datastream written is always in PNG format and normally would % be given the "png" file extension, this method also writes the following % pseudo-formats which are subsets of png: % % o PNG8: An 8-bit indexed PNG datastream is written. If the image has % a depth greater than 8, the depth is reduced. If transparency % is present, the tRNS chunk must only have values 0 and 255 % (i.e., transparency is binary: fully opaque or fully % transparent). If other values are present they will be % 50%-thresholded to binary transparency. If more than 256 % colors are present, they will be quantized to the 4-4-4-1, % 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color % of any resulting fully-transparent pixels is changed to % the image's background color. % % If you want better quantization or dithering of the colors % or alpha than that, you need to do it before calling the % PNG encoder. The pixels contain 8-bit indices even if % they could be represented with 1, 2, or 4 bits. Grayscale % images will be written as indexed PNG files even though the % PNG grayscale type might be slightly more efficient. Please % note that writing to the PNG8 format may result in loss % of color and alpha data. % % o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. The only loss incurred % is reduction of sample depth to 8. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG32: An 8-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 255. The alpha % channel is present even if the image is fully opaque. % The only loss in data is the reduction of the sample depth % to 8. % % o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG64: A 16-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 65535. The alpha % channel is present even if the image is fully opaque. % % o PNG00: A PNG that inherits its colortype and bit-depth from the input % image, if the input was a PNG, is written. If these values % cannot be found, or if the pixels have been changed in a way % that makes this impossible, then "PNG00" falls back to the % regular "PNG" format. % % o -define: For more precise control of the PNG output, you can use the % Image options "png:bit-depth" and "png:color-type". These % can be set from the commandline with "-define" and also % from the application programming interfaces. The options % are case-independent and are converted to lowercase before % being passed to this encoder. % % png:color-type can be 0, 2, 3, 4, or 6. % % When png:color-type is 0 (Grayscale), png:bit-depth can % be 1, 2, 4, 8, or 16. % % When png:color-type is 2 (RGB), png:bit-depth can % be 8 or 16. % % When png:color-type is 3 (Indexed), png:bit-depth can % be 1, 2, 4, or 8. This refers to the number of bits % used to store the index. The color samples always have % bit-depth 8 in indexed PNG files. % % When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte), % png:bit-depth can be 8 or 16. % % If the image cannot be written without loss with the % requested bit-depth and color-type, a PNG file will not % be written, a warning will be issued, and the encoder will % return MagickFalse. % % Since image encoders should not be responsible for the "heavy lifting", % the user should make sure that ImageMagick has already reduced the % image depth and number of colors and limit transparency to binary % transparency prior to attempting to write the image with depth, color, % or transparency limitations. % % Note that another definition, "png:bit-depth-written" exists, but it % is not intended for external use. It is only used internally by the % PNG encoder to inform the JNG encoder of the depth of the alpha channel. % % It is possible to request that the PNG encoder write previously-formatted % ancillary chunks in the output PNG file, using the "-profile" commandline % option as shown below or by setting the profile via a programming % interface: % % -profile PNG-chunk-x:<file> % % where x is a location flag and <file> is a file containing the chunk % name in the first 4 bytes, then a colon (":"), followed by the chunk data. % This encoder will compute the chunk length and CRC, so those must not % be included in the file. % % "x" can be "b" (before PLTE), "m" (middle, i.e., between PLTE and IDAT), % or "e" (end, i.e., after IDAT). If you want to write multiple chunks % of the same type, then add a short unique string after the "x" to prevent % subsequent profiles from overwriting the preceding ones, e.g., % % -profile PNG-chunk-b01:file01 -profile PNG-chunk-b02:file02 % % As of version 6.6.6 the following optimizations are always done: % % o 32-bit depth is reduced to 16. % o 16-bit depth is reduced to 8 if all pixels contain samples whose % high byte and low byte are identical. % o Palette is sorted to remove unused entries and to put a % transparent color first, if BUILD_PNG_PALETTE is defined. % o Opaque matte channel is removed when writing an indexed PNG. % o Grayscale images are reduced to 1, 2, or 4 bit depth if % this can be done without loss and a larger bit depth N was not % requested via the "-define png:bit-depth=N" option. % o If matte channel is present but only one transparent color is % present, RGB+tRNS is written instead of RGBA % o Opaque matte channel is removed (or added, if color-type 4 or 6 % was requested when converting an opaque image). % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { MagickBooleanType excluding, logging, status; MngInfo *mng_info; const char *value; int source; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; mng_info->equal_backgrounds=MagickTrue; /* See if user has requested a specific PNG subformat */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0; mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0; value=GetImageOption(image_info,"png:format"); if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",value); mng_info->write_png8 = MagickFalse; mng_info->write_png24 = MagickFalse; mng_info->write_png32 = MagickFalse; mng_info->write_png48 = MagickFalse; mng_info->write_png64 = MagickFalse; if (LocaleCompare(value,"png8") == 0) mng_info->write_png8 = MagickTrue; else if (LocaleCompare(value,"png24") == 0) mng_info->write_png24 = MagickTrue; else if (LocaleCompare(value,"png32") == 0) mng_info->write_png32 = MagickTrue; else if (LocaleCompare(value,"png48") == 0) mng_info->write_png48 = MagickTrue; else if (LocaleCompare(value,"png64") == 0) mng_info->write_png64 = MagickTrue; else if ((LocaleCompare(value,"png00") == 0) || LocaleCompare(image_info->magick,"PNG00") == 0) { /* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig. */ value=GetImageProperty(image,"png:IHDR.bit-depth-orig",exception); if (value != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited bit depth=%s",value); if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; } value=GetImageProperty(image,"png:IHDR.color-type-orig",exception); if (value != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited color type=%s",value); if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; } } } if (mng_info->write_png8) { mng_info->write_png_colortype = /* 3 */ 4; mng_info->write_png_depth = 8; image->depth = 8; } if (mng_info->write_png24) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 8; image->depth = 8; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageType(image,TrueColorAlphaType,exception); else (void) SetImageType(image,TrueColorType,exception); (void) SyncImage(image,exception); } if (mng_info->write_png32) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 8; image->depth = 8; image->alpha_trait = BlendPixelTrait; (void) SetImageType(image,TrueColorAlphaType,exception); (void) SyncImage(image,exception); } if (mng_info->write_png48) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 16; image->depth = 16; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageType(image,TrueColorAlphaType,exception); else (void) SetImageType(image,TrueColorType,exception); (void) SyncImage(image,exception); } if (mng_info->write_png64) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 16; image->depth = 16; image->alpha_trait = BlendPixelTrait; (void) SetImageType(image,TrueColorAlphaType,exception); (void) SyncImage(image,exception); } value=GetImageOption(image_info,"png:bit-depth"); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:bit-depth", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:bit-depth=%d was defined.\n",mng_info->write_png_depth); } value=GetImageOption(image_info,"png:color-type"); if (value != (char *) NULL) { /* We must store colortype+1 because 0 is a valid colortype */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_colortype = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:color-type", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:color-type=%d was defined.\n", mng_info->write_png_colortype-1); } /* Check for chunks to be excluded: * * The default is to not exclude any known chunks except for any * listed in the "unused_chunks" array, above. * * Chunks can be listed for exclusion via a "png:exclude-chunk" * define (in the image properties or in the image artifacts) * or via a mng_info member. For convenience, in addition * to or instead of a comma-separated list of chunks, the * "exclude-chunk" string can be simply "all" or "none". * * The exclude-chunk define takes priority over the mng_info. * * A "png:include-chunk" define takes priority over both the * mng_info and the "png:exclude-chunk" define. Like the * "exclude-chunk" string, it can define "all" or "none" as * well as a comma-separated list. Chunks that are unknown to * ImageMagick are always excluded, regardless of their "copy-safe" * status according to the PNG specification, and even if they * appear in the "include-chunk" list. Such defines appearing among * the image options take priority over those found among the image * artifacts. * * Finally, all chunks listed in the "unused_chunks" array are * automatically excluded, regardless of the other instructions * or lack thereof. * * if you exclude sRGB but not gAMA (recommended), then sRGB chunk * will not be written and the gAMA chunk will only be written if it * is not between .45 and .46, or approximately (1.0/2.2). * * If you exclude tRNS and the image has transparency, the colortype * is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA). * * The -strip option causes StripImage() to set the png:include-chunk * artifact to "none,trns,gama". */ mng_info->ping_exclude_bKGD=MagickFalse; mng_info->ping_exclude_caNv=MagickFalse; mng_info->ping_exclude_cHRM=MagickFalse; mng_info->ping_exclude_date=MagickFalse; mng_info->ping_exclude_eXIf=MagickFalse; mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */ mng_info->ping_exclude_gAMA=MagickFalse; mng_info->ping_exclude_iCCP=MagickFalse; /* mng_info->ping_exclude_iTXt=MagickFalse; */ mng_info->ping_exclude_oFFs=MagickFalse; mng_info->ping_exclude_pHYs=MagickFalse; mng_info->ping_exclude_sRGB=MagickFalse; mng_info->ping_exclude_tEXt=MagickFalse; mng_info->ping_exclude_tIME=MagickFalse; mng_info->ping_exclude_tRNS=MagickFalse; mng_info->ping_exclude_vpAg=MagickFalse; mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */ mng_info->ping_exclude_zTXt=MagickFalse; mng_info->ping_preserve_colormap=MagickFalse; value=GetImageOption(image_info,"png:preserve-colormap"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-colormap"); if (value != NULL) mng_info->ping_preserve_colormap=MagickTrue; mng_info->ping_preserve_iCCP=MagickFalse; value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) mng_info->ping_preserve_iCCP=MagickTrue; /* These compression-level, compression-strategy, and compression-filter * defines take precedence over values from the -quality option. */ value=GetImageOption(image_info,"png:compression-level"); if (value == NULL) value=GetImageArtifact(image,"png:compression-level"); if (value != NULL) { /* We have to add 1 to everything because 0 is a valid input, * and we want to use 0 (the default) to mean undefined. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_level = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_level = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_level = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_level = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_level = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_level = 6; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_compression_level = 7; else if (LocaleCompare(value,"7") == 0) mng_info->write_png_compression_level = 8; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_compression_level = 9; else if (LocaleCompare(value,"9") == 0) mng_info->write_png_compression_level = 10; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-level", "=%s",value); } value=GetImageOption(image_info,"png:compression-strategy"); if (value == NULL) value=GetImageArtifact(image,"png:compression-strategy"); if (value != NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_strategy = Z_FILTERED+1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; else if (LocaleCompare(value,"3") == 0) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy = Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else if (LocaleCompare(value,"4") == 0) #ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */ mng_info->write_png_compression_strategy = Z_FIXED+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-strategy", "=%s",value); } value=GetImageOption(image_info,"png:compression-filter"); if (value == NULL) value=GetImageArtifact(image,"png:compression-filter"); if (value != NULL) { /* To do: combinations of filters allowed by libpng * masks 0x08 through 0xf8 * * Implement this as a comma-separated list of 0,1,2,3,4,5 * where 5 is a special case meaning PNG_ALL_FILTERS. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_filter = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_filter = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_filter = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_filter = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_filter = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_filter = 6; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-filter", "=%s",value); } for (source=0; source<8; source++) { value = NULL; if (source == 0) value=GetImageOption(image_info,"png:exclude-chunks"); if (source == 1) value=GetImageArtifact(image,"png:exclude-chunks"); if (source == 2) value=GetImageOption(image_info,"png:exclude-chunk"); if (source == 3) value=GetImageArtifact(image,"png:exclude-chunk"); if (source == 4) value=GetImageOption(image_info,"png:include-chunks"); if (source == 5) value=GetImageArtifact(image,"png:include-chunks"); if (source == 6) value=GetImageOption(image_info,"png:include-chunk"); if (source == 7) value=GetImageArtifact(image,"png:include-chunk"); if (value == NULL) continue; if (source < 4) excluding = MagickTrue; else excluding = MagickFalse; if (logging != MagickFalse) { if (source == 0 || source == 2) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image options.\n", value); else if (source == 1 || source == 3) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image artifacts.\n", value); else if (source == 4 || source == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image options.\n", value); else /* if (source == 5 || source == 7) */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image artifacts.\n", value); } if (IsOptionMember("all",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding; mng_info->ping_exclude_caNv=excluding; mng_info->ping_exclude_cHRM=excluding; mng_info->ping_exclude_date=excluding; mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; mng_info->ping_exclude_gAMA=excluding; mng_info->ping_exclude_iCCP=excluding; /* mng_info->ping_exclude_iTXt=excluding; */ mng_info->ping_exclude_oFFs=excluding; mng_info->ping_exclude_pHYs=excluding; mng_info->ping_exclude_sRGB=excluding; mng_info->ping_exclude_tEXt=excluding; mng_info->ping_exclude_tIME=excluding; mng_info->ping_exclude_tRNS=excluding; mng_info->ping_exclude_vpAg=excluding; mng_info->ping_exclude_zCCP=excluding; mng_info->ping_exclude_zTXt=excluding; } if (IsOptionMember("none",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; /* mng_info->ping_exclude_iTXt=!excluding; */ mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_vpAg=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse : MagickTrue; } if (IsOptionMember("bkgd",value) != MagickFalse) mng_info->ping_exclude_bKGD=excluding; if (IsOptionMember("caNv",value) != MagickFalse) mng_info->ping_exclude_caNv=excluding; if (IsOptionMember("chrm",value) != MagickFalse) mng_info->ping_exclude_cHRM=excluding; if (IsOptionMember("date",value) != MagickFalse) mng_info->ping_exclude_date=excluding; if (IsOptionMember("exif",value) != MagickFalse) { mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; } if (IsOptionMember("gama",value) != MagickFalse) mng_info->ping_exclude_gAMA=excluding; if (IsOptionMember("iccp",value) != MagickFalse) mng_info->ping_exclude_iCCP=excluding; #if 0 if (IsOptionMember("itxt",value) != MagickFalse) mng_info->ping_exclude_iTXt=excluding; #endif if (IsOptionMember("offs",value) != MagickFalse) mng_info->ping_exclude_oFFs=excluding; if (IsOptionMember("phys",value) != MagickFalse) mng_info->ping_exclude_pHYs=excluding; if (IsOptionMember("srgb",value) != MagickFalse) mng_info->ping_exclude_sRGB=excluding; if (IsOptionMember("text",value) != MagickFalse) mng_info->ping_exclude_tEXt=excluding; if (IsOptionMember("time",value) != MagickFalse) mng_info->ping_exclude_tIME=excluding; if (IsOptionMember("trns",value) != MagickFalse) mng_info->ping_exclude_tRNS=excluding; if (IsOptionMember("vpag",value) != MagickFalse) mng_info->ping_exclude_vpAg=excluding; if (IsOptionMember("zccp",value) != MagickFalse) mng_info->ping_exclude_zCCP=excluding; if (IsOptionMember("ztxt",value) != MagickFalse) mng_info->ping_exclude_zTXt=excluding; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Chunks to be excluded from the output png:"); if (mng_info->ping_exclude_bKGD != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bKGD"); if (mng_info->ping_exclude_caNv != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " caNv"); if (mng_info->ping_exclude_cHRM != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " cHRM"); if (mng_info->ping_exclude_date != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " date"); if (mng_info->ping_exclude_EXIF != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " EXIF"); if (mng_info->ping_exclude_eXIf != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " eXIf"); if (mng_info->ping_exclude_gAMA != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " gAMA"); if (mng_info->ping_exclude_iCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iCCP"); #if 0 if (mng_info->ping_exclude_iTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iTXt"); #endif if (mng_info->ping_exclude_oFFs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " oFFs"); if (mng_info->ping_exclude_pHYs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pHYs"); if (mng_info->ping_exclude_sRGB != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " sRGB"); if (mng_info->ping_exclude_tEXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tEXt"); if (mng_info->ping_exclude_tIME != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tIME"); if (mng_info->ping_exclude_tRNS != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS"); if (mng_info->ping_exclude_vpAg != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " vpAg"); if (mng_info->ping_exclude_zCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zCCP"); if (mng_info->ping_exclude_zTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zTXt"); } mng_info->need_blob = MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image,exception); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()"); return(status); } #if defined(JNG_SUPPORTED) /* Write one JNG image */ static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image,ExceptionInfo *exception) { Image *jpeg_image; ImageInfo *jpeg_image_info; MagickBooleanType logging, status; size_t length; unsigned char *blob, chunk[80], *p; unsigned int jng_alpha_compression_method, jng_alpha_sample_depth, jng_color_type, transparent; size_t jng_alpha_quality, jng_quality; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOneJNGImage()"); blob=(unsigned char *) NULL; jpeg_image=(Image *) NULL; jpeg_image_info=(ImageInfo *) NULL; length=0; status=MagickTrue; transparent=image_info->type==GrayscaleAlphaType || image_info->type==TrueColorAlphaType || image->alpha_trait != UndefinedPixelTrait; jng_alpha_sample_depth = 0; jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000; jng_alpha_compression_method=image->compression==JPEGCompression? 8 : 0; jng_alpha_quality=image_info->quality == 0UL ? 75UL : image_info->quality; if (jng_alpha_quality >= 1000) jng_alpha_quality /= 1000; length=0; if (transparent != 0) { jng_color_type=14; /* Create JPEG blob, image, and image_info */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info for alpha."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=SeparateImage(image,AlphaChannel,exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); jpeg_image->alpha_trait=UndefinedPixelTrait; jpeg_image->quality=jng_alpha_quality; jpeg_image_info->type=GrayscaleType; (void) SetImageType(jpeg_image,GrayscaleType,exception); (void) AcquireUniqueFilename(jpeg_image->filename); (void) FormatLocaleString(jpeg_image_info->filename,MagickPathExtent, "%s",jpeg_image->filename); } else { jng_alpha_compression_method=0; jng_color_type=10; jng_alpha_sample_depth=0; } /* To do: check bit depth of PNG alpha channel */ /* Check if image is grayscale. */ if (image_info->type != TrueColorAlphaType && image_info->type != TrueColorType && SetImageGray(image,exception)) jng_color_type-=2; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Quality = %d",(int) jng_quality); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Color Type = %d",jng_color_type); if (transparent != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Compression = %d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Depth = %d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Quality = %d",(int) jng_alpha_quality); } } if (transparent != 0) { if (jng_alpha_compression_method==0) { const char *value; /* Encode alpha as a grayscale PNG blob */ status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating PNG blob."); (void) CopyMagickString(jpeg_image_info->magick,"PNG", MagickPathExtent); (void) CopyMagickString(jpeg_image->magick,"PNG",MagickPathExtent); jpeg_image_info->interlace=NoInterlace; /* Exclude all ancillary chunks */ (void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all"); blob=(unsigned char *) ImageToBlob(jpeg_image_info,jpeg_image, &length,exception); /* Retrieve sample depth used */ value=GetImageProperty(jpeg_image,"png:bit-depth-written",exception); if (value != (char *) NULL) jng_alpha_sample_depth= (unsigned int) value[0]; } else { /* Encode alpha as a grayscale JPEG blob */ status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image_info->magick,"JPEG", MagickPathExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); jpeg_image_info->interlace=NoInterlace; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=(unsigned char *) ImageToBlob(jpeg_image_info, jpeg_image,&length, exception); jng_alpha_sample_depth=8; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); } /* Destroy JPEG image and image_info */ jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); jpeg_image_info=DestroyImageInfo(jpeg_image_info); } /* Write JHDR chunk */ (void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */ PNGType(chunk,mng_JHDR); LogPNGChunk(logging,mng_JHDR,16L); PNGLong(chunk+4,(png_uint_32) image->columns); PNGLong(chunk+8,(png_uint_32) image->rows); chunk[12]=jng_color_type; chunk[13]=8; /* sample depth */ chunk[14]=8; /*jng_image_compression_method */ chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8); chunk[16]=jng_alpha_sample_depth; chunk[17]=jng_alpha_compression_method; chunk[18]=0; /*jng_alpha_filter_method */ chunk[19]=0; /*jng_alpha_interlace_method */ (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width:%15lu",(unsigned long) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG height:%14lu",(unsigned long) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG color type:%10d",jng_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG sample depth:%8d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG compression:%9d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG interlace:%11d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha depth:%9d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha compression:%3d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha filter:%8d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha interlace:%5d",0); } /* Write any JNG-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-b",logging); /* Write leading ancillary chunks */ if (transparent != 0) { /* Write JNG bKGD chunk */ unsigned char blue, green, red; ssize_t num_bytes; if (jng_color_type == 8 || jng_color_type == 12) num_bytes=6L; else num_bytes=10L; (void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L)); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L)); red=ScaleQuantumToChar(image->background_color.red); green=ScaleQuantumToChar(image->background_color.green); blue=ScaleQuantumToChar(image->background_color.blue); *(chunk+4)=0; *(chunk+5)=red; *(chunk+6)=0; *(chunk+7)=green; *(chunk+8)=0; *(chunk+9)=blue; (void) WriteBlob(image,(size_t) num_bytes,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes)); } if ((image->colorspace == sRGBColorspace || image->rendering_intent)) { /* Write JNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { if (image->gamma != 0.0) { /* Write JNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); } if ((mng_info->equal_chrms == MagickFalse) && (image->chromaticity.red_primary.x != 0.0)) { PrimaryInfo primary; /* Write JNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); } } if (image->resolution.x && image->resolution.y && !mng_info->equal_physs) { /* Write JNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->resolution.x+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.x || image->page.y)) { /* Write JNG oFFs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_oFFs); LogPNGChunk(logging,mng_oFFs,9L); PNGsLong(chunk+4,(ssize_t) (image->page.x)); PNGsLong(chunk+8,(ssize_t) (image->page.y)); chunk[12]=0; (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.width || image->page.height)) { (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (transparent != 0) { if (jng_alpha_compression_method==0) { register ssize_t i; size_t len; /* Write IDAT chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write IDAT chunks from blob, length=%.20g.",(double) length); /* Copy IDAT chunks */ len=0; p=blob+8; for (i=8; i<(ssize_t) length; i+=len+12) { len=(size_t) (*p) << 24; len|=(size_t) (*(p+1)) << 16; len|=(size_t) (*(p+2)) << 8; len|=(size_t) (*(p+3)); p+=4; if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */ { /* Found an IDAT chunk. */ (void) WriteBlobMSBULong(image,len); LogPNGChunk(logging,mng_IDAT,len); (void) WriteBlob(image,len+4,p); (void) WriteBlobMSBULong(image, crc32(0,p,(uInt) len+4)); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping %c%c%c%c chunk, length=%.20g.", *(p),*(p+1),*(p+2),*(p+3),(double) len); } p+=(8+len); } } else if (length != 0) { /* Write JDAA chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAA chunk, length=%.20g.",(double) length); (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAA); LogPNGChunk(logging,mng_JDAA,length); /* Write JDAT chunk(s) data */ (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob, (uInt) length)); } blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Encode image as a JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); (void) AcquireUniqueFilename(jpeg_image->filename); (void) FormatLocaleString(jpeg_image_info->filename,MagickPathExtent,"%s", jpeg_image->filename); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns, (double) jpeg_image->rows); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (jng_color_type == 8 || jng_color_type == 12) jpeg_image_info->type=GrayscaleType; jpeg_image_info->quality=jng_quality; jpeg_image->quality=jng_quality; (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MagickPathExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=(unsigned char *) ImageToBlob(jpeg_image_info,jpeg_image,&length, exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAT chunk, length=%.20g.",(double) length); } /* Write JDAT chunk(s) */ (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAT); LogPNGChunk(logging,mng_JDAT,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length)); jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); jpeg_image_info=DestroyImageInfo(jpeg_image_info); blob=(unsigned char *) RelinquishMagickMemory(blob); /* Write any JNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-e",logging); /* Write IEND chunk */ (void) WriteBlobMSBULong(image,0L); PNGType(chunk,mng_IEND); LogPNGChunk(logging,mng_IEND,0); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOneJNGImage()"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJNGImage() writes a JPEG Network Graphics (JNG) image file. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteJNGImage method is: % % MagickBooleanType WriteJNGImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WriteJNGImage(const ImageInfo *image_info, Image *image, ExceptionInfo *exception) { MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; (void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n"); status=WriteOneJNGImage(mng_info,image_info,image,exception); mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); (void) CatchImageException(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteJNGImage()"); return(status); } #endif static MagickBooleanType WriteMNGImage(const ImageInfo *image_info, Image *image, ExceptionInfo *exception) { Image *next_image; MagickBooleanType status; volatile MagickBooleanType logging; MngInfo *mng_info; int image_count, need_iterations, need_matte; volatile int #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) need_local_plte, #endif all_images_are_gray, need_defi, use_global_plte; register ssize_t i; unsigned char chunk[800]; volatile unsigned int write_jng, write_mng; volatile size_t scene; size_t final_delay=0, initial_delay; #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; write_mng=LocaleCompare(image_info->magick,"MNG") == 0; /* * See if user has requested a specific PNG subformat to be used * for all of the PNGs in the MNG being written, e.g., * * convert *.png png8:animation.mng * * To do: check -define png:bit_depth and png:color_type as well, * or perhaps use mng:bit_depth and mng:color_type instead for * global settings. */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; write_jng=MagickFalse; if (image_info->compression == JPEGCompression) write_jng=MagickTrue; mng_info->adjoin=image_info->adjoin && (GetNextImageInList(image) != (Image *) NULL) && write_mng; if (logging != MagickFalse) { /* Log some info about the input */ Image *p; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Checking input image(s)\n" " Image_info depth: %.20g, Type: %d", (double) image_info->depth, image_info->type); scene=0; for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scene: %.20g\n, Image depth: %.20g", (double) scene++, (double) p->depth); if (p->alpha_trait != UndefinedPixelTrait) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: False"); if (p->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: PseudoClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: DirectClass"); if (p->colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) p->colors); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: unspecified"); if (mng_info->adjoin == MagickFalse) break; } } use_global_plte=MagickFalse; all_images_are_gray=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_defi=MagickFalse; need_matte=MagickFalse; mng_info->framing_mode=1; mng_info->old_framing_mode=1; if (write_mng) if (image_info->page != (char *) NULL) { /* Determine image bounding box. */ SetGeometry(image,&mng_info->page); (void) ParseMetaGeometry(image_info->page,&mng_info->page.x, &mng_info->page.y,&mng_info->page.width,&mng_info->page.height); } if (write_mng) { unsigned int need_geom; unsigned short red, green, blue; const char * option; mng_info->page=image->page; need_geom=MagickTrue; if (mng_info->page.width || mng_info->page.height) need_geom=MagickFalse; /* Check all the scenes. */ initial_delay=image->delay; need_iterations=MagickFalse; mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0; mng_info->equal_physs=MagickTrue, mng_info->equal_gammas=MagickTrue; mng_info->equal_srgbs=MagickTrue; mng_info->equal_backgrounds=MagickTrue; image_count=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) all_images_are_gray=MagickTrue; mng_info->equal_palettes=MagickFalse; need_local_plte=MagickFalse; #endif for (next_image=image; next_image != (Image *) NULL; ) { if (need_geom) { if ((next_image->columns+next_image->page.x) > mng_info->page.width) mng_info->page.width=next_image->columns+next_image->page.x; if ((next_image->rows+next_image->page.y) > mng_info->page.height) mng_info->page.height=next_image->rows+next_image->page.y; } if (next_image->page.x || next_image->page.y) need_defi=MagickTrue; if (next_image->alpha_trait != UndefinedPixelTrait) need_matte=MagickTrue; if ((int) next_image->dispose >= BackgroundDispose) if ((next_image->alpha_trait != UndefinedPixelTrait) || next_image->page.x || next_image->page.y || ((next_image->columns < mng_info->page.width) && (next_image->rows < mng_info->page.height))) mng_info->need_fram=MagickTrue; if (next_image->iterations) need_iterations=MagickTrue; final_delay=next_image->delay; if (final_delay != initial_delay || final_delay > 1UL* next_image->ticks_per_second) mng_info->need_fram=1; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* check for global palette possibility. */ if (image->alpha_trait != UndefinedPixelTrait) need_local_plte=MagickTrue; if (need_local_plte == 0) { if (SetImageGray(image,exception) == MagickFalse) all_images_are_gray=MagickFalse; mng_info->equal_palettes=PalettesAreEqual(image,next_image); if (use_global_plte == 0) use_global_plte=mng_info->equal_palettes; need_local_plte=!mng_info->equal_palettes; } #endif if (GetNextImageInList(next_image) != (Image *) NULL) { if (next_image->background_color.red != next_image->next->background_color.red || next_image->background_color.green != next_image->next->background_color.green || next_image->background_color.blue != next_image->next->background_color.blue) mng_info->equal_backgrounds=MagickFalse; if (next_image->gamma != next_image->next->gamma) mng_info->equal_gammas=MagickFalse; if (next_image->rendering_intent != next_image->next->rendering_intent) mng_info->equal_srgbs=MagickFalse; if ((next_image->units != next_image->next->units) || (next_image->resolution.x != next_image->next->resolution.x) || (next_image->resolution.y != next_image->next->resolution.y)) mng_info->equal_physs=MagickFalse; if (mng_info->equal_chrms) { if (next_image->chromaticity.red_primary.x != next_image->next->chromaticity.red_primary.x || next_image->chromaticity.red_primary.y != next_image->next->chromaticity.red_primary.y || next_image->chromaticity.green_primary.x != next_image->next->chromaticity.green_primary.x || next_image->chromaticity.green_primary.y != next_image->next->chromaticity.green_primary.y || next_image->chromaticity.blue_primary.x != next_image->next->chromaticity.blue_primary.x || next_image->chromaticity.blue_primary.y != next_image->next->chromaticity.blue_primary.y || next_image->chromaticity.white_point.x != next_image->next->chromaticity.white_point.x || next_image->chromaticity.white_point.y != next_image->next->chromaticity.white_point.y) mng_info->equal_chrms=MagickFalse; } } image_count++; next_image=GetNextImageInList(next_image); } if (image_count < 2) { mng_info->equal_backgrounds=MagickFalse; mng_info->equal_chrms=MagickFalse; mng_info->equal_gammas=MagickFalse; mng_info->equal_srgbs=MagickFalse; mng_info->equal_physs=MagickFalse; use_global_plte=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_iterations=MagickFalse; } if (mng_info->need_fram == MagickFalse) { /* Only certain framing rates 100/n are exactly representable without the FRAM chunk but we'll allow some slop in VLC files */ if (final_delay == 0) { if (need_iterations != MagickFalse) { /* It's probably a GIF with loop; don't run it *too* fast. */ if (mng_info->adjoin) { final_delay=10; (void) ThrowMagickException(exception,GetMagickModule(), CoderWarning, "input has zero delay between all frames; assuming", " 10 cs `%s'",""); } } else mng_info->ticks_per_second=0; } if (final_delay != 0) mng_info->ticks_per_second=(png_uint_32) (image->ticks_per_second/final_delay); if (final_delay > 50) mng_info->ticks_per_second=2; if (final_delay > 75) mng_info->ticks_per_second=1; if (final_delay > 125) mng_info->need_fram=MagickTrue; if (need_defi && final_delay > 2 && (final_delay != 4) && (final_delay != 5) && (final_delay != 10) && (final_delay != 20) && (final_delay != 25) && (final_delay != 50) && (final_delay != (size_t) image->ticks_per_second)) mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */ } if (mng_info->need_fram != MagickFalse) mng_info->ticks_per_second=image->ticks_per_second; /* If pseudocolor, we should also check to see if all the palettes are identical and write a global PLTE if they are. ../glennrp Feb 99. */ /* Write the MNG version 1.0 signature and MHDR chunk. */ (void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n"); (void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */ PNGType(chunk,mng_MHDR); LogPNGChunk(logging,mng_MHDR,28L); PNGLong(chunk+4,(png_uint_32) mng_info->page.width); PNGLong(chunk+8,(png_uint_32) mng_info->page.height); PNGLong(chunk+12,mng_info->ticks_per_second); PNGLong(chunk+16,0L); /* layer count=unknown */ PNGLong(chunk+20,0L); /* frame count=unknown */ PNGLong(chunk+24,0L); /* play time=unknown */ if (write_jng) { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,27L); /* simplicity=LC+JNG */ else PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */ else PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */ } } else { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,11L); /* simplicity=LC */ else PNGLong(chunk+28,9L); /* simplicity=VLC */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */ else PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */ } } (void) WriteBlob(image,32,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,32)); option=GetImageOption(image_info,"mng:need-cacheoff"); if (option != (const char *) NULL) { size_t length; /* Write "nEED CACHEOFF" to turn playback caching off for streaming MNG. */ PNGType(chunk,mng_nEED); length=CopyMagickString((char *) chunk+4,"CACHEOFF",20); (void) WriteBlobMSBULong(image,(size_t) length); LogPNGChunk(logging,mng_nEED,(size_t) length); length+=4; (void) WriteBlob(image,length,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length)); } if ((GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) != (Image *) NULL) && (image->iterations != 1)) { /* Write MNG TERM chunk */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_TERM); LogPNGChunk(logging,mng_TERM,10L); chunk[4]=3; /* repeat animation */ chunk[5]=0; /* show last frame when done */ PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) PNGLong(chunk+10,PNG_UINT_31_MAX); else PNGLong(chunk+10,(png_uint_32) image->iterations); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM delay: %.20g",(double) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM iterations: %.20g",(double) PNG_UINT_31_MAX); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image iterations: %.20g",(double) image->iterations); } (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); } /* To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if ((image->colorspace == sRGBColorspace || image->rendering_intent) && mng_info->equal_srgbs) { /* Write MNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); mng_info->have_write_global_srgb=MagickTrue; } else { if (image->gamma && mng_info->equal_gammas) { /* Write MNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); mng_info->have_write_global_gama=MagickTrue; } if (mng_info->equal_chrms) { PrimaryInfo primary; /* Write MNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); mng_info->have_write_global_chrm=MagickTrue; } } if (image->resolution.x && image->resolution.y && mng_info->equal_physs) { /* Write MNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->resolution.x+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } /* Write MNG BACK chunk and global bKGD chunk, if the image is transparent or does not cover the entire frame. */ if (write_mng && ((image->alpha_trait != UndefinedPixelTrait) || image->page.x > 0 || image->page.y > 0 || (image->page.width && (image->page.width+image->page.x < mng_info->page.width)) || (image->page.height && (image->page.height+image->page.y < mng_info->page.height)))) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_BACK); LogPNGChunk(logging,mng_BACK,6L); red=ScaleQuantumToShort(image->background_color.red); green=ScaleQuantumToShort(image->background_color.green); blue=ScaleQuantumToShort(image->background_color.blue); PNGShort(chunk+4,red); PNGShort(chunk+6,green); PNGShort(chunk+8,blue); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); if (mng_info->equal_backgrounds) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,6L); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); } } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if ((need_local_plte == MagickFalse) && (image->storage_class == PseudoClass) && (all_images_are_gray == MagickFalse)) { size_t data_length; /* Write MNG PLTE chunk */ data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=(unsigned char) (ScaleQuantumToChar( image->colormap[i].red) & 0xff); chunk[5+i*3]=(unsigned char) (ScaleQuantumToChar( image->colormap[i].green) & 0xff); chunk[6+i*3]=(unsigned char) (ScaleQuantumToChar( image->colormap[i].blue) & 0xff); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } #endif } scene=0; mng_info->delay=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) mng_info->equal_palettes=MagickFalse; #endif do { if (mng_info->adjoin) { #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* If we aren't using a global palette for the entire MNG, check to see if we can use one for two or more consecutive images. */ if (need_local_plte && use_global_plte && !all_images_are_gray) { if (mng_info->IsPalette) { /* When equal_palettes is true, this image has the same palette as the previous PseudoClass image */ mng_info->have_write_global_plte=mng_info->equal_palettes; mng_info->equal_palettes=PalettesAreEqual(image,image->next); if (mng_info->equal_palettes && !mng_info->have_write_global_plte) { /* Write MNG PLTE chunk */ size_t data_length; data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red); chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green); chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk, (uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } } else mng_info->have_write_global_plte=MagickFalse; } #endif if (need_defi) { ssize_t previous_x, previous_y; if (scene) { previous_x=mng_info->page.x; previous_y=mng_info->page.y; } else { previous_x=0; previous_y=0; } mng_info->page=image->page; if ((mng_info->page.x != previous_x) || (mng_info->page.y != previous_y)) { (void) WriteBlobMSBULong(image,12L); /* data length=12 */ PNGType(chunk,mng_DEFI); LogPNGChunk(logging,mng_DEFI,12L); chunk[4]=0; /* object 0 MSB */ chunk[5]=0; /* object 0 LSB */ chunk[6]=0; /* visible */ chunk[7]=0; /* abstract */ PNGLong(chunk+8,(png_uint_32) mng_info->page.x); PNGLong(chunk+12,(png_uint_32) mng_info->page.y); (void) WriteBlob(image,16,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,16)); } } } mng_info->write_mng=write_mng; if ((int) image->dispose >= 3) mng_info->framing_mode=3; if (mng_info->need_fram && mng_info->adjoin && ((image->delay != mng_info->delay) || (mng_info->framing_mode != mng_info->old_framing_mode))) { if (image->delay == mng_info->delay) { /* Write a MNG FRAM chunk with the new framing mode. */ (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,1L); chunk[4]=(unsigned char) mng_info->framing_mode; (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { /* Write a MNG FRAM chunk with the delay. */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,10L); chunk[4]=(unsigned char) mng_info->framing_mode; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=2; /* flag for changing default delay */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=0; /* flag for changing frame clipping */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) ((mng_info->ticks_per_second* image->delay)/MagickMax(image->ticks_per_second,1))); (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); mng_info->delay=(png_uint_32) image->delay; } mng_info->old_framing_mode=mng_info->framing_mode; } #if defined(JNG_SUPPORTED) if (image_info->compression == JPEGCompression) { ImageInfo *write_info; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing JNG object."); /* To do: specify the desired alpha compression method. */ write_info=CloneImageInfo(image_info); write_info->compression=UndefinedCompression; status=WriteOneJNGImage(mng_info,write_info,image,exception); write_info=DestroyImageInfo(write_info); } else #endif { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG object."); mng_info->need_blob = MagickFalse; mng_info->ping_preserve_colormap = MagickFalse; /* We don't want any ancillary chunks written */ mng_info->ping_exclude_bKGD=MagickTrue; mng_info->ping_exclude_caNv=MagickTrue; mng_info->ping_exclude_cHRM=MagickTrue; mng_info->ping_exclude_date=MagickTrue; mng_info->ping_exclude_EXIF=MagickTrue; mng_info->ping_exclude_gAMA=MagickTrue; mng_info->ping_exclude_iCCP=MagickTrue; /* mng_info->ping_exclude_iTXt=MagickTrue; */ mng_info->ping_exclude_oFFs=MagickTrue; mng_info->ping_exclude_pHYs=MagickTrue; mng_info->ping_exclude_sRGB=MagickTrue; mng_info->ping_exclude_tEXt=MagickTrue; mng_info->ping_exclude_tRNS=MagickTrue; mng_info->ping_exclude_vpAg=MagickTrue; mng_info->ping_exclude_zCCP=MagickTrue; mng_info->ping_exclude_zTXt=MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image,exception); } if (status == MagickFalse) { mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); return(MagickFalse); } (void) CatchImageException(image); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (mng_info->adjoin); if (write_mng) { while (GetPreviousImageInList(image) != (Image *) NULL) image=GetPreviousImageInList(image); /* Write the MEND chunk. */ (void) WriteBlobMSBULong(image,0x00000000L); PNGType(chunk,mng_MEND); LogPNGChunk(logging,mng_MEND,0L); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); } /* Relinquish resources. */ (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()"); return(MagickTrue); } #else /* PNG_LIBPNG_VER > 10011 */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info, Image *image) { (void) image; printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); ThrowBinaryException(CoderError,"PNG library is too old", image_info->filename); } static MagickBooleanType WriteMNGImage(const ImageInfo *image_info, Image *image) { return(WritePNGImage(image_info,image)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif
./CrossVul/dataset_final_sorted/CWE-772/c/good_2567_1
crossvul-cpp_data_bad_3103_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M PPPP CCCC % % MM MM P P C % % M M M PPPP C % % M M P C % % M M P CCCC % % % % % % Read/Write Magick Persistant Cache Image Format % % % % Software Design % % Cristy % % March 2000 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/constitute.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/hashmap.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/utility.h" #include "magick/version-private.h" /* Forward declarations. */ static MagickBooleanType WriteMPCImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M P C % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMPC() returns MagickTrue if the image format type, identified by the % magick string, is an Magick Persistent Cache image. % % The format of the IsMPC method is: % % MagickBooleanType IsMPC(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsMPC(const unsigned char *magick,const size_t length) { if (length < 14) return(MagickFalse); if (LocaleNCompare((const char *) magick,"id=MagickCache",14) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d C A C H E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMPCImage() reads an Magick Persistent Cache image file and returns % it. It allocates the memory necessary for the new Image structure and % returns a pointer to the new image. % % The format of the ReadMPCImage method is: % % Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) % % Decompression code contributed by Kyle Shorter. % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) { char cache_filename[MaxTextExtent], id[MaxTextExtent], keyword[MaxTextExtent], *options; const unsigned char *p; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; MagickBooleanType status; MagickOffsetType offset; MagickStatusType flags; register ssize_t i; size_t depth, length; ssize_t count; StringInfo *profile; unsigned int signature; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(cache_filename,image->filename,MaxTextExtent); AppendImageFormat("cache",cache_filename); c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } *id='\0'; (void) ResetMagickMemory(keyword,0,sizeof(keyword)); offset=0; do { /* Decode image header; header terminates one character beyond a ':'. */ profiles=(LinkedListInfo *) NULL; length=MaxTextExtent; options=AcquireString((char *) NULL); signature=GetMagickSignature((const StringInfo *) NULL); image->depth=8; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if (c == (int) '\\') c=ReadBlobByte(image); else if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ length=MaxTextExtent; p=keyword; do { if (c == (int) '=') break; if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MaxTextExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } *p++=(char) c; c=ReadBlobByte(image); if (c == '\\') { c=ReadBlobByte(image); if (c == (int) '}') { *p++=(char) c; c=ReadBlobByte(image); } } if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,strlen(options)); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorDatabase(options,&image->background_color, exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorDatabase(options,&image->border_color, exception); break; } (void) SetImageProperty(image,keyword,options); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { ssize_t storage_class; storage_class=ParseCommandOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { image->colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { ssize_t endian; endian=ParseCommandOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } if (LocaleCompare(keyword,"error") == 0) { image->error.mean_error_per_pixel=StringToDouble(options, (char **) NULL); break; } (void) SetImageProperty(image,keyword,options); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options,(char **) NULL); break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MaxTextExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"magick-signature") == 0) { signature=(unsigned int) StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"matte") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"matte-color") == 0) { (void) QueryColorDatabase(options,&image->matte_color, exception); break; } if (LocaleCompare(keyword,"maximum-error") == 0) { image->error.normalized_maximum_error=StringToDouble( options,(char **) NULL); break; } if (LocaleCompare(keyword,"mean-error") == 0) { image->error.normalized_mean_error=StringToDouble(options, (char **) NULL); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'o': case 'O': { if (LocaleCompare(keyword,"opaque") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"orientation") == 0) { ssize_t orientation; orientation=ParseCommandOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"pixel-intensity") == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,options); if (intensity < 0) break; image->intensity=(PixelIntensityMethod) intensity; break; } if ((LocaleNCompare(keyword,"profile:",8) == 0) || (LocaleNCompare(keyword,"profile-",8) == 0)) { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(keyword+8)); profile=BlobToStringInfo((const void *) NULL,(size_t) StringToLong(options)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); (void) SetImageProfile(image,keyword+8,profile); profile=DestroyStringInfo(profile); break; } (void) SetImageProperty(image,keyword,options); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; if ((flags & SigmaValue) != 0) image->chromaticity.red_primary.y=geometry_info.sigma; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(ssize_t) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } if (LocaleCompare(keyword,"type") == 0) { ssize_t type; type=ParseCommandOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions,MagickFalse, options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options); break; } default: { (void) SetImageProperty(image,keyword,options); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"MagickCache") != 0) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (signature != GetMagickSignature((const StringInfo *) NULL)) ThrowReaderException(CacheError,"IncompatibleAPI"); if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MaxTextExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MaxTextExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MaxTextExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; const StringInfo *profile; register unsigned char *p; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); (void) ReadBlob(image,GetStringInfoLength(profile),p); } name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { /* Create image colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->colors != 0) { size_t packet_size; unsigned char *colormap; /* Read image colormap from file. */ packet_size=(size_t) (3UL*depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); if (count != (ssize_t) (packet_size*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=colormap; switch (depth) { default: ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned int pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Attach persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception); if (status == MagickFalse) ThrowReaderException(CacheError,"UnableToPersistPixelCache"); /* Proceed to next image. */ do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (c != EOF); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M P C I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterMPCImage() adds properties for the Cache image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterMPCImage method is: % % size_t RegisterMPCImage(void) % */ ModuleExport size_t RegisterMPCImage(void) { MagickInfo *entry; entry=SetMagickInfo("CACHE"); entry->description=ConstantString("Magick Persistent Cache image format"); entry->module=ConstantString("MPC"); entry->stealth=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("MPC"); entry->decoder=(DecodeImageHandler *) ReadMPCImage; entry->encoder=(EncodeImageHandler *) WriteMPCImage; entry->magick=(IsImageFormatHandler *) IsMPC; entry->description=ConstantString("Magick Persistent Cache image format"); entry->module=ConstantString("MPC"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M P C I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterMPCImage() removes format registrations made by the % MPC module from the list of supported formats. % % The format of the UnregisterMPCImage method is: % % UnregisterMPCImage(void) % */ ModuleExport void UnregisterMPCImage(void) { (void) UnregisterMagickInfo("CACHE"); (void) UnregisterMagickInfo("MPC"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M P C I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMPCImage() writes an Magick Persistent Cache image to a file. % % The format of the WriteMPCImage method is: % % MagickBooleanType WriteMPCImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % */ static MagickBooleanType WriteMPCImage(const ImageInfo *image_info,Image *image) { char buffer[MaxTextExtent], cache_filename[MaxTextExtent]; const char *property, *value; MagickBooleanType status; MagickOffsetType offset, scene; register ssize_t i; size_t depth, one; /* Open persistent cache. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) CopyMagickString(cache_filename,image->filename,MaxTextExtent); AppendImageFormat("cache",cache_filename); scene=0; offset=0; one=1; do { /* Write persistent cache meta-information. */ depth=GetImageQuantumDepth(image,MagickTrue); if ((image->storage_class == PseudoClass) && (image->colors > (one << depth))) image->storage_class=DirectClass; (void) WriteBlobString(image,"id=MagickCache\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"magick-signature=%u\n", GetMagickSignature((const StringInfo *) NULL)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "class=%s colors=%.20g matte=%s\n",CommandOptionToMnemonic( MagickClassOptions,image->storage_class),(double) image->colors, CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) image->matte)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "columns=%.20g rows=%.20g depth=%.20g\n",(double) image->columns, (double) image->rows,(double) image->depth); (void) WriteBlobString(image,buffer); if (image->type != UndefinedType) { (void) FormatLocaleString(buffer,MaxTextExtent,"type=%s\n", CommandOptionToMnemonic(MagickTypeOptions,image->type)); (void) WriteBlobString(image,buffer); } if (image->colorspace != UndefinedColorspace) { (void) FormatLocaleString(buffer,MaxTextExtent,"colorspace=%s\n", CommandOptionToMnemonic(MagickColorspaceOptions,image->colorspace)); (void) WriteBlobString(image,buffer); } if (image->intensity != UndefinedPixelIntensityMethod) { (void) FormatLocaleString(buffer,MaxTextExtent,"pixel-intensity=%s\n", CommandOptionToMnemonic(MagickPixelIntensityOptions, image->intensity)); (void) WriteBlobString(image,buffer); } if (image->endian != UndefinedEndian) { (void) FormatLocaleString(buffer,MaxTextExtent,"endian=%s\n", CommandOptionToMnemonic(MagickEndianOptions,image->endian)); (void) WriteBlobString(image,buffer); } if (image->compression != UndefinedCompression) { (void) FormatLocaleString(buffer,MaxTextExtent, "compression=%s quality=%.20g\n",CommandOptionToMnemonic( MagickCompressOptions,image->compression),(double) image->quality); (void) WriteBlobString(image,buffer); } if (image->units != UndefinedResolution) { (void) FormatLocaleString(buffer,MaxTextExtent,"units=%s\n", CommandOptionToMnemonic(MagickResolutionOptions,image->units)); (void) WriteBlobString(image,buffer); } if ((image->x_resolution != 0) || (image->y_resolution != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent, "resolution=%gx%g\n",image->x_resolution,image->y_resolution); (void) WriteBlobString(image,buffer); } if ((image->page.width != 0) || (image->page.height != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent, "page=%.20gx%.20g%+.20g%+.20g\n",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); (void) WriteBlobString(image,buffer); } else if ((image->page.x != 0) || (image->page.y != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent,"page=%+ld%+ld\n", (long) image->page.x,(long) image->page.y); (void) WriteBlobString(image,buffer); } if ((image->tile_offset.x != 0) || (image->tile_offset.y != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent,"tile-offset=%+ld%+ld\n", (long) image->tile_offset.x,(long) image->tile_offset.y); (void) WriteBlobString(image,buffer); } if ((GetNextImageInList(image) != (Image *) NULL) || (GetPreviousImageInList(image) != (Image *) NULL)) { if (image->scene == 0) (void) FormatLocaleString(buffer,MaxTextExtent, "iterations=%.20g delay=%.20g ticks-per-second=%.20g\n",(double) image->iterations,(double) image->delay,(double) image->ticks_per_second); else (void) FormatLocaleString(buffer,MaxTextExtent,"scene=%.20g " "iterations=%.20g delay=%.20g ticks-per-second=%.20g\n", (double) image->scene,(double) image->iterations,(double) image->delay,(double) image->ticks_per_second); (void) WriteBlobString(image,buffer); } else { if (image->scene != 0) { (void) FormatLocaleString(buffer,MaxTextExtent,"scene=%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); } if (image->iterations != 0) { (void) FormatLocaleString(buffer,MaxTextExtent,"iterations=%.20g\n", (double) image->iterations); (void) WriteBlobString(image,buffer); } if (image->delay != 0) { (void) FormatLocaleString(buffer,MaxTextExtent,"delay=%.20g\n", (double) image->delay); (void) WriteBlobString(image,buffer); } if (image->ticks_per_second != UndefinedTicksPerSecond) { (void) FormatLocaleString(buffer,MaxTextExtent, "ticks-per-second=%.20g\n",(double) image->ticks_per_second); (void) WriteBlobString(image,buffer); } } if (image->gravity != UndefinedGravity) { (void) FormatLocaleString(buffer,MaxTextExtent,"gravity=%s\n", CommandOptionToMnemonic(MagickGravityOptions,image->gravity)); (void) WriteBlobString(image,buffer); } if (image->dispose != UndefinedDispose) { (void) FormatLocaleString(buffer,MaxTextExtent,"dispose=%s\n", CommandOptionToMnemonic(MagickDisposeOptions,image->dispose)); (void) WriteBlobString(image,buffer); } if (image->rendering_intent != UndefinedIntent) { (void) FormatLocaleString(buffer,MaxTextExtent, "rendering-intent=%s\n",CommandOptionToMnemonic(MagickIntentOptions, image->rendering_intent)); (void) WriteBlobString(image,buffer); } if (image->gamma != 0.0) { (void) FormatLocaleString(buffer,MaxTextExtent,"gamma=%g\n", image->gamma); (void) WriteBlobString(image,buffer); } if (image->chromaticity.white_point.x != 0.0) { /* Note chomaticity points. */ (void) FormatLocaleString(buffer,MaxTextExtent,"red-primary=" "%g,%g green-primary=%g,%g blue-primary=%g,%g\n", image->chromaticity.red_primary.x,image->chromaticity.red_primary.y, image->chromaticity.green_primary.x, image->chromaticity.green_primary.y, image->chromaticity.blue_primary.x, image->chromaticity.blue_primary.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "white-point=%g,%g\n",image->chromaticity.white_point.x, image->chromaticity.white_point.y); (void) WriteBlobString(image,buffer); } if (image->orientation != UndefinedOrientation) { (void) FormatLocaleString(buffer,MaxTextExtent, "orientation=%s\n",CommandOptionToMnemonic(MagickOrientationOptions, image->orientation)); (void) WriteBlobString(image,buffer); } if (image->profiles != (void *) NULL) { const char *name; const StringInfo *profile; /* Generic profile. */ ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent, "profile:%s=%.20g\n",name,(double) GetStringInfoLength(profile)); (void) WriteBlobString(image,buffer); } name=GetNextImageProfile(image); } } if (image->montage != (char *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent,"montage=%s\n", image->montage); (void) WriteBlobString(image,buffer); } ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s=",property); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,property); if (value != (const char *) NULL) { size_t length; length=strlen(value); for (i=0; i < (ssize_t) length; i++) if (isspace((int) ((unsigned char) value[i])) != 0) break; if ((i == (ssize_t) length) && (i != 0)) (void) WriteBlob(image,length,(const unsigned char *) value); else { (void) WriteBlobByte(image,'{'); if (strchr(value,'}') == (char *) NULL) (void) WriteBlob(image,length,(const unsigned char *) value); else for (i=0; i < (ssize_t) length; i++) { if (value[i] == (int) '}') (void) WriteBlobByte(image,'\\'); (void) WriteBlobByte(image,value[i]); } (void) WriteBlobByte(image,'}'); } } (void) WriteBlobByte(image,'\n'); property=GetNextImageProperty(image); } (void) WriteBlobString(image,"\f\n:\032"); if (image->montage != (char *) NULL) { /* Write montage tile directory. */ if (image->directory != (char *) NULL) (void) WriteBlobString(image,image->directory); (void) WriteBlobByte(image,'\0'); } if (image->profiles != 0) { const char *name; const StringInfo *profile; /* Write image profiles. */ ResetImageProfileIterator(image); name=GetNextImageProfile(image); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); name=GetNextImageProfile(image); } } if (image->storage_class == PseudoClass) { size_t packet_size; unsigned char *colormap, *q; /* Allocate colormap. */ packet_size=(size_t) (3UL*depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) return(MagickFalse); /* Write colormap to file. */ q=colormap; for (i=0; i < (ssize_t) image->colors; i++) { switch (depth) { default: ThrowWriterException(CorruptImageError,"ImageDepthNotSupported"); case 32: { unsigned int pixel; pixel=ScaleQuantumToLong(image->colormap[i].red); q=PopLongPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToLong(image->colormap[i].green); q=PopLongPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToLong(image->colormap[i].blue); q=PopLongPixel(MSBEndian,pixel,q); break; } case 16: { unsigned short pixel; pixel=ScaleQuantumToShort(image->colormap[i].red); q=PopShortPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToShort(image->colormap[i].green); q=PopShortPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToShort(image->colormap[i].blue); q=PopShortPixel(MSBEndian,pixel,q); break; } case 8: { unsigned char pixel; pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].red); q=PopCharPixel(pixel,q); pixel=(unsigned char) ScaleQuantumToChar( image->colormap[i].green); q=PopCharPixel(pixel,q); pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue); q=PopCharPixel(pixel,q); break; } } } (void) WriteBlob(image,packet_size*image->colors,colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); } /* Initialize persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickFalse,&offset, &image->exception); if (status == MagickFalse) ThrowWriterException(CacheError,"UnableToPersistPixelCache"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); if (image->progress_monitor != (MagickProgressMonitor) NULL) { status=image->progress_monitor(SaveImagesTag,scene, GetImageListLength(image),image->client_data); if (status == MagickFalse) break; } scene++; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_3103_1
crossvul-cpp_data_bad_2829_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Y Y YYYC BBBB YYYC RRRR % % Y Y C B B C R R % % Y C BBBB C RRRR % % Y C B B C R R % % Y YYYC BBBB YYYC R R % % % % % % Read/Write Raw YCbCr Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colorspace.h" #include "MagickCore/constitute.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/utility.h" /* Forward declarations. */ static MagickBooleanType WriteYCBCRImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d Y C b C r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadYCBCRImage() reads an image of raw YCbCr or YCbCrA samples and returns % it. It allocates the memory necessary for the new Image structure and % returns a pointer to the new image. % % The format of the ReadYCBCRImage method is: % % Image *ReadYCBCRImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadYCBCRImage(const ImageInfo *image_info, ExceptionInfo *exception) { const unsigned char *pixels; Image *canvas_image, *image; MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register const Quantum *p; register ssize_t i, x; register Quantum *q; size_t length; ssize_t count, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); SetImageColorspace(image,YCbCrColorspace,exception); if (image_info->interlace != PartitionInterlace) { status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Create virtual canvas to support cropping (i.e. image.rgb[100x100+10+20]). */ canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse, exception); (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod, exception); quantum_info=AcquireQuantumInfo(image_info,canvas_image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); quantum_type=RGBQuantum; if (LocaleCompare(image_info->magick,"YCbCrA") == 0) { quantum_type=RGBAQuantum; image->alpha_trait=BlendPixelTrait; } pixels=(const unsigned char *) NULL; if (image_info->number_scenes != 0) while (image->scene < image_info->scene) { /* Skip to next image. */ image->scene++; length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) break; } } count=0; length=0; scene=0; do { /* Read pixels to virtual canvas image then push to image. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { quantum_info=DestroyQuantumInfo(quantum_info); return(DestroyImageList(image)); } SetImageColorspace(image,YCbCrColorspace,exception); switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: YCbCrYCbCrYCbCrYCbCrYCbCrYCbCr... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=QueueAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,GetPixelRed(canvas_image,p),q); SetPixelGreen(image,GetPixelGreen(canvas_image,p),q); SetPixelBlue(image,GetPixelBlue(canvas_image,p),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,GetPixelAlpha(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } break; } case LineInterlace: { static QuantumType quantum_types[4] = { RedQuantum, GreenQuantum, BlueQuantum, OpacityQuantum }; /* Line interlacing: YYY...CbCbCb...CrCrCr...YYY...CbCbCb...CrCrCr... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { for (i=0; i < (image->alpha_trait != UndefinedPixelTrait ? 4 : 3); i++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } quantum_type=quantum_types[i]; q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { switch (quantum_type) { case RedQuantum: { SetPixelRed(image,GetPixelRed(canvas_image,p),q); break; } case GreenQuantum: { SetPixelGreen(image,GetPixelGreen(canvas_image,p),q); break; } case BlueQuantum: { SetPixelBlue(image,GetPixelBlue(canvas_image,p),q); break; } case OpacityQuantum: { SetPixelAlpha(image,GetPixelAlpha(canvas_image,p),q); break; } default: break; } p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: YYYYYY...CbCbCbCbCbCb...CrCrCrCrCrCr... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,GetPixelRed(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(image,GetPixelGreen(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,GetPixelBlue(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->alpha_trait != UndefinedPixelTrait) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(image,GetPixelAlpha(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: YYYYYY..., CbCbCbCbCbCb..., CrCrCrCrCrCr... */ AppendImageFormat("Y",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,GetPixelRed(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("Cb",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,GreenQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(image,GetPixelGreen(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("Cr",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,BlueQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,GetPixelBlue(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->alpha_trait != UndefinedPixelTrait) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); for (y=0; y < (ssize_t) image->extract_info.height; y++) { if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(image,GetPixelAlpha(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } } SetQuantumImageType(image,quantum_type); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (count == (ssize_t) length) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } scene++; } while (count == (ssize_t) length); quantum_info=DestroyQuantumInfo(quantum_info); canvas_image=DestroyImage(canvas_image); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r Y C b C r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterYCBCRImage() adds attributes for the YCbCr or YCbCrA image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterYCBCRImage method is: % % size_t RegisterYCBCRImage(void) % */ ModuleExport size_t RegisterYCBCRImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("YCbCr","YCbCr","Raw Y, Cb, and Cr samples"); entry->decoder=(DecodeImageHandler *) ReadYCBCRImage; entry->encoder=(EncodeImageHandler *) WriteYCBCRImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("YCbCr","YCbCrA","Raw Y, Cb, Cr, and alpha samples"); entry->decoder=(DecodeImageHandler *) ReadYCBCRImage; entry->encoder=(EncodeImageHandler *) WriteYCBCRImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r Y C b C r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterYCBCRImage() removes format registrations made by the % YCbCr module from the list of supported formats. % % The format of the UnregisterYCBCRImage method is: % % UnregisterYCBCRImage(void) % */ ModuleExport void UnregisterYCBCRImage(void) { (void) UnregisterMagickInfo("YCbCr"); (void) UnregisterMagickInfo("YCbCrA"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e Y C b C r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteYCBCRImage() writes an image to a file in the YCbCr or YCbCrA % rasterfile format. % % The format of the WriteYCBCRImage method is: % % MagickBooleanType WriteYCBCRImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteYCBCRImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register const Quantum *p; size_t length; ssize_t count, y; unsigned char *pixels; /* Allocate memory for pixels. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image_info->interlace != PartitionInterlace) { /* Open output image file. */ assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); } quantum_type=RGBQuantum; if (LocaleCompare(image_info->magick,"YCbCrA") == 0) { quantum_type=RGBAQuantum; image->alpha_trait=BlendPixelTrait; } scene=0; do { /* Convert MIFF to YCbCr raster pixels. */ if (image->colorspace != YCbCrColorspace) (void) TransformImageColorspace(image,YCbCrColorspace,exception); if ((LocaleCompare(image_info->magick,"YCbCrA") == 0) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetQuantumPixels(quantum_info); switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: YCbCrYCbCrYCbCrYCbCrYCbCrYCbCr... */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case LineInterlace: { /* Line interlacing: YYY...CbCbCb...CrCrCr...YYY...CbCbCb...CrCrCr... */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; if (quantum_type == RGBAQuantum) { length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, AlphaQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: YYYYYY...CbCbCbCbCbCb...CrCrCrCrCrCr... */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,1,5); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,2,5); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,3,5); if (status == MagickFalse) break; } if (quantum_type == RGBAQuantum) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, AlphaQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } } if (image_info->interlace == PartitionInterlace) (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,5,5); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: YYYYYY..., CbCbCbCbCbCb..., CrCrCrCrCrCr... */ AppendImageFormat("Y",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("Cb",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("Cr",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,3,5); if (status == MagickFalse) break; } if (quantum_type == RGBAQuantum) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, AlphaQuantum,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,4,5); if (status == MagickFalse) break; } } (void) CloseBlob(image); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,5,5); if (status == MagickFalse) break; } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2829_0
crossvul-cpp_data_good_1168_1
/** * FreeRDP: A Remote Desktop Protocol Implementation * * Copyright 2014 Thincast Technologies GmbH * Copyright 2014 Hardening <contact@hardening-consulting.com> * Copyright 2017 Armin Novak <armin.novak@thincast.com> * Copyright 2017 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <assert.h> #include <winpr/memory.h> #include <freerdp/log.h> #include <freerdp/codec/region.h> #define TAG FREERDP_TAG("codec") /* * The functions in this file implement the Region abstraction largely inspired from * pixman library. The following comment is taken from the pixman code. * * A Region is simply a set of disjoint(non-overlapping) rectangles, plus an * "extent" rectangle which is the smallest single rectangle that contains all * the non-overlapping rectangles. * * A Region is implemented as a "y-x-banded" array of rectangles. This array * imposes two degrees of order. First, all rectangles are sorted by top side * y coordinate first (y1), and then by left side x coordinate (x1). * * Furthermore, the rectangles are grouped into "bands". Each rectangle in a * band has the same top y coordinate (y1), and each has the same bottom y * coordinate (y2). Thus all rectangles in a band differ only in their left * and right side (x1 and x2). Bands are implicit in the array of rectangles: * there is no separate list of band start pointers. * * The y-x band representation does not minimize rectangles. In particular, * if a rectangle vertically crosses a band (the rectangle has scanlines in * the y1 to y2 area spanned by the band), then the rectangle may be broken * down into two or more smaller rectangles stacked one atop the other. * * ----------- ----------- * | | | | band 0 * | | -------- ----------- -------- * | | | | in y-x banded | | | | band 1 * | | | | form is | | | | * ----------- | | ----------- -------- * | | | | band 2 * -------- -------- * * An added constraint on the rectangles is that they must cover as much * horizontal area as possible: no two rectangles within a band are allowed * to touch. * * Whenever possible, bands will be merged together to cover a greater vertical * distance (and thus reduce the number of rectangles). Two bands can be merged * only if the bottom of one touches the top of the other and they have * rectangles in the same places (of the same width, of course). */ struct _REGION16_DATA { long size; long nbRects; }; static REGION16_DATA empty_region = { 0, 0 }; void region16_init(REGION16* region) { assert(region); ZeroMemory(region, sizeof(REGION16)); region->data = &empty_region; } int region16_n_rects(const REGION16* region) { assert(region); assert(region->data); return region->data->nbRects; } const RECTANGLE_16* region16_rects(const REGION16* region, UINT32* nbRects) { REGION16_DATA* data; if (nbRects) *nbRects = 0; if (!region) return NULL; data = region->data; if (!data) return NULL; if (nbRects) *nbRects = data->nbRects; return (RECTANGLE_16*)(data + 1); } static INLINE RECTANGLE_16* region16_rects_noconst(REGION16* region) { REGION16_DATA* data; data = region->data; if (!data) return NULL; return (RECTANGLE_16*)(&data[1]); } const RECTANGLE_16* region16_extents(const REGION16* region) { if (!region) return NULL; return &region->extents; } static RECTANGLE_16* region16_extents_noconst(REGION16* region) { if (!region) return NULL; return &region->extents; } BOOL rectangle_is_empty(const RECTANGLE_16* rect) { /* A rectangle with width = 0 or height = 0 should be regarded * as empty. */ return ((rect->left == rect->right) || (rect->top == rect->bottom)) ? TRUE : FALSE; } BOOL region16_is_empty(const REGION16* region) { assert(region); assert(region->data); return (region->data->nbRects == 0); } BOOL rectangles_equal(const RECTANGLE_16* r1, const RECTANGLE_16* r2) { return ((r1->left == r2->left) && (r1->top == r2->top) && (r1->right == r2->right) && (r1->bottom == r2->bottom)) ? TRUE : FALSE; } BOOL rectangles_intersects(const RECTANGLE_16* r1, const RECTANGLE_16* r2) { RECTANGLE_16 tmp; return rectangles_intersection(r1, r2, &tmp); } BOOL rectangles_intersection(const RECTANGLE_16* r1, const RECTANGLE_16* r2, RECTANGLE_16* dst) { dst->left = MAX(r1->left, r2->left); dst->right = MIN(r1->right, r2->right); dst->top = MAX(r1->top, r2->top); dst->bottom = MIN(r1->bottom, r2->bottom); return (dst->left < dst->right) && (dst->top < dst->bottom); } void region16_clear(REGION16* region) { assert(region); assert(region->data); if ((region->data->size > 0) && (region->data != &empty_region)) free(region->data); region->data = &empty_region; ZeroMemory(&region->extents, sizeof(region->extents)); } static INLINE REGION16_DATA* allocateRegion(long nbItems) { long allocSize = sizeof(REGION16_DATA) + (nbItems * sizeof(RECTANGLE_16)); REGION16_DATA* ret = (REGION16_DATA*) malloc(allocSize); if (!ret) return ret; ret->size = allocSize; ret->nbRects = nbItems; return ret; } BOOL region16_copy(REGION16* dst, const REGION16* src) { assert(dst); assert(dst->data); assert(src); assert(src->data); if (dst == src) return TRUE; dst->extents = src->extents; if ((dst->data->size > 0) && (dst->data != &empty_region)) free(dst->data); if (src->data->size == 0) dst->data = &empty_region; else { dst->data = allocateRegion(src->data->nbRects); if (!dst->data) return FALSE; CopyMemory(dst->data, src->data, src->data->size); } return TRUE; } void region16_print(const REGION16* region) { const RECTANGLE_16* rects; UINT32 nbRects, i; int currentBandY = -1; rects = region16_rects(region, &nbRects); WLog_DBG(TAG, "nrects=%"PRIu32"", nbRects); for (i = 0; i < nbRects; i++, rects++) { if (rects->top != currentBandY) { currentBandY = rects->top; WLog_DBG(TAG, "band %d: ", currentBandY); } WLog_DBG(TAG, "(%"PRIu16",%"PRIu16"-%"PRIu16",%"PRIu16")", rects->left, rects->top, rects->right, rects->bottom); } } static void region16_copy_band_with_union(RECTANGLE_16* dst, const RECTANGLE_16* src, const RECTANGLE_16* end, UINT16 newTop, UINT16 newBottom, const RECTANGLE_16* unionRect, UINT32* dstCounter, const RECTANGLE_16** srcPtr, RECTANGLE_16** dstPtr) { UINT16 refY = src->top; const RECTANGLE_16* startOverlap, *endOverlap; /* merges a band with the given rect * Input: * unionRect * | | * | | * ==============+===============+================================ * |Item1| |Item2| |Item3| |Item4| |Item5| Band * ==============+===============+================================ * before | overlap | after * * Resulting band: * +-----+ +----------------------+ +-----+ * |Item1| | Item2 | |Item3| * +-----+ +----------------------+ +-----+ * * We first copy as-is items that are before Item2, the first overlapping * item. * Then we find the last one that overlap unionRect to agregate Item2, Item3 * and Item4 to create Item2. * Finally Item5 is copied as Item3. * * When no unionRect is provided, we skip the two first steps to just copy items */ if (unionRect) { /* items before unionRect */ while ((src < end) && (src->top == refY) && (src->right < unionRect->left)) { dst->top = newTop; dst->bottom = newBottom; dst->right = src->right; dst->left = src->left; src++; dst++; *dstCounter += 1; } /* treat items overlapping with unionRect */ startOverlap = unionRect; endOverlap = unionRect; if ((src < end) && (src->top == refY) && (src->left < unionRect->left)) startOverlap = src; while ((src < end) && (src->top == refY) && (src->right < unionRect->right)) { src++; } if ((src < end) && (src->top == refY) && (src->left < unionRect->right)) { endOverlap = src; src++; } dst->bottom = newBottom; dst->top = newTop; dst->left = startOverlap->left; dst->right = endOverlap->right; dst++; *dstCounter += 1; } /* treat remaining items on the same band */ while ((src < end) && (src->top == refY)) { dst->top = newTop; dst->bottom = newBottom; dst->right = src->right; dst->left = src->left; src++; dst++; *dstCounter += 1; } if (srcPtr) *srcPtr = src; *dstPtr = dst; } static RECTANGLE_16* next_band(RECTANGLE_16* band1, RECTANGLE_16* endPtr, int* nbItems) { UINT16 refY = band1->top; *nbItems = 0; while ((band1 < endPtr) && (band1->top == refY)) { band1++; *nbItems += 1; } return band1; } static BOOL band_match(const RECTANGLE_16* band1, const RECTANGLE_16* band2, RECTANGLE_16* endPtr) { int refBand2 = band2->top; const RECTANGLE_16* band2Start = band2; while ((band1 < band2Start) && (band2 < endPtr) && (band2->top == refBand2)) { if ((band1->left != band2->left) || (band1->right != band2->right)) return FALSE; band1++; band2++; } if (band1 != band2Start) return FALSE; return (band2 == endPtr) || (band2->top != refBand2); } /** compute if the rectangle is fully included in the band * @param band a pointer on the beginning of the band * @param endPtr end of the region * @param rect the rectangle to test * @return if rect is fully included in an item of the band */ static BOOL rectangle_contained_in_band(const RECTANGLE_16* band, const RECTANGLE_16* endPtr, const RECTANGLE_16* rect) { UINT16 refY = band->top; if ((band->top > rect->top) || (rect->bottom > band->bottom)) return FALSE; /* note: as the band is sorted from left to right, once we've seen an item * that is after rect->left we're sure that the result is False. */ while ((band < endPtr) && (band->top == refY) && (band->left <= rect->left)) { if (rect->right <= band->right) return TRUE; band++; } return FALSE; } static BOOL region16_simplify_bands(REGION16* region) { /** Simplify consecutive bands that touch and have the same items * * ==================== ==================== * | 1 | | 2 | | | | | * ==================== | | | | * | 1 | | 2 | ====> | 1 | | 2 | * ==================== | | | | * | 1 | | 2 | | | | | * ==================== ==================== * */ RECTANGLE_16* band1, *band2, *endPtr, *endBand, *tmp; int nbRects, finalNbRects; int bandItems, toMove; finalNbRects = nbRects = region16_n_rects(region); if (nbRects < 2) return TRUE; band1 = region16_rects_noconst(region); endPtr = band1 + nbRects; do { band2 = next_band(band1, endPtr, &bandItems); if (band2 == endPtr) break; if ((band1->bottom == band2->top) && band_match(band1, band2, endPtr)) { /* adjust the bottom of band1 items */ tmp = band1; while (tmp < band2) { tmp->bottom = band2->bottom; tmp++; } /* override band2, we don't move band1 pointer as the band after band2 * may be merged too */ endBand = band2 + bandItems; toMove = (endPtr - endBand) * sizeof(RECTANGLE_16); if (toMove) MoveMemory(band2, endBand, toMove); finalNbRects -= bandItems; endPtr -= bandItems; } else { band1 = band2; } } while (TRUE); if (finalNbRects != nbRects) { REGION16_DATA* data; size_t allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16)); data = realloc(region->data, allocSize); if (!data) free(region->data); region->data = data; if (!region->data) { region->data = &empty_region; return FALSE; } region->data->nbRects = finalNbRects; region->data->size = allocSize; } return TRUE; } BOOL region16_union_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect) { REGION16_DATA* data; const RECTANGLE_16* srcExtents; RECTANGLE_16* dstExtents; const RECTANGLE_16* currentBand, *endSrcRect, *nextBand; REGION16_DATA* newItems = NULL; RECTANGLE_16* dstRect = NULL; UINT32 usedRects, srcNbRects; UINT16 topInterBand; assert(src); assert(src->data); assert(dst); srcExtents = region16_extents(src); dstExtents = region16_extents_noconst(dst); if (!region16_n_rects(src)) { /* source is empty, so the union is rect */ dst->extents = *rect; dst->data = allocateRegion(1); if (!dst->data) return FALSE; dstRect = region16_rects_noconst(dst); dstRect->top = rect->top; dstRect->left = rect->left; dstRect->right = rect->right; dstRect->bottom = rect->bottom; return TRUE; } newItems = allocateRegion((1 + region16_n_rects(src)) * 4); if (!newItems) return FALSE; dstRect = (RECTANGLE_16*)(&newItems[1]); usedRects = 0; /* adds the piece of rect that is on the top of src */ if (rect->top < srcExtents->top) { dstRect->top = rect->top; dstRect->left = rect->left; dstRect->right = rect->right; dstRect->bottom = MIN(srcExtents->top, rect->bottom); usedRects++; dstRect++; } /* treat possibly overlapping region */ currentBand = region16_rects(src, &srcNbRects); endSrcRect = currentBand + srcNbRects; while (currentBand < endSrcRect) { if ((currentBand->bottom <= rect->top) || (rect->bottom <= currentBand->top) || rectangle_contained_in_band(currentBand, endSrcRect, rect)) { /* no overlap between rect and the band, rect is totally below or totally above * the current band, or rect is already covered by an item of the band. * let's copy all the rectangles from this band +----+ | | rect (case 1) +----+ ================= band of srcRect ================= +----+ | | rect (case 2) +----+ */ region16_copy_band_with_union(dstRect, currentBand, endSrcRect, currentBand->top, currentBand->bottom, NULL, &usedRects, &nextBand, &dstRect); topInterBand = rect->top; } else { /* rect overlaps the band: | | | | ====^=================| |==| |=========================== band | top split | | | | v | 1 | | 2 | ^ | | | | +----+ +----+ | merge zone | | | | | | | 4 | v +----+ | | | | +----+ ^ | | | 3 | | bottom split | | | | ====v=========================| |==| |=================== | | | | possible cases: 1) no top split, merge zone then a bottom split. The band will be splitted in two 2) not band split, only the merge zone, band merged with rect but not splitted 3) a top split, the merge zone and no bottom split. The band will be split in two 4) a top split, the merge zone and also a bottom split. The band will be splitted in 3, but the coalesce algorithm may merge the created bands */ UINT16 mergeTop = currentBand->top; UINT16 mergeBottom = currentBand->bottom; /* test if we need a top split, case 3 and 4 */ if (rect->top > currentBand->top) { region16_copy_band_with_union(dstRect, currentBand, endSrcRect, currentBand->top, rect->top, NULL, &usedRects, &nextBand, &dstRect); mergeTop = rect->top; } /* do the merge zone (all cases) */ if (rect->bottom < currentBand->bottom) mergeBottom = rect->bottom; region16_copy_band_with_union(dstRect, currentBand, endSrcRect, mergeTop, mergeBottom, rect, &usedRects, &nextBand, &dstRect); /* test if we need a bottom split, case 1 and 4 */ if (rect->bottom < currentBand->bottom) { region16_copy_band_with_union(dstRect, currentBand, endSrcRect, mergeBottom, currentBand->bottom, NULL, &usedRects, &nextBand, &dstRect); } topInterBand = currentBand->bottom; } /* test if a piece of rect should be inserted as a new band between * the current band and the next one. band n and n+1 shouldn't touch. * * ============================================================== * band n * +------+ +------+ * ===========| rect |====================| |=============== * | | +------+ | | * +------+ | rect | | rect | * +------+ | | * =======================================| |================ * +------+ band n+1 * =============================================================== * */ if ((nextBand < endSrcRect) && (nextBand->top != currentBand->bottom) && (rect->bottom > currentBand->bottom) && (rect->top < nextBand->top)) { dstRect->right = rect->right; dstRect->left = rect->left; dstRect->top = topInterBand; dstRect->bottom = MIN(nextBand->top, rect->bottom); dstRect++; usedRects++; } currentBand = nextBand; } /* adds the piece of rect that is below src */ if (srcExtents->bottom < rect->bottom) { dstRect->top = MAX(srcExtents->bottom, rect->top); dstRect->left = rect->left; dstRect->right = rect->right; dstRect->bottom = rect->bottom; usedRects++; dstRect++; } if ((src == dst) && (src->data->size > 0) && (src->data != &empty_region)) free(src->data); dstExtents->top = MIN(rect->top, srcExtents->top); dstExtents->left = MIN(rect->left, srcExtents->left); dstExtents->bottom = MAX(rect->bottom, srcExtents->bottom); dstExtents->right = MAX(rect->right, srcExtents->right); newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16)); data = realloc(newItems, newItems->size); if (!data) free(dst->data); dst->data = data; if (!dst->data) { free(newItems); return FALSE; } dst->data->nbRects = usedRects; return region16_simplify_bands(dst); } BOOL region16_intersects_rect(const REGION16* src, const RECTANGLE_16* arg2) { const RECTANGLE_16* rect, *endPtr, *srcExtents; UINT32 nbRects; if (!src || !src->data || !arg2) return FALSE; rect = region16_rects(src, &nbRects); if (!nbRects) return FALSE; srcExtents = region16_extents(src); if (nbRects == 1) return rectangles_intersects(srcExtents, arg2); if (!rectangles_intersects(srcExtents, arg2)) return FALSE; for (endPtr = rect + nbRects; (rect < endPtr) && (arg2->bottom > rect->top); rect++) { if (rectangles_intersects(rect, arg2)) return TRUE; } return FALSE; } BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect) { REGION16_DATA* data; REGION16_DATA* newItems; const RECTANGLE_16* srcPtr, *endPtr, *srcExtents; RECTANGLE_16* dstPtr; UINT32 nbRects, usedRects; RECTANGLE_16 common, newExtents; assert(src); assert(src->data); srcPtr = region16_rects(src, &nbRects); if (!nbRects) { region16_clear(dst); return TRUE; } srcExtents = region16_extents(src); if (nbRects == 1) { BOOL intersects = rectangles_intersection(srcExtents, rect, &common); region16_clear(dst); if (intersects) return region16_union_rect(dst, dst, &common); return TRUE; } newItems = allocateRegion(nbRects); if (!newItems) return FALSE; dstPtr = (RECTANGLE_16*)(&newItems[1]); usedRects = 0; ZeroMemory(&newExtents, sizeof(newExtents)); /* accumulate intersecting rectangles, the final region16_simplify_bands() will * do all the bad job to recreate correct rectangles */ for (endPtr = srcPtr + nbRects; (srcPtr < endPtr) && (rect->bottom > srcPtr->top); srcPtr++) { if (rectangles_intersection(srcPtr, rect, &common)) { *dstPtr = common; usedRects++; dstPtr++; if (rectangle_is_empty(&newExtents)) { /* Check if the existing newExtents is empty. If it is empty, use * new common directly. We do not need to check common rectangle * because the rectangles_intersection() ensures that it is not empty. */ newExtents = common; } else { newExtents.top = MIN(common.top, newExtents.top); newExtents.left = MIN(common.left, newExtents.left); newExtents.bottom = MAX(common.bottom, newExtents.bottom); newExtents.right = MAX(common.right, newExtents.right); } } } newItems->nbRects = usedRects; newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16)); if ((dst->data->size > 0) && (dst->data != &empty_region)) free(dst->data); data = realloc(newItems, newItems->size); if (!data) free(dst->data); dst->data = data; if (!dst->data) { free(newItems); return FALSE; } dst->extents = newExtents; return region16_simplify_bands(dst); } void region16_uninit(REGION16* region) { assert(region); if (region->data) { if ((region->data->size > 0) && (region->data != &empty_region)) free(region->data); region->data = NULL; } }
./CrossVul/dataset_final_sorted/CWE-772/c/good_1168_1
crossvul-cpp_data_bad_361_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N GGGG % % P P NN N G % % PPPP N N N G GG % % P N NN G G % % P N N GGG % % % % % % Read/Write Portable Network Graphics Image Format % % % % Software Design % % Cristy % % Glenn Randers-Pehrson % % November 1997 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ #define IM /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/MagickCore.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_PNG_DELEGATE) /* Suppress libpng pedantic warnings that were added in * libpng-1.2.41 and libpng-1.4.0. If you are working on * migration to libpng-1.5, remove these defines and then * fix any code that generates warnings. */ /* #define PNG_DEPRECATED Use of this function is deprecated */ /* #define PNG_USE_RESULT The result of this function must be checked */ /* #define PNG_NORETURN This function does not return */ /* #define PNG_ALLOCATED The result of the function is new memory */ /* #define PNG_DEPSTRUCT Access to this struct member is deprecated */ /* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */ #define PNG_PTR_NORETURN #include "png.h" #include "zlib.h" /* ImageMagick differences */ #define first_scene scene #if PNG_LIBPNG_VER > 10011 /* Optional declarations. Define or undefine them as you like. */ /* #define PNG_DEBUG -- turning this on breaks VisualC compiling */ /* Features under construction. Define these to work on them. */ #undef MNG_OBJECT_BUFFERS #undef MNG_BASI_SUPPORTED #define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */ #define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */ #if defined(MAGICKCORE_JPEG_DELEGATE) # define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */ #endif #if !defined(RGBColorMatchExact) #define IsPNGColorEqual(color,target) \ (((color).red == (target).red) && \ ((color).green == (target).green) && \ ((color).blue == (target).blue)) #endif /* Table of recognized sRGB ICC profiles */ struct sRGB_info_struct { png_uint_32 len; png_uint_32 crc; png_byte intent; }; const struct sRGB_info_struct sRGB_info[] = { /* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */ { 3048, 0x3b8772b9UL, 0}, /* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */ { 3052, 0x427ebb21UL, 1}, /* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */ {60988, 0x306fd8aeUL, 0}, /* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */ {60960, 0xbbef7812UL, 0}, /* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */ { 3024, 0x5d5129ceUL, 1}, /* HP-Microsoft sRGB v2 perceptual */ { 3144, 0x182ea552UL, 0}, /* HP-Microsoft sRGB v2 media-relative */ { 3144, 0xf29e526dUL, 1}, /* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */ { 524, 0xd4938c39UL, 0}, /* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */ { 3212, 0x034af5a1UL, 0}, /* Not recognized */ { 0, 0x00000000UL, 0}, }; /* Macros for left-bit-replication to ensure that pixels * and PixelInfos all have the same image->depth, and for use * in PNG8 quantization. */ /* LBR01: Replicate top bit */ #define LBR01PacketRed(pixelpacket) \ (pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketGreen(pixelpacket) \ (pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketBlue(pixelpacket) \ (pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketAlpha(pixelpacket) \ (pixelpacket).alpha=(ScaleQuantumToChar((pixelpacket).alpha) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketRGB(pixelpacket) \ { \ LBR01PacketRed((pixelpacket)); \ LBR01PacketGreen((pixelpacket)); \ LBR01PacketBlue((pixelpacket)); \ } #define LBR01PacketRGBA(pixelpacket) \ { \ LBR01PacketRGB((pixelpacket)); \ LBR01PacketAlpha((pixelpacket)); \ } #define LBR01PixelRed(pixel) \ (SetPixelRed(image, \ ScaleQuantumToChar(GetPixelRed(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelGreen(pixel) \ (SetPixelGreen(image, \ ScaleQuantumToChar(GetPixelGreen(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelBlue(pixel) \ (SetPixelBlue(image, \ ScaleQuantumToChar(GetPixelBlue(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelAlpha(pixel) \ (SetPixelAlpha(image, \ ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelRGB(pixel) \ { \ LBR01PixelRed((pixel)); \ LBR01PixelGreen((pixel)); \ LBR01PixelBlue((pixel)); \ } #define LBR01PixelRGBA(pixel) \ { \ LBR01PixelRGB((pixel)); \ LBR01PixelAlpha((pixel)); \ } /* LBR02: Replicate top 2 bits */ #define LBR02PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketAlpha(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).alpha) & 0xc0; \ (pixelpacket).alpha=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketRGB(pixelpacket) \ { \ LBR02PacketRed((pixelpacket)); \ LBR02PacketGreen((pixelpacket)); \ LBR02PacketBlue((pixelpacket)); \ } #define LBR02PacketRGBA(pixelpacket) \ { \ LBR02PacketRGB((pixelpacket)); \ LBR02PacketAlpha((pixelpacket)); \ } #define LBR02PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \ & 0xc0; \ SetPixelRed(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel)); \ } #define LBR02PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\ & 0xc0; \ SetPixelGreen(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel)); \ } #define LBR02PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue(image,(pixel))) & 0xc0; \ SetPixelBlue(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel)); \ } #define LBR02PixelAlpha(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) & 0xc0; \ SetPixelAlpha(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel) ); \ } #define LBR02PixelRGB(pixel) \ { \ LBR02PixelRed((pixel)); \ LBR02PixelGreen((pixel)); \ LBR02PixelBlue((pixel)); \ } #define LBR02PixelRGBA(pixel) \ { \ LBR02PixelRGB((pixel)); \ LBR02PixelAlpha((pixel)); \ } /* LBR03: Replicate top 3 bits (only used with opaque pixels during PNG8 quantization) */ #define LBR03PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketRGB(pixelpacket) \ { \ LBR03PacketRed((pixelpacket)); \ LBR03PacketGreen((pixelpacket)); \ LBR03PacketBlue((pixelpacket)); \ } #define LBR03PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \ & 0xe0; \ SetPixelRed(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \ } #define LBR03Green(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\ & 0xe0; \ SetPixelGreen(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \ } #define LBR03Blue(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue(image,(pixel))) \ & 0xe0; \ SetPixelBlue(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \ } #define LBR03RGB(pixel) \ { \ LBR03PixelRed((pixel)); \ LBR03Green((pixel)); \ LBR03Blue((pixel)); \ } /* LBR04: Replicate top 4 bits */ #define LBR04PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \ (pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \ (pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \ (pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketAlpha(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).alpha) & 0xf0; \ (pixelpacket).alpha=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketRGB(pixelpacket) \ { \ LBR04PacketRed((pixelpacket)); \ LBR04PacketGreen((pixelpacket)); \ LBR04PacketBlue((pixelpacket)); \ } #define LBR04PacketRGBA(pixelpacket) \ { \ LBR04PacketRGB((pixelpacket)); \ LBR04PacketAlpha((pixelpacket)); \ } #define LBR04PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \ & 0xf0; \ SetPixelRed(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\ & 0xf0; \ SetPixelGreen(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue(image,(pixel))) & 0xf0; \ SetPixelBlue(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelAlpha(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) & 0xf0; \ SetPixelAlpha(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelRGB(pixel) \ { \ LBR04PixelRed((pixel)); \ LBR04PixelGreen((pixel)); \ LBR04PixelBlue((pixel)); \ } #define LBR04PixelRGBA(pixel) \ { \ LBR04PixelRGB((pixel)); \ LBR04PixelAlpha((pixel)); \ } /* Establish thread safety. setjmp/longjmp is claimed to be safe on these platforms: setjmp/longjmp is alleged to be unsafe on these platforms: */ #ifdef PNG_SETJMP_SUPPORTED # ifndef IMPNG_SETJMP_IS_THREAD_SAFE # define IMPNG_SETJMP_NOT_THREAD_SAFE # endif # ifdef IMPNG_SETJMP_NOT_THREAD_SAFE static SemaphoreInfo *ping_semaphore = (SemaphoreInfo *) NULL; # endif #endif /* This temporary until I set up malloc'ed object attributes array. Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but waste more memory. */ #define MNG_MAX_OBJECTS 256 /* If this not defined, spec is interpreted strictly. If it is defined, an attempt will be made to recover from some errors, including o global PLTE too short */ #undef MNG_LOOSE /* Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8, PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here. PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and will be enabled by default in libpng-1.2.0. */ #ifdef PNG_MNG_FEATURES_SUPPORTED # ifndef PNG_READ_EMPTY_PLTE_SUPPORTED # define PNG_READ_EMPTY_PLTE_SUPPORTED # endif # ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED # define PNG_WRITE_EMPTY_PLTE_SUPPORTED # endif #endif /* Maximum valid size_t in PNG/MNG chunks is (2^31)-1 This macro is only defined in libpng-1.0.3 and later. Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6 */ #ifndef PNG_UINT_31_MAX #define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL #endif /* Constant strings for known chunk types. If you need to add a chunk, add a string holding the name here. To make the code more portable, we use ASCII numbers like this, not characters. */ static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'}; static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'}; static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'}; static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'}; static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'}; static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'}; static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'}; static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'}; static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'}; static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'}; static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'}; static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'}; static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'}; static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'}; static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'}; static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'}; static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'}; static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'}; static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'}; static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'}; static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'}; static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'}; static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'}; static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'}; static const png_byte mng_orNT[5]={111, 114, 78, 84, (png_byte) '\0'}; static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'}; static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'}; static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'}; static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'}; static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'}; static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'}; #if defined(JNG_SUPPORTED) static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'}; static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'}; static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'}; static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'}; #endif #if 0 /* Other known chunks that are not yet supported by ImageMagick: */ static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'}; static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'}; static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'}; static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'}; static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'}; static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'}; static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'}; #endif typedef struct _MngBox { long left, right, top, bottom; } MngBox; typedef struct _MngPair { volatile long a, b; } MngPair; #ifdef MNG_OBJECT_BUFFERS typedef struct _MngBuffer { size_t height, width; Image *image; png_color plte[256]; int reference_count; unsigned char alpha_sample_depth, compression_method, color_type, concrete, filter_method, frozen, image_type, interlace_method, pixel_sample_depth, plte_length, sample_depth, viewable; } MngBuffer; #endif typedef struct _MngInfo { #ifdef MNG_OBJECT_BUFFERS MngBuffer *ob[MNG_MAX_OBJECTS]; #endif Image * image; RectangleInfo page; int adjoin, #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED bytes_in_read_buffer, found_empty_plte, #endif equal_backgrounds, equal_chrms, equal_gammas, #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) equal_palettes, #endif equal_physs, equal_srgbs, framing_mode, have_global_bkgd, have_global_chrm, have_global_gama, have_global_phys, have_global_sbit, have_global_srgb, have_saved_bkgd_index, have_write_global_chrm, have_write_global_gama, have_write_global_plte, have_write_global_srgb, need_fram, object_id, old_framing_mode, saved_bkgd_index; int new_number_colors; ssize_t image_found, loop_count[256], loop_iteration[256], scenes_found, x_off[MNG_MAX_OBJECTS], y_off[MNG_MAX_OBJECTS]; MngBox clip, frame, image_box, object_clip[MNG_MAX_OBJECTS]; unsigned char /* These flags could be combined into one byte */ exists[MNG_MAX_OBJECTS], frozen[MNG_MAX_OBJECTS], loop_active[256], invisible[MNG_MAX_OBJECTS], viewable[MNG_MAX_OBJECTS]; MagickOffsetType loop_jump[256]; png_colorp global_plte; png_color_8 global_sbit; png_byte #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED read_buffer[8], #endif global_trns[256]; float global_gamma; ChromaticityInfo global_chrm; RenderingIntent global_srgb_intent; unsigned long delay, global_plte_length, global_trns_length, global_x_pixels_per_unit, global_y_pixels_per_unit, mng_width, mng_height, ticks_per_second; MagickBooleanType need_blob; unsigned int IsPalette, global_phys_unit_type, basi_warning, clon_warning, dhdr_warning, jhdr_warning, magn_warning, past_warning, phyg_warning, phys_warning, sbit_warning, show_warning, mng_type, write_mng, write_png_colortype, write_png_depth, write_png_compression_level, write_png_compression_strategy, write_png_compression_filter, write_png8, write_png24, write_png32, write_png48, write_png64; #ifdef MNG_BASI_SUPPORTED unsigned long basi_width, basi_height; unsigned int basi_depth, basi_color_type, basi_compression_method, basi_filter_type, basi_interlace_method, basi_red, basi_green, basi_blue, basi_alpha, basi_viewable; #endif png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; PixelInfo mng_global_bkgd; /* Added at version 6.6.6-7 */ MagickBooleanType ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, ping_exclude_eXIf, ping_exclude_EXIF, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tRNS, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, /* Added at version 6.8.5-7 */ ping_preserve_iCCP, /* Added at version 6.8.9-9 */ ping_exclude_tIME; } MngInfo; #endif /* VER */ /* Forward declarations. */ static MagickBooleanType WritePNGImage(const ImageInfo *,Image *,ExceptionInfo *); static MagickBooleanType WriteMNGImage(const ImageInfo *,Image *,ExceptionInfo *); #if defined(JNG_SUPPORTED) static MagickBooleanType WriteJNGImage(const ImageInfo *,Image *,ExceptionInfo *); #endif #if PNG_LIBPNG_VER > 10011 #if (MAGICKCORE_QUANTUM_DEPTH >= 16) static MagickBooleanType LosslessReduceDepthOK(Image *image,ExceptionInfo *exception) { /* Reduce bit depth if it can be reduced losslessly from 16+ to 8. * * This is true if the high byte and the next highest byte of * each sample of the image, the colormap, and the background color * are equal to each other. We check this by seeing if the samples * are unchanged when we scale them down to 8 and back up to Quantum. * * We don't use the method GetImageDepth() because it doesn't check * background and doesn't handle PseudoClass specially. */ #define QuantumToCharToQuantumEqQuantum(quantum) \ ((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum) MagickBooleanType ok_to_reduce=MagickFalse; if (image->depth >= 16) { const Quantum *p; ok_to_reduce= QuantumToCharToQuantumEqQuantum(image->background_color.red) && QuantumToCharToQuantumEqQuantum(image->background_color.green) && QuantumToCharToQuantumEqQuantum(image->background_color.blue) ? MagickTrue : MagickFalse; if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass) { int indx; for (indx=0; indx < (ssize_t) image->colors; indx++) { ok_to_reduce=( QuantumToCharToQuantumEqQuantum( image->colormap[indx].red) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].green) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].blue)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; } } if ((ok_to_reduce != MagickFalse) && (image->storage_class != PseudoClass)) { ssize_t y; register ssize_t x; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { ok_to_reduce = MagickFalse; break; } for (x=(ssize_t) image->columns-1; x >= 0; x--) { ok_to_reduce= QuantumToCharToQuantumEqQuantum(GetPixelRed(image,p)) && QuantumToCharToQuantumEqQuantum(GetPixelGreen(image,p)) && QuantumToCharToQuantumEqQuantum(GetPixelBlue(image,p)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; p+=GetPixelChannels(image); } if (x >= 0) break; } } if (ok_to_reduce != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " OK to reduce PNG bit depth to 8 without loss of info"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Not OK to reduce PNG bit depth to 8 without losing info"); } } return ok_to_reduce; } #endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */ static const char* PngColorTypeToString(const unsigned int color_type) { const char *result = "Unknown"; switch (color_type) { case PNG_COLOR_TYPE_GRAY: result = "Gray"; break; case PNG_COLOR_TYPE_GRAY_ALPHA: result = "Gray+Alpha"; break; case PNG_COLOR_TYPE_PALETTE: result = "Palette"; break; case PNG_COLOR_TYPE_RGB: result = "RGB"; break; case PNG_COLOR_TYPE_RGB_ALPHA: result = "RGB+Alpha"; break; } return result; } static int Magick_Orientation_to_Exif_Orientation(const OrientationType orientation) { switch (orientation) { /* Convert to Exif orientations as defined in "Exchangeable image file * format for digital still cameras: Exif Version 2.31", * http://www.cipa.jp/std/documents/e/DC-008-Translation-2016-E.pdf */ case TopLeftOrientation: return 1; case TopRightOrientation: return 2; case BottomRightOrientation: return 3; case BottomLeftOrientation: return 4; case LeftTopOrientation: return 5; case RightTopOrientation: return 6; case RightBottomOrientation: return 7; case LeftBottomOrientation: return 8; case UndefinedOrientation: default: return 0; } } static OrientationType Magick_Orientation_from_Exif_Orientation(const int orientation) { switch (orientation) { case 1: return TopLeftOrientation; case 2: return TopRightOrientation; case 3: return BottomRightOrientation; case 4: return BottomLeftOrientation; case 5: return LeftTopOrientation; case 6: return RightTopOrientation; case 7: return RightBottomOrientation; case 8: return LeftBottomOrientation; case 0: default: return UndefinedOrientation; } } static int Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent) { switch (intent) { case PerceptualIntent: return 0; case RelativeIntent: return 1; case SaturationIntent: return 2; case AbsoluteIntent: return 3; default: return -1; } } static RenderingIntent Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return PerceptualIntent; case 1: return RelativeIntent; case 2: return SaturationIntent; case 3: return AbsoluteIntent; default: return UndefinedIntent; } } static const char * Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return "Perceptual Intent"; case 1: return "Relative Intent"; case 2: return "Saturation Intent"; case 3: return "Absolute Intent"; default: return "Undefined Intent"; } } static const char * Magick_ColorType_from_PNG_ColorType(const int ping_colortype) { switch (ping_colortype) { case 0: return "Grayscale"; case 2: return "Truecolor"; case 3: return "Indexed"; case 4: return "GrayAlpha"; case 6: return "RGBA"; default: return "UndefinedColorType"; } } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* MAGICKCORE_PNG_DELEGATE */ /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMNG() returns MagickTrue if the image format type, identified by the % magick string, is MNG. % % The format of the IsMNG method is: % % MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJNG() returns MagickTrue if the image format type, identified by the % magick string, is JNG. % % The format of the IsJNG method is: % % MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNG() returns MagickTrue if the image format type, identified by the % magick string, is PNG. % % The format of the IsPNG method is: % % MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_PNG_DELEGATE) #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if (PNG_LIBPNG_VER > 10011) static size_t WriteBlobMSBULong(Image *image,const size_t value) { unsigned char buffer[4]; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; return((size_t) WriteBlob(image,4,buffer)); } static void PNGLong(png_bytep p,png_uint_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGsLong(png_bytep p,png_int_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGShort(png_bytep p,png_uint_16 value) { *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGType(png_bytep p,const png_byte *type) { (void) memcpy(p,type,4*sizeof(png_byte)); } static void LogPNGChunk(MagickBooleanType logging, const png_byte *type, size_t length) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing %c%c%c%c chunk, length: %.20g", type[0],type[1],type[2],type[3],(double) length); } #endif /* PNG_LIBPNG_VER > 10011 */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNGImage() reads a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image or set of images. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadPNGImage method is: % % Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % % To do, more or less in chronological order (as of version 5.5.2, % November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage): % % Get 16-bit cheap transparency working. % % (At this point, PNG decoding is supposed to be in full MNG-LC compliance) % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % (At this point, PNG encoding should be in full MNG compliance) % % Provide options for choice of background to use when the MNG BACK % chunk is not present or is not mandatory (i.e., leave transparent, % user specified, MNG BACK, PNG bKGD) % % Implement LOOP/ENDL [done, but could do discretionary loops more % efficiently by linking in the duplicate frames.]. % % Decode and act on the MHDR simplicity profile (offer option to reject % files or attempt to process them anyway when the profile isn't LC or VLC). % % Upgrade to full MNG without Delta-PNG. % % o BACK [done a while ago except for background image ID] % o MOVE [done 15 May 1999] % o CLIP [done 15 May 1999] % o DISC [done 19 May 1999] % o SAVE [partially done 19 May 1999 (marks objects frozen)] % o SEEK [partially done 19 May 1999 (discard function only)] % o SHOW % o PAST % o BASI % o MNG-level tEXt/iTXt/zTXt % o pHYg % o pHYs % o sBIT % o bKGD % o iTXt (wait for libpng implementation). % % Use the scene signature to discover when an identical scene is % being reused, and just point to the original image->exception instead % of storing another set of pixels. This not specific to MNG % but could be applied generally. % % Upgrade to full MNG with Delta-PNG. % % JNG tEXt/iTXt/zTXt % % We will not attempt to read files containing the CgBI chunk. % They are really Xcode files meant for display on the iPhone. % These are not valid PNG files and it is impossible to recover % the original PNG from files that have been converted to Xcode-PNG, % since irretrievable loss of color data has occurred due to the % use of premultiplied alpha. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* This the function that does the actual reading of data. It is the same as the one supplied in libpng, except that it receives the datastream from the ReadBlob() function instead of standard input. */ static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) ReadBlob(image,(size_t) length,data); if (check != length) { char msg[MagickPathExtent]; (void) FormatLocaleString(msg,MagickPathExtent, "Expected %.20g bytes; found %.20g bytes",(double) length, (double) check); png_warning(png_ptr,msg); png_error(png_ptr,"Read Exception"); } } } #if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \ !defined(PNG_MNG_FEATURES_SUPPORTED) /* We use mng_get_data() instead of png_get_data() if we have a libpng * older than libpng-1.0.3a, which was the first to allow the empty * PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was * ifdef'ed out. Earlier versions would crash if the bKGD chunk was * encountered after an empty PLTE, so we have to look ahead for bKGD * chunks and remove them from the datastream that is passed to libpng, * and store their contents for later use. */ static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { MngInfo *mng_info; Image *image; png_size_t check; register ssize_t i; i=0; mng_info=(MngInfo *) png_get_io_ptr(png_ptr); image=(Image *) mng_info->image; while (mng_info->bytes_in_read_buffer && length) { data[i]=mng_info->read_buffer[i]; mng_info->bytes_in_read_buffer--; length--; i++; } if (length != 0) { check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data); if (check != length) png_error(png_ptr,"Read Exception"); if (length == 4) { if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 0)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0) mng_info->found_empty_plte=MagickTrue; if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0) { mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; } } if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 1)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0) if (mng_info->found_empty_plte) { /* Skip the bKGD data byte and CRC. */ check=(png_size_t) ReadBlob(image,5,(char *) mng_info->read_buffer); check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->saved_bkgd_index=mng_info->read_buffer[0]; mng_info->have_saved_bkgd_index=MagickTrue; mng_info->bytes_in_read_buffer=0; } } } } } #endif static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) WriteBlob(image,(size_t) length,data); if (check != length) png_error(png_ptr,"WriteBlob Failed"); } } static void png_flush_data(png_structp png_ptr) { (void) png_ptr; } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED static int PalettesAreEqual(Image *a,Image *b) { ssize_t i; if ((a == (Image *) NULL) || (b == (Image *) NULL)) return((int) MagickFalse); if (a->storage_class != PseudoClass || b->storage_class != PseudoClass) return((int) MagickFalse); if (a->colors != b->colors) return((int) MagickFalse); for (i=0; i < (ssize_t) a->colors; i++) { if ((a->colormap[i].red != b->colormap[i].red) || (a->colormap[i].green != b->colormap[i].green) || (a->colormap[i].blue != b->colormap[i].blue)) return((int) MagickFalse); } return((int) MagickTrue); } #endif static void MngInfoDiscardObject(MngInfo *mng_info,int i) { if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) && mng_info->exists[i] && !mng_info->frozen[i]) { #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) { if (mng_info->ob[i]->reference_count > 0) mng_info->ob[i]->reference_count--; if (mng_info->ob[i]->reference_count == 0) { if (mng_info->ob[i]->image != (Image *) NULL) mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image); mng_info->ob[i]=DestroyString(mng_info->ob[i]); } } mng_info->ob[i]=(MngBuffer *) NULL; #endif mng_info->exists[i]=MagickFalse; mng_info->invisible[i]=MagickFalse; mng_info->viewable[i]=MagickFalse; mng_info->frozen[i]=MagickFalse; mng_info->x_off[i]=0; mng_info->y_off[i]=0; mng_info->object_clip[i].left=0; mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].top=0; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } } static MngInfo *MngInfoFreeStruct(MngInfo *mng_info) { register ssize_t i; if (mng_info == (MngInfo *) NULL) return((MngInfo *) NULL); for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); mng_info->global_plte=(png_colorp) RelinquishMagickMemory(mng_info->global_plte); return((MngInfo *) RelinquishMagickMemory(mng_info)); } static MngBox mng_minimum_box(MngBox box1,MngBox box2) { MngBox box; box=box1; if (box.left < box2.left) box.left=box2.left; if (box.top < box2.top) box.top=box2.top; if (box.right > box2.right) box.right=box2.right; if (box.bottom > box2.bottom) box.bottom=box2.bottom; return box; } static long mng_get_long(unsigned char *p) { return ((long) (((png_uint_32) p[0] << 24) | ((png_uint_32) p[1] << 16) | ((png_uint_32) p[2] << 8) | (png_uint_32) p[3])); } static MngBox mng_read_box(MngBox previous_box,char delta_type, unsigned char *p) { MngBox box; /* Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk. */ box.left=mng_get_long(p); box.right=mng_get_long(&p[4]); box.top=mng_get_long(&p[8]); box.bottom=mng_get_long(&p[12]); if (delta_type != 0) { box.left+=previous_box.left; box.right+=previous_box.right; box.top+=previous_box.top; box.bottom+=previous_box.bottom; } return(box); } static MngPair mng_read_pair(MngPair previous_pair,int delta_type, unsigned char *p) { MngPair pair; /* Read two ssize_t's from CLON, MOVE or PAST chunk */ pair.a=mng_get_long(p); pair.b=mng_get_long(&p[4]); if (delta_type != 0) { pair.a+=previous_pair.a; pair.b+=previous_pair.b; } return(pair); } typedef struct _PNGErrorInfo { Image *image; ExceptionInfo *exception; } PNGErrorInfo; static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message) { ExceptionInfo *exception; Image *image; PNGErrorInfo *error_info; error_info=(PNGErrorInfo *) png_get_error_ptr(ping); image=error_info->image; exception=error_info->exception; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s error: %s", png_get_libpng_ver(NULL),message); (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message, "`%s'",image->filename); #if (PNG_LIBPNG_VER < 10500) /* A warning about deprecated use of jmpbuf here is unavoidable if you * are building with libpng-1.4.x and can be ignored. */ longjmp(ping->jmpbuf,1); #else png_longjmp(ping,1); #endif } static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message) { ExceptionInfo *exception; Image *image; PNGErrorInfo *error_info; if (LocaleCompare(message, "Missing PLTE before tRNS") == 0) png_error(ping, message); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); image=error_info->image; exception=error_info->exception; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s warning: %s", png_get_libpng_ver(NULL),message); (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'",image->filename); } #ifdef PNG_USER_MEM_SUPPORTED #if PNG_LIBPNG_VER >= 10400 static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size) #else static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size) #endif { (void) png_ptr; return((png_voidp) AcquireMagickMemory((size_t) size)); } /* Free a pointer. It is removed from the list at the same time. */ static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr) { (void) png_ptr; ptr=RelinquishMagickMemory(ptr); return((png_free_ptr) NULL); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static int Magick_png_read_raw_profile(png_struct *ping,Image *image, const ImageInfo *image_info, png_textp text,int ii,ExceptionInfo *exception) { register ssize_t i; register unsigned char *dp; register png_charp sp; size_t extent, length, nibbles; StringInfo *profile; static const unsigned char unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12, 13,14,15}; sp=text[ii].text+1; extent=text[ii].text_length; /* look for newline */ while ((*sp != '\n') && extent--) sp++; /* look for length */ while (((*sp == '\0' || *sp == ' ' || *sp == '\n')) && extent--) sp++; if (extent == 0) { png_warning(ping,"invalid profile length"); return(MagickFalse); } length=StringToLong(sp); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu",(unsigned long) length); while ((*sp != ' ' && *sp != '\n') && extent--) sp++; if (extent == 0) { png_warning(ping,"missing profile length"); return(MagickFalse); } /* allocate space */ if (length == 0) { png_warning(ping,"invalid profile length"); return(MagickFalse); } profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { png_warning(ping, "unable to copy profile"); return(MagickFalse); } /* copy profile, skipping white space and column 1 "=" signs */ dp=GetStringInfoDatum(profile); nibbles=length*2; for (i=0; i < (ssize_t) nibbles; i++) { while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f') { if (*sp == '\0') { png_warning(ping, "ran out of profile data"); profile=DestroyStringInfo(profile); return(MagickFalse); } sp++; } if (i%2 == 0) *dp=(unsigned char) (16*unhex[(int) *sp++]); else (*dp++)+=unhex[(int) *sp++]; } /* We have already read "Raw profile type. */ (void) SetImageProfile(image,&text[ii].key[17],profile,exception); profile=DestroyStringInfo(profile); if (image_info->verbose) (void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]); return MagickTrue; } static int PNGSetExifProfile(Image *image,png_size_t size,png_byte *data, ExceptionInfo *exception) { StringInfo *profile; unsigned char *p; png_byte *s; size_t i; profile=BlobToStringInfo((const void *) NULL,size+6); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); return(-1); } p=GetStringInfoDatum(profile); /* Initialize profile with "Exif\0\0" */ *p++ ='E'; *p++ ='x'; *p++ ='i'; *p++ ='f'; *p++ ='\0'; *p++ ='\0'; s=data; i=0; if (size > 6) { /* Skip first 6 bytes if "Exif\0\0" is already present by accident */ if (s[0] == 'E' && s[1] == 'x' && s[2] == 'i' && s[3] == 'f' && s[4] == '\0' && s[5] == '\0') { s+=6; i=6; SetStringInfoLength(profile,size); p=GetStringInfoDatum(profile); } } /* copy chunk->data to profile */ for (; i<size; i++) *p++ = *s++; (void) SetImageProfile(image,"exif",profile,exception); profile=DestroyStringInfo(profile); return(1); } #if defined(PNG_READ_eXIf_SUPPORTED) static void read_eXIf_chunk(Image *image,png_struct *ping,png_info *info, ExceptionInfo *exception) { png_uint_32 size; png_bytep data; #if PNG_LIBPNG_VER > 10631 if (png_get_eXIf_1(ping,info,&size,&data)) (void) PNGSetExifProfile(image,size,data,exception); #endif } #endif #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk) { Image *image; /* The unknown chunk structure contains the chunk data: png_byte name[5]; png_byte *data; png_size_t size; Note that libpng has already taken care of the CRC handling. Returns one of the following: return(-n); chunk had an error return(0); did not recognize return(n); success */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read_user_chunk: found %c%c%c%c chunk", chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]); if (chunk->name[0] == 101 && (chunk->name[1] == 88 || chunk->name[1] == 120 ) && chunk->name[2] == 73 && chunk-> name[3] == 102) { /* process eXIf or exIf chunk */ PNGErrorInfo *error_info; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " recognized eXIf chunk"); image=(Image *) png_get_user_chunk_ptr(ping); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); return(PNGSetExifProfile(image,chunk->size,chunk->data, error_info->exception)); } /* orNT */ if (chunk->name[0] == 111 && chunk->name[1] == 114 && chunk->name[2] == 78 && chunk->name[3] == 84) { /* recognized orNT */ if (chunk->size != 1) return(-1); /* Error return */ image=(Image *) png_get_user_chunk_ptr(ping); image->orientation= Magick_Orientation_from_Exif_Orientation((int) chunk->data[0]); return(1); } /* vpAg (deprecated, replaced by caNv) */ if (chunk->name[0] == 118 && chunk->name[1] == 112 && chunk->name[2] == 65 && chunk->name[3] == 103) { /* recognized vpAg */ if (chunk->size != 9) return(-1); /* Error return */ if (chunk->data[8] != 0) return(0); /* ImageMagick requires pixel units */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t)mng_get_long(chunk->data); image->page.height=(size_t)mng_get_long(&chunk->data[4]); return(1); } /* caNv */ if (chunk->name[0] == 99 && chunk->name[1] == 97 && chunk->name[2] == 78 && chunk->name[3] == 118) { /* recognized caNv */ if (chunk->size != 16) return(-1); /* Error return */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t)mng_get_long(chunk->data); image->page.height=(size_t)mng_get_long(&chunk->data[4]); image->page.x=(size_t)mng_get_long(&chunk->data[8]); image->page.y=(size_t)mng_get_long(&chunk->data[12]); return(1); } return(0); /* Did not recognize */ } #endif /* PNG_UNKNOWN_CHUNKS_SUPPORTED */ #if defined(PNG_tIME_SUPPORTED) static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info, ExceptionInfo *exception) { png_timep time; if (png_get_tIME(ping,info,&time)) { char timestamp[21]; FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ", time->year,time->month,time->day,time->hour,time->minute,time->second); SetImageProperty(image,"png:tIME",timestamp,exception); } } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the ReadOnePNGImage method is: % % Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { /* Read one PNG image */ /* To do: Read the tEXt/Creation Time chunk into the date:create property */ Image *image; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; int intent, /* "PNG Rendering intent", which is ICC intent + 1 */ num_raw_profiles, num_text, num_text_total, num_passes, number_colors, pass, ping_bit_depth, ping_color_type, ping_file_depth, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans, unit_type; double file_gamma; MagickBooleanType logging, ping_found_cHRM, ping_found_gAMA, ping_found_iCCP, ping_found_sRGB, ping_found_sRGB_cHRM, ping_preserve_iCCP, status; MemoryInfo *volatile pixel_info; PixelInfo transparent_color; PNGErrorInfo error_info; png_bytep ping_trans_alpha; png_color_16p ping_background, ping_trans_color; png_info *end_info, *ping_info; png_struct *ping; png_textp text; png_uint_32 ping_height, ping_width, x_resolution, y_resolution; QuantumInfo *volatile quantum_info; Quantum *volatile quantum_scanline; ssize_t ping_rowbytes, y; register unsigned char *p; register ssize_t i, x; register Quantum *q; size_t length, row_offset; ssize_t j; unsigned char *ping_pixels; #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED png_byte unused_chunks[]= { 104, 73, 83, 84, (png_byte) '\0', /* hIST */ 105, 84, 88, 116, (png_byte) '\0', /* iTXt */ 112, 67, 65, 76, (png_byte) '\0', /* pCAL */ 115, 67, 65, 76, (png_byte) '\0', /* sCAL */ 115, 80, 76, 84, (png_byte) '\0', /* sPLT */ #if !defined(PNG_tIME_SUPPORTED) 116, 73, 77, 69, (png_byte) '\0', /* tIME */ #endif #ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */ /* ignore the APNG chunks */ 97, 99, 84, 76, (png_byte) '\0', /* acTL */ 102, 99, 84, 76, (png_byte) '\0', /* fcTL */ 102, 100, 65, 84, (png_byte) '\0', /* fdAT */ #endif }; #endif /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,32); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,32); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOnePNGImage()\n" " IM version = %s\n" " Libpng version = %s", im_vers, libpng_vers); if (logging != MagickFalse) { if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " running with %s", zlib_runv); } } #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif #if (PNG_LIBPNG_VER >= 10400) # ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */ if (image_info->verbose) { printf("Your PNG library (libpng-%s) is an old beta version.\n", PNG_LIBPNG_VER_STRING); printf("Please update it.\n"); } # endif #endif quantum_info = (QuantumInfo *) NULL; image=mng_info->image; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before reading:\n" " image->alpha_trait=%d\n" " image->rendering_intent=%d\n" " image->colorspace=%d\n" " image->gamma=%f", (int) image->alpha_trait, (int) image->rendering_intent, (int) image->colorspace, image->gamma); } intent= Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent); /* Set to an out-of-range color unless tRNS chunk is present */ transparent_color.red=65537; transparent_color.green=65537; transparent_color.blue=65537; transparent_color.alpha=65537; number_colors=0; num_text = 0; num_text_total = 0; num_raw_profiles = 0; ping_found_cHRM = MagickFalse; ping_found_gAMA = MagickFalse; ping_found_iCCP = MagickFalse; ping_found_sRGB = MagickFalse; ping_found_sRGB_cHRM = MagickFalse; ping_preserve_iCCP = MagickFalse; /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler, NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } end_info=png_create_info_struct(ping); if (end_info == (png_info *) NULL) { png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=(MemoryInfo *) NULL; quantum_scanline = (Quantum *) NULL; quantum_info = (QuantumInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG image is corrupt. */ png_destroy_read_struct(&ping,&ping_info,&end_info); if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() with error."); if (image != (Image *) NULL) image=DestroyImageList(image); return(image); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED { const char *option; /* Reject images with too many rows or columns */ png_set_user_limits(ping,(png_uint_32) MagickMin(PNG_UINT_31_MAX, GetMagickResourceLimit(WidthResource)),(png_uint_32) MagickMin(PNG_UINT_31_MAX,GetMagickResourceLimit(HeightResource))); #if (PNG_LIBPNG_VER >= 10400) option=GetImageOption(image_info,"png:chunk-cache-max"); if (option != (const char *) NULL) png_set_chunk_cache_max(ping,(png_uint_32) MagickMin(PNG_UINT_32_MAX, StringToLong(option))); else png_set_chunk_cache_max(ping,32767); #endif #if (PNG_LIBPNG_VER >= 10401) option=GetImageOption(image_info,"png:chunk-malloc-max"); if (option != (const char *) NULL) png_set_chunk_malloc_max(ping,(png_alloc_size_t) MagickMin(PNG_SIZE_MAX, StringToLong(option))); #endif } #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for reading. */ mng_info->image_found++; png_set_sig_bytes(ping,8); if (LocaleCompare(image_info->magick,"MNG") == 0) { #if defined(PNG_MNG_FEATURES_SUPPORTED) (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); png_set_read_fn(ping,image,png_get_data); #else #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) png_permit_empty_plte(ping,MagickTrue); png_set_read_fn(ping,image,png_get_data); #else mng_info->image=image; mng_info->bytes_in_read_buffer=0; mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; png_set_read_fn(ping,mng_info,mng_get_data); #endif #endif } else png_set_read_fn(ping,image,png_get_data); { const char *value; value=GetImageOption(image_info,"png:ignore-crc"); if (value != NULL) { /* Turn off CRC checking while reading */ png_set_crc_action(ping, PNG_CRC_QUIET_USE, PNG_CRC_QUIET_USE); #ifdef PNG_IGNORE_ADLER32 /* Turn off ADLER32 checking while reading */ png_set_option(ping, PNG_IGNORE_ADLER32, PNG_OPTION_ON); #endif } value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",value) == MagickFalse) { value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) ping_preserve_iCCP=MagickTrue; #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) /* Don't let libpng check for ICC/sRGB profile because we're going * to do that anyway. This feature was added at libpng-1.6.12. * If logging, go ahead and check and issue a warning as appropriate. */ if (logging == MagickFalse) png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) else { png_set_keep_unknown_chunks(ping, 1, (png_bytep) mng_iCCP, 1); } #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* Ignore unused chunks and all unknown chunks except for caNv and vpAg */ # if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */ png_set_keep_unknown_chunks(ping, 2, NULL, 0); # else png_set_keep_unknown_chunks(ping, 1, NULL, 0); # endif png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_caNv, 1); png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_vpAg, 1); png_set_keep_unknown_chunks(ping, 1, unused_chunks, (int)sizeof(unused_chunks)/5); /* Callback for other unknown chunks */ png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback); #endif #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature */ png_set_check_for_invalid_index (ping, 0); #endif #if (PNG_LIBPNG_VER < 10400) # if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \ (PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__) /* Disable thread-unsafe features of pnggccrd */ if (png_access_version_number() >= 10200) { png_uint_32 mmx_disable_mask=0; png_uint_32 asm_flags; mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \ | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \ | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \ | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ); asm_flags=png_get_asm_flags(ping); png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask); } # endif #endif png_read_info(ping,ping_info); png_get_IHDR(ping,ping_info,&ping_width,&ping_height, &ping_bit_depth,&ping_color_type, &ping_interlace_method,&ping_compression_method, &ping_filter_method); ping_file_depth = ping_bit_depth; /* Swap bytes if requested */ if (ping_file_depth == 16) { const char *value; value=GetImageOption(image_info,"png:swap-bytes"); if (value == NULL) value=GetImageArtifact(image,"png:swap-bytes"); if (value != NULL) png_set_swap(ping); } /* Save bit-depth and color-type in case we later want to write a PNG00 */ { char msg[MagickPathExtent]; (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) ping_color_type); (void) SetImageProperty(image,"png:IHDR.color-type-orig",msg,exception); (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) ping_bit_depth); (void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg,exception); } (void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans, &ping_trans_color); (void) png_get_bKGD(ping, ping_info, &ping_background); if (ping_bit_depth < 8) { png_set_packing(ping); ping_bit_depth = 8; } image->depth=ping_bit_depth; image->depth=GetImageQuantumDepth(image,MagickFalse); image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { image->rendering_intent=UndefinedIntent; intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent); (void) memset(&image->chromaticity,0, sizeof(image->chromaticity)); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG width: %.20g, height: %.20g\n" " PNG color_type: %d, bit_depth: %d\n" " PNG compression_method: %d\n" " PNG interlace_method: %d, filter_method: %d", (double) ping_width, (double) ping_height, ping_color_type, ping_bit_depth, ping_compression_method, ping_interlace_method,ping_filter_method); } if (png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_gAMA)) { ping_found_gAMA=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG gAMA chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { ping_found_cHRM=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG cHRM chunk."); } if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { ping_found_sRGB=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG sRGB chunk."); } #ifdef PNG_READ_iCCP_SUPPORTED if (ping_found_iCCP !=MagickTrue && ping_found_sRGB != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_iCCP)) { int compression; #if (PNG_LIBPNG_VER < 10500) png_charp info; #else png_bytep info; #endif png_charp name; png_uint_32 profile_length; (void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info, &profile_length); if (profile_length != 0) { StringInfo *profile; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG iCCP chunk."); profile=BlobToStringInfo(info,profile_length); if (profile == (StringInfo *) NULL) { png_warning(ping, "ICC profile is NULL"); profile=DestroyStringInfo(profile); } else { if (ping_preserve_iCCP == MagickFalse) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } break; } } } if (sRGB_info[icheck].len == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); (void) SetImageProfile(image,"icc",profile,exception); } } else /* Preserve-iCCP */ { (void) SetImageProfile(image,"icc",profile,exception); } profile=DestroyStringInfo(profile); } } } #endif #if defined(PNG_READ_sRGB_SUPPORTED) { if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { if (png_get_sRGB(ping,ping_info,&intent)) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (intent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG sRGB chunk: rendering_intent: %d",intent); } } else if (mng_info->have_global_srgb) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (mng_info->global_srgb_intent); } } #endif { if (!png_get_gAMA(ping,ping_info,&file_gamma)) if (mng_info->have_global_gama) png_set_gAMA(ping,ping_info,mng_info->global_gamma); if (png_get_gAMA(ping,ping_info,&file_gamma)) { image->gamma=(float) file_gamma; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG gAMA chunk: gamma: %f",file_gamma); } } if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { if (mng_info->have_global_chrm != MagickFalse) { (void) png_set_cHRM(ping,ping_info, mng_info->global_chrm.white_point.x, mng_info->global_chrm.white_point.y, mng_info->global_chrm.red_primary.x, mng_info->global_chrm.red_primary.y, mng_info->global_chrm.green_primary.x, mng_info->global_chrm.green_primary.y, mng_info->global_chrm.blue_primary.x, mng_info->global_chrm.blue_primary.y); } } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { (void) png_get_cHRM(ping,ping_info, &image->chromaticity.white_point.x, &image->chromaticity.white_point.y, &image->chromaticity.red_primary.x, &image->chromaticity.red_primary.y, &image->chromaticity.green_primary.x, &image->chromaticity.green_primary.y, &image->chromaticity.blue_primary.x, &image->chromaticity.blue_primary.y); ping_found_cHRM=MagickTrue; if (image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f) ping_found_sRGB_cHRM=MagickTrue; } if (image->rendering_intent != UndefinedIntent) { if (ping_found_sRGB != MagickTrue && (ping_found_gAMA != MagickTrue || (image->gamma > .45 && image->gamma < .46)) && (ping_found_cHRM != MagickTrue || ping_found_sRGB_cHRM != MagickFalse) && ping_found_iCCP != MagickTrue) { png_set_sRGB(ping,ping_info, Magick_RenderingIntent_to_PNG_RenderingIntent (image->rendering_intent)); file_gamma=1.000f/2.200f; ping_found_sRGB=MagickTrue; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting sRGB as if in input"); } } #if defined(PNG_oFFs_SUPPORTED) if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info); image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info); if (logging != MagickFalse) if (image->page.x || image->page.y) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double) image->page.x,(double) image->page.y); } #endif #if defined(PNG_pHYs_SUPPORTED) if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { if (mng_info->have_global_phys) { png_set_pHYs(ping,ping_info, mng_info->global_x_pixels_per_unit, mng_info->global_y_pixels_per_unit, mng_info->global_phys_unit_type); } } x_resolution=0; y_resolution=0; unit_type=0; if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { /* Set image resolution. */ (void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution, &unit_type); image->resolution.x=(double) x_resolution; image->resolution.y=(double) y_resolution; if (unit_type == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->resolution.x=(double) x_resolution/100.0; image->resolution.y=(double) y_resolution/100.0; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) x_resolution,(double) y_resolution,unit_type); } #endif if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); if ((number_colors == 0) && ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)) { if (mng_info->global_plte_length) { png_set_PLTE(ping,ping_info,mng_info->global_plte, (int) mng_info->global_plte_length); if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { if (mng_info->global_trns_length) { png_warning(ping, "global tRNS has more entries than global PLTE"); } else { png_set_tRNS(ping,ping_info,mng_info->global_trns, (int) mng_info->global_trns_length,NULL); } } #ifdef PNG_READ_bKGD_SUPPORTED if ( #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED mng_info->have_saved_bkgd_index || #endif png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { png_color_16 background; #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED if (mng_info->have_saved_bkgd_index) background.index=mng_info->saved_bkgd_index; #endif if (png_get_valid(ping, ping_info, PNG_INFO_bKGD)) background.index=ping_background->index; background.red=(png_uint_16) mng_info->global_plte[background.index].red; background.green=(png_uint_16) mng_info->global_plte[background.index].green; background.blue=(png_uint_16) mng_info->global_plte[background.index].blue; background.gray=(png_uint_16) mng_info->global_plte[background.index].green; png_set_bKGD(ping,ping_info,&background); } #endif } else png_error(ping,"No global PLTE in file"); } } #ifdef PNG_READ_bKGD_SUPPORTED if (mng_info->have_global_bkgd && (!png_get_valid(ping,ping_info,PNG_INFO_bKGD))) image->background_color=mng_info->mng_global_bkgd; if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { unsigned int bkgd_scale; /* Set image background color. * Scale background components to 16-bit, then scale * to quantum depth */ bkgd_scale = 1; if (ping_file_depth == 1) bkgd_scale = 255; else if (ping_file_depth == 2) bkgd_scale = 85; else if (ping_file_depth == 4) bkgd_scale = 17; if (ping_file_depth <= 8) bkgd_scale *= 257; ping_background->red *= bkgd_scale; ping_background->green *= bkgd_scale; ping_background->blue *= bkgd_scale; if (logging != MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d)\n" " bkgd_scale=%d. ping_background=(%d,%d,%d)", ping_background->red,ping_background->green, ping_background->blue, bkgd_scale,ping_background->red, ping_background->green,ping_background->blue); } image->background_color.red= ScaleShortToQuantum(ping_background->red); image->background_color.green= ScaleShortToQuantum(ping_background->green); image->background_color.blue= ScaleShortToQuantum(ping_background->blue); image->background_color.alpha=OpaqueAlpha; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->background_color=(%.20g,%.20g,%.20g).", (double) image->background_color.red, (double) image->background_color.green, (double) image->background_color.blue); } #endif /* PNG_READ_bKGD_SUPPORTED */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { /* Image has a tRNS chunk. */ int max_sample; size_t one = 1; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG tRNS chunk."); max_sample = (int) ((one << ping_file_depth) - 1); if ((ping_color_type == PNG_COLOR_TYPE_GRAY && (int)ping_trans_color->gray > max_sample) || (ping_color_type == PNG_COLOR_TYPE_RGB && ((int)ping_trans_color->red > max_sample || (int)ping_trans_color->green > max_sample || (int)ping_trans_color->blue > max_sample))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Ignoring PNG tRNS chunk with out-of-range sample."); png_free_data(ping, ping_info, PNG_FREE_TRNS, 0); png_set_invalid(ping,ping_info,PNG_INFO_tRNS); image->alpha_trait=UndefinedPixelTrait; } else { int scale_to_short; scale_to_short = 65535L/((1UL << ping_file_depth)-1); /* Scale transparent_color to short */ transparent_color.red= scale_to_short*ping_trans_color->red; transparent_color.green= scale_to_short*ping_trans_color->green; transparent_color.blue= scale_to_short*ping_trans_color->blue; transparent_color.alpha= scale_to_short*ping_trans_color->gray; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Raw tRNS graylevel = %d, scaled graylevel = %d.", (int) ping_trans_color->gray,(int) transparent_color.alpha); } transparent_color.red=transparent_color.alpha; transparent_color.green=transparent_color.alpha; transparent_color.blue=transparent_color.alpha; } } } #if defined(PNG_READ_sBIT_SUPPORTED) if (mng_info->have_global_sbit) { if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT)) png_set_sBIT(ping,ping_info,&mng_info->global_sbit); } #endif num_passes=png_set_interlace_handling(ping); png_read_update_info(ping,ping_info); ping_rowbytes=png_get_rowbytes(ping,ping_info); /* Initialize image structure. */ mng_info->image_box.left=0; mng_info->image_box.right=(ssize_t) ping_width; mng_info->image_box.top=0; mng_info->image_box.bottom=(ssize_t) ping_height; if (mng_info->mng_type == 0) { mng_info->mng_width=ping_width; mng_info->mng_height=ping_height; mng_info->frame=mng_info->image_box; mng_info->clip=mng_info->image_box; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } image->compression=ZipCompression; image->columns=ping_width; image->rows=ping_height; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { double image_gamma = image->gamma; (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%f",(float) image_gamma); if (image_gamma > 0.75) { /* Set image->rendering_intent to Undefined, * image->colorspace to GRAY, and reset image->chromaticity. */ image->intensity = Rec709LuminancePixelIntensityMethod; SetImageColorspace(image,LinearGRAYColorspace,exception); } else { RenderingIntent save_rendering_intent = image->rendering_intent; ChromaticityInfo save_chromaticity = image->chromaticity; SetImageColorspace(image,GRAYColorspace,exception); image->rendering_intent = save_rendering_intent; image->chromaticity = save_chromaticity; } image->gamma = image_gamma; } else { double image_gamma = image->gamma; (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%f",(float) image_gamma); if (image_gamma > 0.75) { /* Set image->rendering_intent to Undefined, * image->colorspace to GRAY, and reset image->chromaticity. */ image->intensity = Rec709LuminancePixelIntensityMethod; SetImageColorspace(image,RGBColorspace,exception); } else { RenderingIntent save_rendering_intent = image->rendering_intent; ChromaticityInfo save_chromaticity = image->chromaticity; SetImageColorspace(image,sRGBColorspace,exception); image->rendering_intent = save_rendering_intent; image->chromaticity = save_chromaticity; } image->gamma = image_gamma; } (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace=%d",(int) image->colorspace); if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || ((int) ping_bit_depth < 16 && (int) ping_color_type == PNG_COLOR_TYPE_GRAY)) { size_t one; image->storage_class=PseudoClass; one=1; image->colors=one << ping_file_depth; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->colors > 256) image->colors=256; #else if (image->colors > 65536L) image->colors=65536L; #endif if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); image->colors=(size_t) number_colors; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG PLTE chunk: number_colors: %d.",number_colors); } } if (image->storage_class == PseudoClass) { /* Initialize image colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) png_error(ping,"Memory allocation failed"); if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); for (i=0; i < (ssize_t) number_colors; i++) { image->colormap[i].red=ScaleCharToQuantum(palette[i].red); image->colormap[i].green=ScaleCharToQuantum(palette[i].green); image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue); } for ( ; i < (ssize_t) image->colors; i++) { image->colormap[i].red=0; image->colormap[i].green=0; image->colormap[i].blue=0; } } } /* Set some properties for reporting by "identify" */ { char msg[MagickPathExtent]; /* encode ping_width, ping_height, ping_file_depth, ping_color_type, ping_interlace_method in value */ (void) FormatLocaleString(msg,MagickPathExtent, "%d, %d",(int) ping_width, (int) ping_height); (void) SetImageProperty(image,"png:IHDR.width,height",msg,exception); (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) ping_file_depth); (void) SetImageProperty(image,"png:IHDR.bit_depth",msg,exception); (void) FormatLocaleString(msg,MagickPathExtent,"%d (%s)", (int) ping_color_type, Magick_ColorType_from_PNG_ColorType((int)ping_color_type)); (void) SetImageProperty(image,"png:IHDR.color_type",msg,exception); if (ping_interlace_method == 0) { (void) FormatLocaleString(msg,MagickPathExtent,"%d (Not interlaced)", (int) ping_interlace_method); } else if (ping_interlace_method == 1) { (void) FormatLocaleString(msg,MagickPathExtent,"%d (Adam7 method)", (int) ping_interlace_method); } else { (void) FormatLocaleString(msg,MagickPathExtent,"%d (Unknown method)", (int) ping_interlace_method); } (void) SetImageProperty(image,"png:IHDR.interlace_method", msg,exception); if (number_colors != 0) { (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) number_colors); (void) SetImageProperty(image,"png:PLTE.number_colors",msg, exception); } } #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,ping_info,exception); #endif #if defined(PNG_READ_eXIf_SUPPORTED) read_eXIf_chunk(image,ping,ping_info,exception); #endif /* Read image scanlines. */ if (image->delay != 0) mng_info->scenes_found++; if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || ( (image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)))) { /* This happens later in non-ping decodes */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) image->storage_class=DirectClass; image->alpha_trait= (((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? BlendPixelTrait : UndefinedPixelTrait; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping PNG image data for scene %.20g",(double) mng_info->scenes_found-1); png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()."); return(image); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG IDAT chunk(s)"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif return(DestroyImageList(image)); } if (num_passes > 1) pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes* sizeof(*ping_pixels)); else pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Memory allocation failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting PNG pixels to pixel packets"); /* Convert PNG pixels to pixel packets. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Failed to allocate quantum_info"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); { MagickBooleanType found_transparent_pixel; found_transparent_pixel=MagickFalse; if (image->storage_class == DirectClass) { for (pass=0; pass < num_passes; pass++) { /* Convert image to DirectClass pixel packets. */ image->alpha_trait= (((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? BlendPixelTrait : UndefinedPixelTrait; for (y=0; y < (ssize_t) image->rows; y++) { if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayAlphaQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBAQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, IndexQuantum,ping_pixels+row_offset,exception); else /* ping_color_type == PNG_COLOR_TYPE_RGB */ (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBQuantum,ping_pixels+row_offset,exception); if (found_transparent_pixel == MagickFalse) { /* Is there a transparent pixel in the row? */ if (y== 0 && logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Looking for cheap transparent pixel"); for (x=(ssize_t) image->columns-1; x >= 0; x--) { if ((ping_color_type == PNG_COLOR_TYPE_RGBA || ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) && (GetPixelAlpha(image,q) != OpaqueAlpha)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } if ((ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_GRAY) && (ScaleQuantumToShort(GetPixelRed(image,q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(image,q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(image,q)) == transparent_color.blue)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } q+=GetPixelChannels(image); } } if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag, (MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (y < (long) image->rows) break; if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } } } else /* image->storage_class != DirectClass */ for (pass=0; pass < num_passes; pass++) { register Quantum *r; /* Convert grayscale image to PseudoClass pixel packets. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting grayscale pixels to pixel packets"); image->alpha_trait=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ? BlendPixelTrait : UndefinedPixelTrait; quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns, (image->alpha_trait == BlendPixelTrait? 2 : 1)* sizeof(*quantum_scanline)); if (quantum_scanline == (Quantum *) NULL) png_error(ping,"Memory allocation failed"); for (y=0; y < (ssize_t) image->rows; y++) { Quantum alpha; if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=ping_pixels+row_offset; r=quantum_scanline; switch (ping_bit_depth) { case 8: { if (ping_color_type == 4) for (x=(ssize_t) image->columns-1; x >= 0; x--) { *r++=*p++; alpha=ScaleCharToQuantum((unsigned char)*p++); SetPixelAlpha(image,alpha,q); if (alpha != OpaqueAlpha) found_transparent_pixel = MagickTrue; q+=GetPixelChannels(image); } else for (x=(ssize_t) image->columns-1; x >= 0; x--) *r++=*p++; break; } case 16: { for (x=(ssize_t) image->columns-1; x >= 0; x--) { #if (MAGICKCORE_QUANTUM_DEPTH >= 16) unsigned long quantum; if (image->colors > 256) quantum=(((unsigned int) *p++) << 8); else quantum=0; quantum|=(*p++); *r=ScaleShortToQuantum(quantum); r++; if (ping_color_type == 4) { if (image->colors > 256) quantum=(((unsigned int) *p++) << 8); else quantum=0; quantum|=(*p++); alpha=ScaleShortToQuantum(quantum); SetPixelAlpha(image,alpha,q); if (alpha != OpaqueAlpha) found_transparent_pixel = MagickTrue; q+=GetPixelChannels(image); } #else /* MAGICKCORE_QUANTUM_DEPTH == 8 */ *r++=(*p++); p++; /* strip low byte */ if (ping_color_type == 4) { SetPixelAlpha(image,*p++,q); if (GetPixelAlpha(image,q) != OpaqueAlpha) found_transparent_pixel = MagickTrue; p++; q+=GetPixelChannels(image); } #endif } break; } default: break; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; /* Transfer image scanline. */ r=quantum_scanline; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*r++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline); if (y < (long) image->rows) break; if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } } image->alpha_trait=found_transparent_pixel ? BlendPixelTrait : UndefinedPixelTrait; if (logging != MagickFalse) { if (found_transparent_pixel != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found transparent pixel"); else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No transparent pixel was found"); ping_color_type&=0x03; } } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->storage_class == PseudoClass) { PixelTrait alpha_trait; alpha_trait=image->alpha_trait; image->alpha_trait=UndefinedPixelTrait; (void) SyncImage(image,exception); image->alpha_trait=alpha_trait; } png_read_end(ping,end_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=%d\n",(int) image->storage_class); } if (image_info->number_scenes != 0 && mng_info->scenes_found-1 < (ssize_t) image_info->first_scene && image->delay != 0) { png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); image->colors=2; (void) SetImageBackgroundColor(image,exception); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() early."); return(image); } if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { ClassType storage_class; /* Image has a transparent background. */ storage_class=image->storage_class; image->alpha_trait=BlendPixelTrait; /* Balfour fix from imagemagick discourse server, 5 Feb 2010 */ if (storage_class == PseudoClass) { if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { for (x=0; x < ping_num_trans; x++) { image->colormap[x].alpha_trait=BlendPixelTrait; image->colormap[x].alpha = ScaleCharToQuantum((unsigned char)ping_trans_alpha[x]); } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY) { for (x=0; x < (int) image->colors; x++) { if (ScaleQuantumToShort(image->colormap[x].red) == transparent_color.alpha) { image->colormap[x].alpha_trait=BlendPixelTrait; image->colormap[x].alpha = (Quantum) TransparentAlpha; } } } (void) SyncImage(image,exception); } #if 1 /* Should have already been done above, but glennrp problem P10 * needs this. */ else { for (y=0; y < (ssize_t) image->rows; y++) { image->storage_class=storage_class; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; /* Caution: on a Q8 build, this does not distinguish between * 16-bit colors that differ only in the low byte */ for (x=(ssize_t) image->columns-1; x >= 0; x--) { if (ScaleQuantumToShort(GetPixelRed(image,q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(image,q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(image,q)) == transparent_color.blue) { SetPixelAlpha(image,TransparentAlpha,q); } else { SetPixelAlpha(image,OpaqueAlpha,q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif image->storage_class=DirectClass; } for (j = 0; j < 2; j++) { if (j == 0) status = png_get_text(ping,ping_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; else status = png_get_text(ping,end_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) for (i=0; i < (ssize_t) num_text; i++) { /* Check for a profile */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG text chunk"); if (strlen(text[i].key) > 16 && memcmp(text[i].key, "Raw profile type ",17) == 0) { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember(text[i].key+17,value) == MagickFalse) { (void) Magick_png_read_raw_profile(ping,image,image_info,text, (int) i,exception); num_raw_profiles++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Read raw profile %s",text[i].key+17); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping raw profile %s",text[i].key+17); } } else { char *value; length=text[i].text_length; value=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*value)); if (value == (char *) NULL) { png_error(ping,"Memory allocation failed"); break; } *value='\0'; (void) ConcatenateMagickString(value,text[i].text,length+2); /* Don't save "density" or "units" property if we have a pHYs * chunk */ if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) || (LocaleCompare(text[i].key,"density") != 0 && LocaleCompare(text[i].key,"units") != 0)) (void) SetImageProperty(image,text[i].key,value,exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu\n" " Keyword: %s", (unsigned long) length, text[i].key); } value=DestroyString(value); } } num_text_total += num_text; } #ifdef MNG_OBJECT_BUFFERS /* Store the object if necessary. */ if (object_id && !mng_info->frozen[object_id]) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) { /* create a new object buffer. */ mng_info->ob[object_id]=(MngBuffer *) AcquireMagickMemory(sizeof(MngBuffer)); if (mng_info->ob[object_id] != (MngBuffer *) NULL) { mng_info->ob[object_id]->image=(Image *) NULL; mng_info->ob[object_id]->reference_count=1; } } if ((mng_info->ob[object_id] == (MngBuffer *) NULL) || mng_info->ob[object_id]->frozen) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) png_error(ping,"Memory allocation failed"); if (mng_info->ob[object_id]->frozen) png_error(ping,"Cannot overwrite frozen MNG object buffer"); } else { if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image=DestroyImage (mng_info->ob[object_id]->image); mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue, exception); if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image->file=(FILE *) NULL; else png_error(ping, "Cloning image for object buffer failed"); if (ping_width > 250000L || ping_height > 250000L) png_error(ping,"PNG Image dimensions are too large."); mng_info->ob[object_id]->width=ping_width; mng_info->ob[object_id]->height=ping_height; mng_info->ob[object_id]->color_type=ping_color_type; mng_info->ob[object_id]->sample_depth=ping_bit_depth; mng_info->ob[object_id]->interlace_method=ping_interlace_method; mng_info->ob[object_id]->compression_method= ping_compression_method; mng_info->ob[object_id]->filter_method=ping_filter_method; if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp plte; /* Copy the PLTE to the object buffer. */ png_get_PLTE(ping,ping_info,&plte,&number_colors); mng_info->ob[object_id]->plte_length=number_colors; for (i=0; i < number_colors; i++) { mng_info->ob[object_id]->plte[i]=plte[i]; } } else mng_info->ob[object_id]->plte_length=0; } } #endif /* Set image->alpha_trait to MagickTrue if the input colortype supports * alpha or if a valid tRNS chunk is present, no matter whether there * is actual transparency present. */ image->alpha_trait=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? BlendPixelTrait : UndefinedPixelTrait; if (image->alpha_trait == BlendPixelTrait) (void) SetImageStorageClass(image,DirectClass,exception); #if 0 /* I'm not sure what's wrong here but it does not work. */ if (image->alpha_trait != UndefinedPixelTrait) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) SetImageType(image,GrayscaleAlphaType,exception); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteAlphaType,exception); else (void) SetImageType(image,TrueColorAlphaType,exception); } else { if (ping_color_type == PNG_COLOR_TYPE_GRAY) (void) SetImageType(image,GrayscaleType,exception); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteType,exception); else (void) SetImageType(image,TrueColorType,exception); } #endif /* Set more properties for identify to retrieve */ { char msg[MagickPathExtent]; if (num_text_total != 0) { /* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */ (void) FormatLocaleString(msg,MagickPathExtent, "%d tEXt/zTXt/iTXt chunks were found", num_text_total); (void) SetImageProperty(image,"png:text",msg, exception); } if (num_raw_profiles != 0) { (void) FormatLocaleString(msg,MagickPathExtent, "%d were found", num_raw_profiles); (void) SetImageProperty(image,"png:text-encoded profiles",msg, exception); } /* cHRM chunk: */ if (ping_found_cHRM != MagickFalse) { (void) FormatLocaleString(msg,MagickPathExtent,"%s", "chunk was found (see Chromaticity, above)"); (void) SetImageProperty(image,"png:cHRM",msg, exception); } /* bKGD chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { (void) FormatLocaleString(msg,MagickPathExtent,"%s", "chunk was found (see Background color, above)"); (void) SetImageProperty(image,"png:bKGD",msg, exception); } (void) FormatLocaleString(msg,MagickPathExtent,"%s", "chunk was found"); #if defined(PNG_iCCP_SUPPORTED) /* iCCP chunk: */ if (ping_found_iCCP != MagickFalse) (void) SetImageProperty(image,"png:iCCP",msg, exception); #endif if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) (void) SetImageProperty(image,"png:tRNS",msg, exception); #if defined(PNG_sRGB_SUPPORTED) /* sRGB chunk: */ if (ping_found_sRGB != MagickFalse) { (void) FormatLocaleString(msg,MagickPathExtent, "intent=%d (%s)", (int) intent, Magick_RenderingIntentString_from_PNG_RenderingIntent(intent)); (void) SetImageProperty(image,"png:sRGB",msg, exception); } #endif /* gAMA chunk: */ if (ping_found_gAMA != MagickFalse) { (void) FormatLocaleString(msg,MagickPathExtent, "gamma=%.8g (See Gamma, above)", file_gamma); (void) SetImageProperty(image,"png:gAMA",msg, exception); } #if defined(PNG_pHYs_SUPPORTED) /* pHYs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { (void) FormatLocaleString(msg,MagickPathExtent, "x_res=%.10g, y_res=%.10g, units=%d", (double) x_resolution,(double) y_resolution, unit_type); (void) SetImageProperty(image,"png:pHYs",msg, exception); } #endif #if defined(PNG_oFFs_SUPPORTED) /* oFFs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { (void) FormatLocaleString(msg,MagickPathExtent, "x_off=%.20g, y_off=%.20g", (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:oFFs",msg, exception); } #endif #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,end_info,exception); #endif #if defined(PNG_READ_eXIf_SUPPORTED) read_eXIf_chunk(image,ping,end_info,exception); #endif /* caNv chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || (image->page.x != 0 || image->page.y != 0)) { (void) FormatLocaleString(msg,MagickPathExtent, "width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:caNv",msg, exception); } } /* Relinquish resources. */ png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block, revert to * Throwing an Exception when an error occurs. */ return(image); /* end of reading one PNG image */ } static Image *ReadPNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MagickPathExtent]; ssize_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()"); image=AcquireImage(image_info,exception); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Verify PNG signature. */ count=ReadBlob(image,8,(unsigned char *) magic_number); if ((count < 8) || (memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a PNG datastream. */ if (GetBlobSize(image) < 61) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) memset(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOnePNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if ((image->columns == 0) || (image->rows == 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if ((IssRGBColorspace(image->colorspace) != MagickFalse) && ((image->gamma < .45) || (image->gamma > .46)) && !(image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "SetImageColorspace to RGBColorspace"); SetImageColorspace(image,RGBColorspace,exception); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace: %d", (int) image->colorspace); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()"); return(image); } #if defined(JNG_SUPPORTED) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadOneJNGImage method is: % % Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static void DestroyJNG(unsigned char *chunk,Image **color_image, ImageInfo **color_image_info,Image **alpha_image, ImageInfo **alpha_image_info) { (void) RelinquishMagickMemory(chunk); if (color_image_info && *color_image_info) { DestroyImageInfo(*color_image_info); *color_image_info = (ImageInfo *)NULL; } if (alpha_image_info && *alpha_image_info) { DestroyImageInfo(*alpha_image_info); *alpha_image_info = (ImageInfo *)NULL; } if (color_image && *color_image) { DestroyImage(*color_image); *color_image = (Image *)NULL; } if (alpha_image && *alpha_image) { DestroyImage(*alpha_image); *alpha_image = (Image *)NULL; } } static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const Quantum *s; register ssize_t i, x; register Quantum *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MagickPathExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MagickPathExtent); length=(size_t) ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) { DestroyJNG(NULL,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (length > GetBlobSize(image)) { DestroyJNG(NULL,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } for ( ; i < (ssize_t) length; i++) chunk[i]='\0'; p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(png_uint_32)mng_get_long(p); jng_height=(png_uint_32)mng_get_long(&p[4]); if ((jng_width == 0) || (jng_height == 0)) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError, "NegativeOrZeroImageSize"); } jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (jng_width > 65535 || jng_height > 65535 || (long) jng_width > GetMagickResourceLimit(WidthResource) || (long) jng_height > GetMagickResourceLimit(HeightResource)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width or height too large: (%lu x %lu)", (long) jng_width, (long) jng_height); DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info,exception); if (color_image == (Image *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); (void) AcquireUniqueFilename(color_image->filename); status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info,exception); if (alpha_image == (Image *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if ((length != 0) && (color_image != (Image *) NULL)) (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if ((alpha_image != NULL) && (image_info->ping == MagickFalse) && (length != 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->resolution.x=(double) mng_get_long(p); image->resolution.y=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->resolution.x=image->resolution.x/100.0f; image->resolution.y=image->resolution.y/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into alpha samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); if (color_image != (Image *) NULL) color_image=DestroyImageList(color_image); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MagickPathExtent, "jpeg:%s",color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) { DestroyJNG(NULL,NULL,NULL,&alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->rows=jng_height; image->columns=jng_width; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, &alpha_image_info); jng_image=DestroyImageList(jng_image); return(DestroyImageList(image)); } if ((image->columns != jng_image->columns) || (image->rows != jng_image->rows)) { DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, &alpha_image_info); jng_image=DestroyImageList(jng_image); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelRed(image,GetPixelRed(jng_image,s),q); SetPixelGreen(image,GetPixelGreen(jng_image,s),q); SetPixelBlue(image,GetPixelBlue(jng_image,s),q); q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) CloseBlob(alpha_image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading alpha from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MagickPathExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; if (image->alpha_trait != UndefinedPixelTrait) for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelAlpha(image,GetPixelRed(jng_image,s),q); q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } else for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelAlpha(image,GetPixelRed(jng_image,s),q); if (GetPixelAlpha(image,q) != OpaqueAlpha) image->alpha_trait=BlendPixelTrait; q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage()"); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJNGImage() reads a JPEG Network Graphics (JNG) image file % (including the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadJNGImage method is: % % Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo % *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MagickPathExtent]; size_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()"); image=AcquireImage(image_info,exception); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (LocaleCompare(image_info->magick,"JNG") != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify JNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if ((count < 8) || (memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a JNG datastream. */ if (GetBlobSize(image) < 147) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) memset(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneJNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (image->columns == 0 || image->rows == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); ThrowReaderException(CorruptImageError,"CorruptImage"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()"); return(image); } #endif static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MagickPathExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if ((count < 8) || (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False during convert or mogrify */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MagickPathExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if ((length > PNG_UINT_31_MAX) || (length > GetBlobSize(image)) || (count < 4)) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 9) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) { (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream","`%s'", image->filename); if (object_id >= MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS-1; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { /* Read global PLTE. */ if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) { mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (((p-chunk) < (long) length) && *p) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || (length % 2) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters <= 0) skipping_loop=loop_level; else { if (loop_iters > GetMagickResourceLimit(ListLengthResource)) loop_iters=GetMagickResourceLimit(ListLengthResource); if (loop_iters >= 2147483647L) loop_iters=2147483647L; mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=((png_uint_32) p[12] << 8) & (png_uint_32) p[13]; else basi_red=0; if (length > 13) basi_green=((png_uint_32) p[14] << 8) & (png_uint_32) p[15]; else basi_green=0; if (length > 15) basi_blue=((png_uint_32) p[16] << 8) & (png_uint_32) p[17]; else basi_blue=0; if (length > 17) basi_alpha=((png_uint_32) p[18] << 8) & (png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { if (prev != (Quantum *) NULL) prev=(Quantum *) RelinquishMagickMemory(prev); if (next != (Quantum *) NULL) next=(Quantum *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) memcpy(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) memcpy(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (Quantum *) NULL) break; q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { /* Interpolate */ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelChannel() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } /* To do: Rewrite using Get/Set***PixelChannel() */ else { /* Interpolate */ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { /* Interpolate */ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneMNGImage();"); return(image); } static Image *ReadMNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()"); image=AcquireImage(image_info,exception); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) memset(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneMNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadMNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()"); return(GetFirstImageInList(image)); } #else /* PNG_LIBPNG_VER > 10011 */ static Image *ReadPNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "PNG library is too old","`%s'",image_info->filename); return(Image *) NULL; } static Image *ReadMNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { return(ReadPNGImage(image_info,exception)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNGImage() adds properties for the PNG image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNGImage method is: % % size_t RegisterPNGImage(void) % */ ModuleExport size_t RegisterPNGImage(void) { char version[MagickPathExtent]; MagickInfo *entry; static const char *PNGNote= { "See http://www.libpng.org/ for details about the PNG format." }, *JNGNote= { "See http://www.libpng.org/pub/mng/ for details about the JNG\n" "format." }, *MNGNote= { "See http://www.libpng.org/pub/mng/ for details about the MNG\n" "format." }; *version='\0'; #if defined(PNG_LIBPNG_VER_STRING) (void) ConcatenateMagickString(version,"libpng ",MagickPathExtent); (void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING, MagickPathExtent); if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0) { (void) ConcatenateMagickString(version,",",MagickPathExtent); (void) ConcatenateMagickString(version,png_get_libpng_ver(NULL), MagickPathExtent); } #endif entry=AcquireMagickInfo("PNG","MNG","Multiple-image Network Graphics"); entry->flags|=CoderDecoderSeekableStreamFlag; #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMNGImage; entry->encoder=(EncodeImageHandler *) WriteMNGImage; #endif entry->magick=(IsImageFormatHandler *) IsMNG; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("video/x-mng"); entry->note=ConstantString(MNGNote); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG","Portable Network Graphics"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); if (*version != '\0') entry->version=ConstantString(version); entry->note=ConstantString(PNGNote); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG8", "8-bit indexed with optional binary transparency"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG24", "opaque or binary transparent 24-bit RGB"); *version='\0'; #if defined(ZLIB_VERSION) (void) ConcatenateMagickString(version,"zlib ",MagickPathExtent); (void) ConcatenateMagickString(version,ZLIB_VERSION,MagickPathExtent); if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0) { (void) ConcatenateMagickString(version,",",MagickPathExtent); (void) ConcatenateMagickString(version,zlib_version,MagickPathExtent); } #endif if (*version != '\0') entry->version=ConstantString(version); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG32","opaque or transparent 32-bit RGBA"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG48", "opaque or binary transparent 48-bit RGB"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG64","opaque or transparent 64-bit RGBA"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG00", "PNG inheriting bit-depth, color-type from original, if possible"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","JNG","JPEG Network Graphics"); #if defined(JNG_SUPPORTED) #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJNGImage; entry->encoder=(EncodeImageHandler *) WriteJNGImage; #endif #endif entry->magick=(IsImageFormatHandler *) IsJNG; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/x-jng"); entry->note=ConstantString(JNGNote); (void) RegisterMagickInfo(entry); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE ping_semaphore=AcquireSemaphoreInfo(); #endif return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNGImage() removes format registrations made by the % PNG module from the list of supported formats. % % The format of the UnregisterPNGImage method is: % % UnregisterPNGImage(void) % */ ModuleExport void UnregisterPNGImage(void) { (void) UnregisterMagickInfo("MNG"); (void) UnregisterMagickInfo("PNG"); (void) UnregisterMagickInfo("PNG8"); (void) UnregisterMagickInfo("PNG24"); (void) UnregisterMagickInfo("PNG32"); (void) UnregisterMagickInfo("PNG48"); (void) UnregisterMagickInfo("PNG64"); (void) UnregisterMagickInfo("PNG00"); (void) UnregisterMagickInfo("JNG"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE if (ping_semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&ping_semaphore); #endif } #if defined(MAGICKCORE_PNG_DELEGATE) #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMNGImage() writes an image in the Portable Network Graphics % Group's "Multiple-image Network Graphics" encoded image format. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteMNGImage method is: % % MagickBooleanType WriteMNGImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % % To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also % "To do" under ReadPNGImage): % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % Write the iCCP chunk at MNG level when (icc profile length > 0) % % Improve selection of color type (use indexed-colour or indexed-colour % with tRNS when 256 or fewer unique RGBA values are present). % % Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3) % This will be complicated if we limit ourselves to generating MNG-LC % files. For now we ignore disposal method 3 and simply overlay the next % image on it. % % Check for identical PLTE's or PLTE/tRNS combinations and use a % global MNG PLTE or PLTE/tRNS combination when appropriate. % [mostly done 15 June 1999 but still need to take care of tRNS] % % Check for identical sRGB and replace with a global sRGB (and remove % gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and % replace with global gAMA/cHRM (or with sRGB if appropriate; replace % local gAMA/cHRM with local sRGB if appropriate). % % Check for identical sBIT chunks and write global ones. % % Provide option to skip writing the signature tEXt chunks. % % Use signatures to detect identical objects and reuse the first % instance of such objects instead of writing duplicate objects. % % Use a smaller-than-32k value of compression window size when % appropriate. % % Encode JNG datastreams. Mostly done as of 5.5.2; need to write % ancillary text chunks and save profiles. % % Provide an option to force LC files (to ensure exact framing rate) % instead of VLC. % % Provide an option to force VLC files instead of LC, even when offsets % are present. This will involve expanding the embedded images with a % transparent region at the top and/or left. */ static void Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping, png_info *ping_info, unsigned char *profile_type, unsigned char *profile_description, unsigned char *profile_data, png_uint_32 length) { png_textp text; register ssize_t i; unsigned char *sp; png_charp dp; png_uint_32 allocated_length, description_length; unsigned char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0) return; if (image_info->verbose) { (void) printf("writing raw profile: type=%s, length=%.20g\n", (char *) profile_type, (double) length); } #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif description_length=(png_uint_32) strlen((const char *) profile_description); allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20 + description_length); #if PNG_LIBPNG_VER >= 10400 text[0].text=(png_charp) png_malloc(ping, (png_alloc_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80); #else text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80); #endif text[0].key[0]='\0'; (void) ConcatenateMagickString(text[0].key, "Raw profile type ",MagickPathExtent); (void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62); sp=profile_data; dp=text[0].text; *dp++='\n'; (void) CopyMagickString(dp,(const char *) profile_description, allocated_length); dp+=description_length; *dp++='\n'; (void) FormatLocaleString(dp,allocated_length- (png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length); dp+=8; for (i=0; i < (ssize_t) length; i++) { if (i%36 == 0) *dp++='\n'; *(dp++)=(char) hex[((*sp >> 4) & 0x0f)]; *(dp++)=(char) hex[((*sp++ ) & 0x0f)]; } *dp++='\n'; *dp='\0'; text[0].text_length=(png_size_t) (dp-text[0].text); text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? -1 : 0; if (text[0].text_length <= allocated_length) png_set_text(ping,ping_info,text,1); png_free(ping,text[0].text); png_free(ping,text[0].key); png_free(ping,text); } static inline MagickBooleanType IsColorEqual(const Image *image, const Quantum *p, const PixelInfo *q) { MagickRealType blue, green, red; red=(MagickRealType) GetPixelRed(image,p); green=(MagickRealType) GetPixelGreen(image,p); blue=(MagickRealType) GetPixelBlue(image,p); if ((AbsolutePixelValue(red-q->red) < MagickEpsilon) && (AbsolutePixelValue(green-q->green) < MagickEpsilon) && (AbsolutePixelValue(blue-q->blue) < MagickEpsilon)) return(MagickTrue); return(MagickFalse); } #if defined(PNG_tIME_SUPPORTED) static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info, const char *timestamp,ExceptionInfo *exception) { int ret; int day, hour, minute, month, second, year; int addhours=0, addminutes=0; png_time ptime; assert(timestamp != (const char *) NULL); LogMagickEvent(CoderEvent,GetMagickModule(), " Writing tIME chunk: timestamp property is %30s\n",timestamp); ret=sscanf(timestamp,"%d-%d-%dT%d:%d:%d",&year,&month,&day,&hour, &minute, &second); addhours=0; addminutes=0; ret=sscanf(timestamp,"%d-%d-%dT%d:%d:%d%d:%d",&year,&month,&day,&hour, &minute, &second, &addhours, &addminutes); LogMagickEvent(CoderEvent,GetMagickModule(), " Date format specified for png:tIME=%s" ,timestamp); LogMagickEvent(CoderEvent,GetMagickModule(), " ret=%d,y=%d, m=%d, d=%d, h=%d, m=%d, s=%d, ah=%d, as=%d", ret,year,month,day,hour,minute,second,addhours,addminutes); if (ret < 6) { LogMagickEvent(CoderEvent,GetMagickModule(), " Invalid date, ret=%d",ret); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "Invalid date format specified for png:tIME","`%s' (ret=%d)", image->filename,ret); return; } if (addhours < 0) { addhours+=24; addminutes=-addminutes; day--; } hour+=addhours; minute+=addminutes; if (day == 0) { month--; day=31; if(month == 2) day=28; else { if(month == 4 || month == 6 || month == 9 || month == 11) day=30; else day=31; } } if (month == 0) { month++; year--; } if (minute > 59) { hour++; minute-=60; } if (hour > 23) { day ++; hour -=24; } if (hour < 0) { day --; hour +=24; } /* To do: fix this for leap years */ if (day > 31 || (month == 2 && day > 28) || ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30)) { month++; day = 1; } if (month > 12) { year++; month=1; } ptime.year = year; ptime.month = month; ptime.day = day; ptime.hour = hour; ptime.minute = minute; ptime.second = second; LogMagickEvent(CoderEvent,GetMagickModule(), " png_set_tIME: y=%d, m=%d, d=%d, h=%d, m=%d, s=%d, ah=%d, am=%d", ptime.year, ptime.month, ptime.day, ptime.hour, ptime.minute, ptime.second, addhours, addminutes); png_set_tIME(ping,info,&ptime); } #endif /* Write one PNG image */ static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char s[2]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%g", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBA(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBA(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBA(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *s; register Quantum *q, *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->alpha_trait=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,q) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image, q, opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(image,q,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image, q, opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,q) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image, q, transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,q); ping_trans_color.green=(unsigned short) GetPixelGreen(image,q); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,q); ping_trans_color.gray=(unsigned short) GetPixelGray(image,q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(image,q,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,q,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,q,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(image,q,semitransparent+i) && GetPixelAlpha(image,q) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image, q, semitransparent+i); } } } q+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != GetPixelGreen(image,s) || GetPixelRed(image,s) != GetPixelBlue(image,s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != 0 && GetPixelRed(image,s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) < OpaqueAlpha/2) { SetPixelViaPixelInfo(image,&image->background_color,r); SetPixelAlpha(image,TransparentAlpha,r); } else SetPixelAlpha(image,OpaqueAlpha,r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha/2 ? TransparentAlpha : OpaqueAlpha); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR04PixelRGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR03RGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR02PixelBlue(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 && GetPixelAlpha(image,r) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),r); } r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",IMimage->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } else if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; else { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates "-define png:compression-strategy", etc. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { /* Add an opaque matte channel */ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { /* Do not write hex-encoded ICC chunk */ name=GetNextImageProfile(image); continue; } } #endif /* WRITE_iCCP */ if (LocaleCompare(name,"exif") == 0) { /* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk */ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXt chunk with uuencoded %s profile", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); /* write orNT if image->orientation is defined */ if (image->orientation != UndefinedOrientation) { unsigned char chunk[6]; (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_orNT); LogPNGChunk(logging,mng_orNT,1L); /* PNG uses Exif orientation values */ chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const Quantum *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write eXIf profile */ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; /* otherwise crashes */ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\0' && *(data+5) == '\0') { /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNGImage() writes a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WritePNGImage method is: % % MagickBooleanType WritePNGImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % % Returns MagickTrue on success, MagickFalse on failure. % % Communicating with the PNG encoder: % % While the datastream written is always in PNG format and normally would % be given the "png" file extension, this method also writes the following % pseudo-formats which are subsets of png: % % o PNG8: An 8-bit indexed PNG datastream is written. If the image has % a depth greater than 8, the depth is reduced. If transparency % is present, the tRNS chunk must only have values 0 and 255 % (i.e., transparency is binary: fully opaque or fully % transparent). If other values are present they will be % 50%-thresholded to binary transparency. If more than 256 % colors are present, they will be quantized to the 4-4-4-1, % 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color % of any resulting fully-transparent pixels is changed to % the image's background color. % % If you want better quantization or dithering of the colors % or alpha than that, you need to do it before calling the % PNG encoder. The pixels contain 8-bit indices even if % they could be represented with 1, 2, or 4 bits. Grayscale % images will be written as indexed PNG files even though the % PNG grayscale type might be slightly more efficient. Please % note that writing to the PNG8 format may result in loss % of color and alpha data. % % o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. The only loss incurred % is reduction of sample depth to 8. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG32: An 8-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 255. The alpha % channel is present even if the image is fully opaque. % The only loss in data is the reduction of the sample depth % to 8. % % o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG64: A 16-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 65535. The alpha % channel is present even if the image is fully opaque. % % o PNG00: A PNG that inherits its colortype and bit-depth from the input % image, if the input was a PNG, is written. If these values % cannot be found, or if the pixels have been changed in a way % that makes this impossible, then "PNG00" falls back to the % regular "PNG" format. % % o -define: For more precise control of the PNG output, you can use the % Image options "png:bit-depth" and "png:color-type". These % can be set from the commandline with "-define" and also % from the application programming interfaces. The options % are case-independent and are converted to lowercase before % being passed to this encoder. % % png:color-type can be 0, 2, 3, 4, or 6. % % When png:color-type is 0 (Grayscale), png:bit-depth can % be 1, 2, 4, 8, or 16. % % When png:color-type is 2 (RGB), png:bit-depth can % be 8 or 16. % % When png:color-type is 3 (Indexed), png:bit-depth can % be 1, 2, 4, or 8. This refers to the number of bits % used to store the index. The color samples always have % bit-depth 8 in indexed PNG files. % % When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte), % png:bit-depth can be 8 or 16. % % If the image cannot be written without loss with the % requested bit-depth and color-type, a PNG file will not % be written, a warning will be issued, and the encoder will % return MagickFalse. % % Since image encoders should not be responsible for the "heavy lifting", % the user should make sure that ImageMagick has already reduced the % image depth and number of colors and limit transparency to binary % transparency prior to attempting to write the image with depth, color, % or transparency limitations. % % Note that another definition, "png:bit-depth-written" exists, but it % is not intended for external use. It is only used internally by the % PNG encoder to inform the JNG encoder of the depth of the alpha channel. % % As of version 6.6.6 the following optimizations are always done: % % o 32-bit depth is reduced to 16. % o 16-bit depth is reduced to 8 if all pixels contain samples whose % high byte and low byte are identical. % o Palette is sorted to remove unused entries and to put a % transparent color first, if BUILD_PNG_PALETTE is defined. % o Opaque matte channel is removed when writing an indexed PNG. % o Grayscale images are reduced to 1, 2, or 4 bit depth if % this can be done without loss and a larger bit depth N was not % requested via the "-define png:bit-depth=N" option. % o If matte channel is present but only one transparent color is % present, RGB+tRNS is written instead of RGBA % o Opaque matte channel is removed (or added, if color-type 4 or 6 % was requested when converting an opaque image). % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { MagickBooleanType excluding, logging, status; MngInfo *mng_info; const char *value; int source; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) memset(mng_info,0,sizeof(MngInfo)); mng_info->image=image; mng_info->equal_backgrounds=MagickTrue; /* See if user has requested a specific PNG subformat */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0; mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0; value=GetImageOption(image_info,"png:format"); if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",value); mng_info->write_png8 = MagickFalse; mng_info->write_png24 = MagickFalse; mng_info->write_png32 = MagickFalse; mng_info->write_png48 = MagickFalse; mng_info->write_png64 = MagickFalse; if (LocaleCompare(value,"png8") == 0) mng_info->write_png8 = MagickTrue; else if (LocaleCompare(value,"png24") == 0) mng_info->write_png24 = MagickTrue; else if (LocaleCompare(value,"png32") == 0) mng_info->write_png32 = MagickTrue; else if (LocaleCompare(value,"png48") == 0) mng_info->write_png48 = MagickTrue; else if (LocaleCompare(value,"png64") == 0) mng_info->write_png64 = MagickTrue; else if ((LocaleCompare(value,"png00") == 0) || LocaleCompare(image_info->magick,"PNG00") == 0) { /* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig. */ value=GetImageProperty(image,"png:IHDR.bit-depth-orig",exception); if (value != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited bit depth=%s",value); if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; } value=GetImageProperty(image,"png:IHDR.color-type-orig",exception); if (value != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited color type=%s",value); if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; } } } if (mng_info->write_png8) { mng_info->write_png_colortype = /* 3 */ 4; mng_info->write_png_depth = 8; image->depth = 8; } if (mng_info->write_png24) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 8; image->depth = 8; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageType(image,TrueColorAlphaType,exception); else (void) SetImageType(image,TrueColorType,exception); (void) SyncImage(image,exception); } if (mng_info->write_png32) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 8; image->depth = 8; image->alpha_trait = BlendPixelTrait; (void) SetImageType(image,TrueColorAlphaType,exception); (void) SyncImage(image,exception); } if (mng_info->write_png48) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 16; image->depth = 16; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageType(image,TrueColorAlphaType,exception); else (void) SetImageType(image,TrueColorType,exception); (void) SyncImage(image,exception); } if (mng_info->write_png64) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 16; image->depth = 16; image->alpha_trait = BlendPixelTrait; (void) SetImageType(image,TrueColorAlphaType,exception); (void) SyncImage(image,exception); } value=GetImageOption(image_info,"png:bit-depth"); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:bit-depth", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:bit-depth=%d was defined.\n",mng_info->write_png_depth); } value=GetImageOption(image_info,"png:color-type"); if (value != (char *) NULL) { /* We must store colortype+1 because 0 is a valid colortype */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_colortype = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:color-type", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:color-type=%d was defined.\n", mng_info->write_png_colortype-1); } /* Check for chunks to be excluded: * * The default is to not exclude any known chunks except for any * listed in the "unused_chunks" array, above. * * Chunks can be listed for exclusion via a "png:exclude-chunk" * define (in the image properties or in the image artifacts) * or via a mng_info member. For convenience, in addition * to or instead of a comma-separated list of chunks, the * "exclude-chunk" string can be simply "all" or "none". * * Note that the "-strip" option provides a convenient way of * doing the equivalent of * * -define png:exclude-chunk="bKGD,caNv,cHRM,eXIf,gAMA,iCCP, * iTXt,pHYs,sRGB,tEXt,zCCP,zTXt,date" * * The exclude-chunk define takes priority over the mng_info. * * A "png:include-chunk" define takes priority over both the * mng_info and the "png:exclude-chunk" define. Like the * "exclude-chunk" string, it can define "all" or "none" as * well as a comma-separated list. Chunks that are unknown to * ImageMagick are always excluded, regardless of their "copy-safe" * status according to the PNG specification, and even if they * appear in the "include-chunk" list. Such defines appearing among * the image options take priority over those found among the image * artifacts. * * Finally, all chunks listed in the "unused_chunks" array are * automatically excluded, regardless of the other instructions * or lack thereof. * * if you exclude sRGB but not gAMA (recommended), then sRGB chunk * will not be written and the gAMA chunk will only be written if it * is not between .45 and .46, or approximately (1.0/2.2). * * If you exclude tRNS and the image has transparency, the colortype * is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA). * * The -strip option causes StripImage() to set the png:include-chunk * artifact to "none,trns,gama". */ mng_info->ping_exclude_bKGD=MagickFalse; mng_info->ping_exclude_caNv=MagickFalse; mng_info->ping_exclude_cHRM=MagickFalse; mng_info->ping_exclude_date=MagickFalse; mng_info->ping_exclude_eXIf=MagickFalse; mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */ mng_info->ping_exclude_gAMA=MagickFalse; mng_info->ping_exclude_iCCP=MagickFalse; /* mng_info->ping_exclude_iTXt=MagickFalse; */ mng_info->ping_exclude_oFFs=MagickFalse; mng_info->ping_exclude_pHYs=MagickFalse; mng_info->ping_exclude_sRGB=MagickFalse; mng_info->ping_exclude_tEXt=MagickFalse; mng_info->ping_exclude_tIME=MagickFalse; mng_info->ping_exclude_tRNS=MagickFalse; mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */ mng_info->ping_exclude_zTXt=MagickFalse; mng_info->ping_preserve_colormap=MagickFalse; value=GetImageOption(image_info,"png:preserve-colormap"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-colormap"); if (value != NULL) mng_info->ping_preserve_colormap=MagickTrue; mng_info->ping_preserve_iCCP=MagickFalse; value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) mng_info->ping_preserve_iCCP=MagickTrue; /* These compression-level, compression-strategy, and compression-filter * defines take precedence over values from the -quality option. */ value=GetImageOption(image_info,"png:compression-level"); if (value == NULL) value=GetImageArtifact(image,"png:compression-level"); if (value != NULL) { /* We have to add 1 to everything because 0 is a valid input, * and we want to use 0 (the default) to mean undefined. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_level = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_level = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_level = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_level = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_level = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_level = 6; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_compression_level = 7; else if (LocaleCompare(value,"7") == 0) mng_info->write_png_compression_level = 8; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_compression_level = 9; else if (LocaleCompare(value,"9") == 0) mng_info->write_png_compression_level = 10; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-level", "=%s",value); } value=GetImageOption(image_info,"png:compression-strategy"); if (value == NULL) value=GetImageArtifact(image,"png:compression-strategy"); if (value != NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_strategy = Z_FILTERED+1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; else if (LocaleCompare(value,"3") == 0) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy = Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else if (LocaleCompare(value,"4") == 0) #ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */ mng_info->write_png_compression_strategy = Z_FIXED+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-strategy", "=%s",value); } value=GetImageOption(image_info,"png:compression-filter"); if (value == NULL) value=GetImageArtifact(image,"png:compression-filter"); if (value != NULL) { /* To do: combinations of filters allowed by libpng * masks 0x08 through 0xf8 * * Implement this as a comma-separated list of 0,1,2,3,4,5 * where 5 is a special case meaning PNG_ALL_FILTERS. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_filter = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_filter = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_filter = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_filter = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_filter = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_filter = 6; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-filter", "=%s",value); } for (source=0; source<8; source++) { value = NULL; if (source == 0) value=GetImageOption(image_info,"png:exclude-chunks"); if (source == 1) value=GetImageArtifact(image,"png:exclude-chunks"); if (source == 2) value=GetImageOption(image_info,"png:exclude-chunk"); if (source == 3) value=GetImageArtifact(image,"png:exclude-chunk"); if (source == 4) value=GetImageOption(image_info,"png:include-chunks"); if (source == 5) value=GetImageArtifact(image,"png:include-chunks"); if (source == 6) value=GetImageOption(image_info,"png:include-chunk"); if (source == 7) value=GetImageArtifact(image,"png:include-chunk"); if (value == NULL) continue; if (source < 4) excluding = MagickTrue; else excluding = MagickFalse; if (logging != MagickFalse) { if (source == 0 || source == 2) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image options.\n", value); else if (source == 1 || source == 3) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image artifacts.\n", value); else if (source == 4 || source == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image options.\n", value); else /* if (source == 5 || source == 7) */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image artifacts.\n", value); } if (IsOptionMember("all",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding; mng_info->ping_exclude_caNv=excluding; mng_info->ping_exclude_cHRM=excluding; mng_info->ping_exclude_date=excluding; mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; mng_info->ping_exclude_gAMA=excluding; mng_info->ping_exclude_iCCP=excluding; /* mng_info->ping_exclude_iTXt=excluding; */ mng_info->ping_exclude_oFFs=excluding; mng_info->ping_exclude_pHYs=excluding; mng_info->ping_exclude_sRGB=excluding; mng_info->ping_exclude_tEXt=excluding; mng_info->ping_exclude_tIME=excluding; mng_info->ping_exclude_tRNS=excluding; mng_info->ping_exclude_zCCP=excluding; mng_info->ping_exclude_zTXt=excluding; } if (IsOptionMember("none",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; /* mng_info->ping_exclude_iTXt=!excluding; */ mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse : MagickTrue; } if (IsOptionMember("bkgd",value) != MagickFalse) mng_info->ping_exclude_bKGD=excluding; if (IsOptionMember("caNv",value) != MagickFalse) mng_info->ping_exclude_caNv=excluding; if (IsOptionMember("chrm",value) != MagickFalse) mng_info->ping_exclude_cHRM=excluding; if (IsOptionMember("date",value) != MagickFalse) mng_info->ping_exclude_date=excluding; if (IsOptionMember("exif",value) != MagickFalse) { mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; } if (IsOptionMember("gama",value) != MagickFalse) mng_info->ping_exclude_gAMA=excluding; if (IsOptionMember("iccp",value) != MagickFalse) mng_info->ping_exclude_iCCP=excluding; #if 0 if (IsOptionMember("itxt",value) != MagickFalse) mng_info->ping_exclude_iTXt=excluding; #endif if (IsOptionMember("offs",value) != MagickFalse) mng_info->ping_exclude_oFFs=excluding; if (IsOptionMember("phys",value) != MagickFalse) mng_info->ping_exclude_pHYs=excluding; if (IsOptionMember("srgb",value) != MagickFalse) mng_info->ping_exclude_sRGB=excluding; if (IsOptionMember("text",value) != MagickFalse) mng_info->ping_exclude_tEXt=excluding; if (IsOptionMember("time",value) != MagickFalse) mng_info->ping_exclude_tIME=excluding; if (IsOptionMember("trns",value) != MagickFalse) mng_info->ping_exclude_tRNS=excluding; if (IsOptionMember("zccp",value) != MagickFalse) mng_info->ping_exclude_zCCP=excluding; if (IsOptionMember("ztxt",value) != MagickFalse) mng_info->ping_exclude_zTXt=excluding; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Chunks to be excluded from the output png:"); if (mng_info->ping_exclude_bKGD != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bKGD"); if (mng_info->ping_exclude_caNv != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " caNv"); if (mng_info->ping_exclude_cHRM != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " cHRM"); if (mng_info->ping_exclude_date != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " date"); if (mng_info->ping_exclude_EXIF != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " EXIF"); if (mng_info->ping_exclude_eXIf != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " eXIf"); if (mng_info->ping_exclude_gAMA != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " gAMA"); if (mng_info->ping_exclude_iCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iCCP"); #if 0 if (mng_info->ping_exclude_iTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iTXt"); #endif if (mng_info->ping_exclude_oFFs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " oFFs"); if (mng_info->ping_exclude_pHYs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pHYs"); if (mng_info->ping_exclude_sRGB != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " sRGB"); if (mng_info->ping_exclude_tEXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tEXt"); if (mng_info->ping_exclude_tIME != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tIME"); if (mng_info->ping_exclude_tRNS != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS"); if (mng_info->ping_exclude_zCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zCCP"); if (mng_info->ping_exclude_zTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zTXt"); } mng_info->need_blob = MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image,exception); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()"); return(status); } #if defined(JNG_SUPPORTED) /* Write one JNG image */ static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image,ExceptionInfo *exception) { Image *jpeg_image; ImageInfo *jpeg_image_info; MagickBooleanType logging, status; size_t length; unsigned char *blob, chunk[80], *p; unsigned int jng_alpha_compression_method, jng_alpha_sample_depth, jng_color_type, transparent; size_t jng_alpha_quality, jng_quality; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOneJNGImage()"); blob=(unsigned char *) NULL; jpeg_image=(Image *) NULL; jpeg_image_info=(ImageInfo *) NULL; length=0; status=MagickTrue; transparent=image_info->type==GrayscaleAlphaType || image_info->type==TrueColorAlphaType || image->alpha_trait != UndefinedPixelTrait; jng_alpha_sample_depth = 0; jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000; jng_alpha_compression_method=(image->compression==JPEGCompression || image_info->compression==JPEGCompression) ? 8 : 0; jng_alpha_quality=image_info->quality == 0UL ? 75UL : image_info->quality; if (jng_alpha_quality >= 1000) jng_alpha_quality /= 1000; length=0; if (transparent != 0) { jng_color_type=14; /* Create JPEG blob, image, and image_info */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info for alpha."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) { jpeg_image_info=DestroyImageInfo(jpeg_image_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=SeparateImage(image,AlphaChannel,exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); jpeg_image->alpha_trait=UndefinedPixelTrait; jpeg_image->quality=jng_alpha_quality; jpeg_image_info->type=GrayscaleType; (void) SetImageType(jpeg_image,GrayscaleType,exception); (void) AcquireUniqueFilename(jpeg_image->filename); (void) FormatLocaleString(jpeg_image_info->filename,MagickPathExtent, "%s",jpeg_image->filename); } else { jng_alpha_compression_method=0; jng_color_type=10; jng_alpha_sample_depth=0; } /* To do: check bit depth of PNG alpha channel */ /* Check if image is grayscale. */ if (image_info->type != TrueColorAlphaType && image_info->type != TrueColorType && SetImageGray(image,exception)) jng_color_type-=2; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Quality = %d",(int) jng_quality); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Color Type = %d",jng_color_type); if (transparent != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Compression = %d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Depth = %d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Quality = %d",(int) jng_alpha_quality); } } if (transparent != 0) { if (jng_alpha_compression_method==0) { const char *value; /* Encode alpha as a grayscale PNG blob */ status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating PNG blob."); (void) CopyMagickString(jpeg_image_info->magick,"PNG", MagickPathExtent); (void) CopyMagickString(jpeg_image->magick,"PNG",MagickPathExtent); jpeg_image_info->interlace=NoInterlace; /* Exclude all ancillary chunks */ (void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all"); blob=(unsigned char *) ImageToBlob(jpeg_image_info,jpeg_image, &length,exception); /* Retrieve sample depth used */ value=GetImageProperty(jpeg_image,"png:bit-depth-written",exception); if (value != (char *) NULL) jng_alpha_sample_depth= (unsigned int) value[0]; } else { /* Encode alpha as a grayscale JPEG blob */ status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image_info->magick,"JPEG", MagickPathExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); jpeg_image_info->interlace=NoInterlace; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=(unsigned char *) ImageToBlob(jpeg_image_info, jpeg_image,&length, exception); jng_alpha_sample_depth=8; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); } /* Destroy JPEG image and image_info */ jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); jpeg_image_info=DestroyImageInfo(jpeg_image_info); } /* Write JHDR chunk */ (void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */ PNGType(chunk,mng_JHDR); LogPNGChunk(logging,mng_JHDR,16L); PNGLong(chunk+4,(png_uint_32) image->columns); PNGLong(chunk+8,(png_uint_32) image->rows); chunk[12]=jng_color_type; chunk[13]=8; /* sample depth */ chunk[14]=8; /*jng_image_compression_method */ chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8); chunk[16]=jng_alpha_sample_depth; chunk[17]=jng_alpha_compression_method; chunk[18]=0; /*jng_alpha_filter_method */ chunk[19]=0; /*jng_alpha_interlace_method */ (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width:%15lu",(unsigned long) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG height:%14lu",(unsigned long) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG color type:%10d",jng_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG sample depth:%8d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG compression:%9d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG interlace:%11d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha depth:%9d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha compression:%3d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha filter:%8d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha interlace:%5d",0); } /* Write leading ancillary chunks */ if (transparent != 0) { /* Write JNG bKGD chunk */ unsigned char blue, green, red; ssize_t num_bytes; if (jng_color_type == 8 || jng_color_type == 12) num_bytes=6L; else num_bytes=10L; (void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L)); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L)); red=ScaleQuantumToChar(image->background_color.red); green=ScaleQuantumToChar(image->background_color.green); blue=ScaleQuantumToChar(image->background_color.blue); *(chunk+4)=0; *(chunk+5)=red; *(chunk+6)=0; *(chunk+7)=green; *(chunk+8)=0; *(chunk+9)=blue; (void) WriteBlob(image,(size_t) num_bytes,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes)); } if ((image->colorspace == sRGBColorspace || image->rendering_intent)) { /* Write JNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { if (image->gamma != 0.0) { /* Write JNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); } if ((mng_info->equal_chrms == MagickFalse) && (image->chromaticity.red_primary.x != 0.0)) { PrimaryInfo primary; /* Write JNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); } } if (image->resolution.x && image->resolution.y && !mng_info->equal_physs) { /* Write JNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->resolution.x+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.x || image->page.y)) { /* Write JNG oFFs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_oFFs); LogPNGChunk(logging,mng_oFFs,9L); PNGsLong(chunk+4,(ssize_t) (image->page.x)); PNGsLong(chunk+8,(ssize_t) (image->page.y)); chunk[12]=0; (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (transparent != 0) { if (jng_alpha_compression_method==0) { register ssize_t i; size_t len; /* Write IDAT chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write IDAT chunks from blob, length=%.20g.",(double) length); /* Copy IDAT chunks */ len=0; p=blob+8; for (i=8; i<(ssize_t) length; i+=len+12) { len=(((unsigned int) *(p ) & 0xff) << 24) + (((unsigned int) *(p + 1) & 0xff) << 16) + (((unsigned int) *(p + 2) & 0xff) << 8) + (((unsigned int) *(p + 3) & 0xff) ) ; p+=4; if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */ { /* Found an IDAT chunk. */ (void) WriteBlobMSBULong(image,len); LogPNGChunk(logging,mng_IDAT,len); (void) WriteBlob(image,len+4,p); (void) WriteBlobMSBULong(image, crc32(0,p,(uInt) len+4)); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping %c%c%c%c chunk, length=%.20g.", *(p),*(p+1),*(p+2),*(p+3),(double) len); } p+=(8+len); } } else if (length != 0) { /* Write JDAA chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAA chunk, length=%.20g.",(double) length); (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAA); LogPNGChunk(logging,mng_JDAA,length); /* Write JDAT chunk(s) data */ (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob, (uInt) length)); } blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Encode image as a JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,exception); if (jpeg_image == (Image *) NULL) { jpeg_image_info=DestroyImageInfo(jpeg_image_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); (void) AcquireUniqueFilename(jpeg_image->filename); (void) FormatLocaleString(jpeg_image_info->filename,MagickPathExtent,"%s", jpeg_image->filename); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns, (double) jpeg_image->rows); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (jng_color_type == 8 || jng_color_type == 12) jpeg_image_info->type=GrayscaleType; jpeg_image_info->quality=jng_quality; jpeg_image->quality=jng_quality; (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MagickPathExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=(unsigned char *) ImageToBlob(jpeg_image_info,jpeg_image,&length, exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAT chunk, length=%.20g.",(double) length); } /* Write JDAT chunk(s) */ (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAT); LogPNGChunk(logging,mng_JDAT,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length)); jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); jpeg_image_info=DestroyImageInfo(jpeg_image_info); blob=(unsigned char *) RelinquishMagickMemory(blob); /* Write IEND chunk */ (void) WriteBlobMSBULong(image,0L); PNGType(chunk,mng_IEND); LogPNGChunk(logging,mng_IEND,0); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOneJNGImage()"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJNGImage() writes a JPEG Network Graphics (JNG) image file. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteJNGImage method is: % % MagickBooleanType WriteJNGImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WriteJNGImage(const ImageInfo *image_info, Image *image, ExceptionInfo *exception) { MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) memset(mng_info,0,sizeof(MngInfo)); mng_info->image=image; (void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n"); status=WriteOneJNGImage(mng_info,image_info,image,exception); mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); (void) CatchImageException(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteJNGImage()"); return(status); } #endif static MagickBooleanType WriteMNGImage(const ImageInfo *image_info, Image *image, ExceptionInfo *exception) { Image *next_image; MagickBooleanType status; volatile MagickBooleanType logging; MngInfo *mng_info; int image_count, need_iterations, need_matte; volatile int #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) need_local_plte, #endif all_images_are_gray, need_defi, use_global_plte; register ssize_t i; unsigned char chunk[800]; volatile unsigned int write_jng, write_mng; volatile size_t scene; size_t final_delay=0, imageListLength, initial_delay; #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) memset(mng_info,0,sizeof(MngInfo)); mng_info->image=image; write_mng=LocaleCompare(image_info->magick,"MNG") == 0; /* * See if user has requested a specific PNG subformat to be used * for all of the PNGs in the MNG being written, e.g., * * convert *.png png8:animation.mng * * To do: check -define png:bit_depth and png:color_type as well, * or perhaps use mng:bit_depth and mng:color_type instead for * global settings. */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; write_jng=MagickFalse; if (image_info->compression == JPEGCompression) write_jng=MagickTrue; mng_info->adjoin=image_info->adjoin && (GetNextImageInList(image) != (Image *) NULL) && write_mng; if (logging != MagickFalse) { /* Log some info about the input */ Image *p; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Checking input image(s)\n" " Image_info depth: %.20g, Type: %d", (double) image_info->depth, image_info->type); scene=0; for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scene: %.20g\n, Image depth: %.20g", (double) scene++, (double) p->depth); if (p->alpha_trait != UndefinedPixelTrait) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: False"); if (p->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: PseudoClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: DirectClass"); if (p->colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) p->colors); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: unspecified"); if (mng_info->adjoin == MagickFalse) break; } } use_global_plte=MagickFalse; all_images_are_gray=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_defi=MagickFalse; need_matte=MagickFalse; mng_info->framing_mode=1; mng_info->old_framing_mode=1; if (write_mng) if (image_info->page != (char *) NULL) { /* Determine image bounding box. */ SetGeometry(image,&mng_info->page); (void) ParseMetaGeometry(image_info->page,&mng_info->page.x, &mng_info->page.y,&mng_info->page.width,&mng_info->page.height); } if (write_mng) { unsigned int need_geom; unsigned short red, green, blue; const char * option; mng_info->page=image->page; need_geom=MagickTrue; if (mng_info->page.width || mng_info->page.height) need_geom=MagickFalse; /* Check all the scenes. */ initial_delay=image->delay; need_iterations=MagickFalse; mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0; mng_info->equal_physs=MagickTrue, mng_info->equal_gammas=MagickTrue; mng_info->equal_srgbs=MagickTrue; mng_info->equal_backgrounds=MagickTrue; image_count=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) all_images_are_gray=MagickTrue; mng_info->equal_palettes=MagickFalse; need_local_plte=MagickFalse; #endif for (next_image=image; next_image != (Image *) NULL; ) { if (need_geom) { if ((next_image->columns+next_image->page.x) > mng_info->page.width) mng_info->page.width=next_image->columns+next_image->page.x; if ((next_image->rows+next_image->page.y) > mng_info->page.height) mng_info->page.height=next_image->rows+next_image->page.y; } if (next_image->page.x || next_image->page.y) need_defi=MagickTrue; if (next_image->alpha_trait != UndefinedPixelTrait) need_matte=MagickTrue; if ((int) next_image->dispose >= BackgroundDispose) if ((next_image->alpha_trait != UndefinedPixelTrait) || next_image->page.x || next_image->page.y || ((next_image->columns < mng_info->page.width) && (next_image->rows < mng_info->page.height))) mng_info->need_fram=MagickTrue; if (next_image->iterations) need_iterations=MagickTrue; final_delay=next_image->delay; if (final_delay != initial_delay || final_delay > 1UL* next_image->ticks_per_second) mng_info->need_fram=1; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* check for global palette possibility. */ if (image->alpha_trait != UndefinedPixelTrait) need_local_plte=MagickTrue; if (need_local_plte == 0) { if (SetImageGray(image,exception) == MagickFalse) all_images_are_gray=MagickFalse; mng_info->equal_palettes=PalettesAreEqual(image,next_image); if (use_global_plte == 0) use_global_plte=mng_info->equal_palettes; need_local_plte=!mng_info->equal_palettes; } #endif if (GetNextImageInList(next_image) != (Image *) NULL) { if (next_image->background_color.red != next_image->next->background_color.red || next_image->background_color.green != next_image->next->background_color.green || next_image->background_color.blue != next_image->next->background_color.blue) mng_info->equal_backgrounds=MagickFalse; if (next_image->gamma != next_image->next->gamma) mng_info->equal_gammas=MagickFalse; if (next_image->rendering_intent != next_image->next->rendering_intent) mng_info->equal_srgbs=MagickFalse; if ((next_image->units != next_image->next->units) || (next_image->resolution.x != next_image->next->resolution.x) || (next_image->resolution.y != next_image->next->resolution.y)) mng_info->equal_physs=MagickFalse; if (mng_info->equal_chrms) { if (next_image->chromaticity.red_primary.x != next_image->next->chromaticity.red_primary.x || next_image->chromaticity.red_primary.y != next_image->next->chromaticity.red_primary.y || next_image->chromaticity.green_primary.x != next_image->next->chromaticity.green_primary.x || next_image->chromaticity.green_primary.y != next_image->next->chromaticity.green_primary.y || next_image->chromaticity.blue_primary.x != next_image->next->chromaticity.blue_primary.x || next_image->chromaticity.blue_primary.y != next_image->next->chromaticity.blue_primary.y || next_image->chromaticity.white_point.x != next_image->next->chromaticity.white_point.x || next_image->chromaticity.white_point.y != next_image->next->chromaticity.white_point.y) mng_info->equal_chrms=MagickFalse; } } image_count++; next_image=GetNextImageInList(next_image); } if (image_count < 2) { mng_info->equal_backgrounds=MagickFalse; mng_info->equal_chrms=MagickFalse; mng_info->equal_gammas=MagickFalse; mng_info->equal_srgbs=MagickFalse; mng_info->equal_physs=MagickFalse; use_global_plte=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_iterations=MagickFalse; } if (mng_info->need_fram == MagickFalse) { /* Only certain framing rates 100/n are exactly representable without the FRAM chunk but we'll allow some slop in VLC files */ if (final_delay == 0) { if (need_iterations != MagickFalse) { /* It's probably a GIF with loop; don't run it *too* fast. */ if (mng_info->adjoin) { final_delay=10; (void) ThrowMagickException(exception,GetMagickModule(), CoderWarning, "input has zero delay between all frames; assuming", " 10 cs `%s'",""); } } else mng_info->ticks_per_second=0; } if (final_delay != 0) mng_info->ticks_per_second=(png_uint_32) (image->ticks_per_second/final_delay); if (final_delay > 50) mng_info->ticks_per_second=2; if (final_delay > 75) mng_info->ticks_per_second=1; if (final_delay > 125) mng_info->need_fram=MagickTrue; if (need_defi && final_delay > 2 && (final_delay != 4) && (final_delay != 5) && (final_delay != 10) && (final_delay != 20) && (final_delay != 25) && (final_delay != 50) && (final_delay != (size_t) image->ticks_per_second)) mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */ } if (mng_info->need_fram != MagickFalse) mng_info->ticks_per_second=image->ticks_per_second; /* If pseudocolor, we should also check to see if all the palettes are identical and write a global PLTE if they are. ../glennrp Feb 99. */ /* Write the MNG version 1.0 signature and MHDR chunk. */ (void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n"); (void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */ PNGType(chunk,mng_MHDR); LogPNGChunk(logging,mng_MHDR,28L); PNGLong(chunk+4,(png_uint_32) mng_info->page.width); PNGLong(chunk+8,(png_uint_32) mng_info->page.height); PNGLong(chunk+12,mng_info->ticks_per_second); PNGLong(chunk+16,0L); /* layer count=unknown */ PNGLong(chunk+20,0L); /* frame count=unknown */ PNGLong(chunk+24,0L); /* play time=unknown */ if (write_jng) { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,27L); /* simplicity=LC+JNG */ else PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */ else PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */ } } else { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,11L); /* simplicity=LC */ else PNGLong(chunk+28,9L); /* simplicity=VLC */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */ else PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */ } } (void) WriteBlob(image,32,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,32)); option=GetImageOption(image_info,"mng:need-cacheoff"); if (option != (const char *) NULL) { size_t length; /* Write "nEED CACHEOFF" to turn playback caching off for streaming MNG. */ PNGType(chunk,mng_nEED); length=CopyMagickString((char *) chunk+4,"CACHEOFF",20); (void) WriteBlobMSBULong(image,(size_t) length); LogPNGChunk(logging,mng_nEED,(size_t) length); length+=4; (void) WriteBlob(image,length,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length)); } if ((GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) != (Image *) NULL) && (image->iterations != 1)) { /* Write MNG TERM chunk */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_TERM); LogPNGChunk(logging,mng_TERM,10L); chunk[4]=3; /* repeat animation */ chunk[5]=0; /* show last frame when done */ PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) PNGLong(chunk+10,PNG_UINT_31_MAX); else PNGLong(chunk+10,(png_uint_32) image->iterations); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM delay: %.20g",(double) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM iterations: %.20g",(double) PNG_UINT_31_MAX); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image iterations: %.20g",(double) image->iterations); } (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); } /* To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if ((image->colorspace == sRGBColorspace || image->rendering_intent) && mng_info->equal_srgbs) { /* Write MNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); mng_info->have_write_global_srgb=MagickTrue; } else { if (image->gamma && mng_info->equal_gammas) { /* Write MNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); mng_info->have_write_global_gama=MagickTrue; } if (mng_info->equal_chrms) { PrimaryInfo primary; /* Write MNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); mng_info->have_write_global_chrm=MagickTrue; } } if (image->resolution.x && image->resolution.y && mng_info->equal_physs) { /* Write MNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->resolution.x+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } /* Write MNG BACK chunk and global bKGD chunk, if the image is transparent or does not cover the entire frame. */ if (write_mng && ((image->alpha_trait != UndefinedPixelTrait) || image->page.x > 0 || image->page.y > 0 || (image->page.width && (image->page.width+image->page.x < mng_info->page.width)) || (image->page.height && (image->page.height+image->page.y < mng_info->page.height)))) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_BACK); LogPNGChunk(logging,mng_BACK,6L); red=ScaleQuantumToShort(image->background_color.red); green=ScaleQuantumToShort(image->background_color.green); blue=ScaleQuantumToShort(image->background_color.blue); PNGShort(chunk+4,red); PNGShort(chunk+6,green); PNGShort(chunk+8,blue); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); if (mng_info->equal_backgrounds) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,6L); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); } } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if ((need_local_plte == MagickFalse) && (image->storage_class == PseudoClass) && (all_images_are_gray == MagickFalse)) { size_t data_length; /* Write MNG PLTE chunk */ data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=(unsigned char) (ScaleQuantumToChar( image->colormap[i].red) & 0xff); chunk[5+i*3]=(unsigned char) (ScaleQuantumToChar( image->colormap[i].green) & 0xff); chunk[6+i*3]=(unsigned char) (ScaleQuantumToChar( image->colormap[i].blue) & 0xff); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } #endif } scene=0; mng_info->delay=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) mng_info->equal_palettes=MagickFalse; #endif imageListLength=GetImageListLength(image); do { if (mng_info->adjoin) { #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* If we aren't using a global palette for the entire MNG, check to see if we can use one for two or more consecutive images. */ if (need_local_plte && use_global_plte && !all_images_are_gray) { if (mng_info->IsPalette) { /* When equal_palettes is true, this image has the same palette as the previous PseudoClass image */ mng_info->have_write_global_plte=mng_info->equal_palettes; mng_info->equal_palettes=PalettesAreEqual(image,image->next); if (mng_info->equal_palettes && !mng_info->have_write_global_plte) { /* Write MNG PLTE chunk */ size_t data_length; data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red); chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green); chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk, (uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } } else mng_info->have_write_global_plte=MagickFalse; } #endif if (need_defi) { ssize_t previous_x, previous_y; if (scene != 0) { previous_x=mng_info->page.x; previous_y=mng_info->page.y; } else { previous_x=0; previous_y=0; } mng_info->page=image->page; if ((mng_info->page.x != previous_x) || (mng_info->page.y != previous_y)) { (void) WriteBlobMSBULong(image,12L); /* data length=12 */ PNGType(chunk,mng_DEFI); LogPNGChunk(logging,mng_DEFI,12L); chunk[4]=0; /* object 0 MSB */ chunk[5]=0; /* object 0 LSB */ chunk[6]=0; /* visible */ chunk[7]=0; /* abstract */ PNGLong(chunk+8,(png_uint_32) mng_info->page.x); PNGLong(chunk+12,(png_uint_32) mng_info->page.y); (void) WriteBlob(image,16,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,16)); } } } mng_info->write_mng=write_mng; if ((int) image->dispose >= 3) mng_info->framing_mode=3; if (mng_info->need_fram && mng_info->adjoin && ((image->delay != mng_info->delay) || (mng_info->framing_mode != mng_info->old_framing_mode))) { if (image->delay == mng_info->delay) { /* Write a MNG FRAM chunk with the new framing mode. */ (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,1L); chunk[4]=(unsigned char) mng_info->framing_mode; (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { /* Write a MNG FRAM chunk with the delay. */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,10L); chunk[4]=(unsigned char) mng_info->framing_mode; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=2; /* flag for changing default delay */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=0; /* flag for changing frame clipping */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) ((mng_info->ticks_per_second* image->delay)/MagickMax(image->ticks_per_second,1))); (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); mng_info->delay=(png_uint_32) image->delay; } mng_info->old_framing_mode=mng_info->framing_mode; } #if defined(JNG_SUPPORTED) if (image_info->compression == JPEGCompression) { ImageInfo *write_info; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing JNG object."); /* To do: specify the desired alpha compression method. */ write_info=CloneImageInfo(image_info); write_info->compression=UndefinedCompression; status=WriteOneJNGImage(mng_info,write_info,image,exception); write_info=DestroyImageInfo(write_info); } else #endif { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG object."); mng_info->need_blob = MagickFalse; mng_info->ping_preserve_colormap = MagickFalse; /* We don't want any ancillary chunks written */ mng_info->ping_exclude_bKGD=MagickTrue; mng_info->ping_exclude_caNv=MagickTrue; mng_info->ping_exclude_cHRM=MagickTrue; mng_info->ping_exclude_date=MagickTrue; mng_info->ping_exclude_EXIF=MagickTrue; mng_info->ping_exclude_gAMA=MagickTrue; mng_info->ping_exclude_iCCP=MagickTrue; /* mng_info->ping_exclude_iTXt=MagickTrue; */ mng_info->ping_exclude_oFFs=MagickTrue; mng_info->ping_exclude_pHYs=MagickTrue; mng_info->ping_exclude_sRGB=MagickTrue; mng_info->ping_exclude_tEXt=MagickTrue; mng_info->ping_exclude_tRNS=MagickTrue; mng_info->ping_exclude_zCCP=MagickTrue; mng_info->ping_exclude_zTXt=MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image,exception); } if (status == MagickFalse) { mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); return(MagickFalse); } (void) CatchImageException(image); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (mng_info->adjoin); if (write_mng) { while (GetPreviousImageInList(image) != (Image *) NULL) image=GetPreviousImageInList(image); /* Write the MEND chunk. */ (void) WriteBlobMSBULong(image,0x00000000L); PNGType(chunk,mng_MEND); LogPNGChunk(logging,mng_MEND,0L); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); } /* Relinquish resources. */ (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()"); return(MagickTrue); } #else /* PNG_LIBPNG_VER > 10011 */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info, Image *image) { (void) image; printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); ThrowBinaryException(CoderError,"PNG library is too old", image_info->filename); } static MagickBooleanType WriteMNGImage(const ImageInfo *image_info, Image *image) { return(WritePNGImage(image_info,image)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif
./CrossVul/dataset_final_sorted/CWE-772/c/bad_361_0
crossvul-cpp_data_good_2618_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE % % Q Q U U A A NN N T I ZZ E % % Q Q U U AAAAA N N N T I ZZZ EEEEE % % Q QQ U U A A N NN T I ZZ E % % QQQQ UUU A A N N T IIIII ZZZZZ EEEEE % % % % % % MagickCore Methods to Reduce the Number of Unique Colors in an Image % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Realism in computer graphics typically requires using 24 bits/pixel to % generate an image. Yet many graphic display devices do not contain the % amount of memory necessary to match the spatial and color resolution of % the human eye. The Quantize methods takes a 24 bit image and reduces % the number of colors so it can be displayed on raster device with less % bits per pixel. In most instances, the quantized image closely % resembles the original reference image. % % A reduction of colors in an image is also desirable for image % transmission and real-time animation. % % QuantizeImage() takes a standard RGB or monochrome images and quantizes % them down to some fixed number of colors. % % For purposes of color allocation, an image is a set of n pixels, where % each pixel is a point in RGB space. RGB space is a 3-dimensional % vector space, and each pixel, Pi, is defined by an ordered triple of % red, green, and blue coordinates, (Ri, Gi, Bi). % % Each primary color component (red, green, or blue) represents an % intensity which varies linearly from 0 to a maximum value, Cmax, which % corresponds to full saturation of that color. Color allocation is % defined over a domain consisting of the cube in RGB space with opposite % vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax = % 255. % % The algorithm maps this domain onto a tree in which each node % represents a cube within that domain. In the following discussion % these cubes are defined by the coordinate of two opposite vertices (vertex % nearest the origin in RGB space and the vertex farthest from the origin). % % The tree's root node represents the entire domain, (0,0,0) through % (Cmax,Cmax,Cmax). Each lower level in the tree is generated by % subdividing one node's cube into eight smaller cubes of equal size. % This corresponds to bisecting the parent cube with planes passing % through the midpoints of each edge. % % The basic algorithm operates in three phases: Classification, % Reduction, and Assignment. Classification builds a color description % tree for the image. Reduction collapses the tree until the number it % represents, at most, the number of colors desired in the output image. % Assignment defines the output image's color map and sets each pixel's % color by restorage_class in the reduced tree. Our goal is to minimize % the numerical discrepancies between the original colors and quantized % colors (quantization error). % % Classification begins by initializing a color description tree of % sufficient depth to represent each possible input color in a leaf. % However, it is impractical to generate a fully-formed color description % tree in the storage_class phase for realistic values of Cmax. If % colors components in the input image are quantized to k-bit precision, % so that Cmax= 2k-1, the tree would need k levels below the root node to % allow representing each possible input color in a leaf. This becomes % prohibitive because the tree's total number of nodes is 1 + % sum(i=1, k, 8k). % % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255. % Therefore, to avoid building a fully populated tree, QUANTIZE: (1) % Initializes data structures for nodes only as they are needed; (2) % Chooses a maximum depth for the tree as a function of the desired % number of colors in the output image (currently log2(colormap size)). % % For each pixel in the input image, storage_class scans downward from % the root of the color description tree. At each level of the tree it % identifies the single node which represents a cube in RGB space % containing the pixel's color. It updates the following data for each % such node: % % n1: Number of pixels whose color is contained in the RGB cube which % this node represents; % % n2: Number of pixels whose color is not represented in a node at % lower depth in the tree; initially, n2 = 0 for all nodes except % leaves of the tree. % % Sr, Sg, Sb: Sums of the red, green, and blue component values for all % pixels not classified at a lower depth. The combination of these sums % and n2 will ultimately characterize the mean color of a set of % pixels represented by this node. % % E: the distance squared in RGB space between each pixel contained % within a node and the nodes' center. This represents the % quantization error for a node. % % Reduction repeatedly prunes the tree until the number of nodes with n2 % > 0 is less than or equal to the maximum number of colors allowed in % the output image. On any given iteration over the tree, it selects % those nodes whose E count is minimal for pruning and merges their color % statistics upward. It uses a pruning threshold, Ep, to govern node % selection as follows: % % Ep = 0 % while number of nodes with (n2 > 0) > required maximum number of colors % prune all nodes such that E <= Ep % Set Ep to minimum E in remaining nodes % % This has the effect of minimizing any quantization error when merging % two nodes together. % % When a node to be pruned has offspring, the pruning procedure invokes % itself recursively in order to prune the tree from the leaves upward. % n2, Sr, Sg, and Sb in a node being pruned are always added to the % corresponding data in that node's parent. This retains the pruned % node's color characteristics for later averaging. % % For each node, n2 pixels exist for which that node represents the % smallest volume in RGB space containing those pixel's colors. When n2 % > 0 the node will uniquely define a color in the output image. At the % beginning of reduction, n2 = 0 for all nodes except a the leaves of % the tree which represent colors present in the input image. % % The other pixel count, n1, indicates the total number of colors within % the cubic volume which the node represents. This includes n1 - n2 % pixels whose colors should be defined by nodes at a lower level in the % tree. % % Assignment generates the output image from the pruned tree. The output % image consists of two parts: (1) A color map, which is an array of % color descriptions (RGB triples) for each color present in the output % image; (2) A pixel array, which represents each pixel as an index % into the color map array. % % First, the assignment phase makes one pass over the pruned color % description tree to establish the image's color map. For each node % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean % color of all pixels that classify no lower than this node. Each of % these colors becomes an entry in the color map. % % Finally, the assignment phase reclassifies each pixel in the pruned % tree to identify the deepest node containing the pixel's color. The % pixel's value in the pixel array becomes the index of this node's mean % color in the color map. % % This method is based on a similar algorithm written by Paul Raveling. % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/histogram.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/resource_.h" #include "magick/string_.h" #include "magick/thread-private.h" /* Define declarations. */ #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE) #define CacheShift 2 #else #define CacheShift 3 #endif #define ErrorQueueLength 16 #define MaxNodes 266817 #define MaxTreeDepth 8 #define NodesInAList 1920 /* Typdef declarations. */ typedef struct _NodeInfo { struct _NodeInfo *parent, *child[16]; MagickSizeType number_unique; DoublePixelPacket total_color; MagickRealType quantize_error; size_t color_number, id, level; } NodeInfo; typedef struct _Nodes { NodeInfo *nodes; struct _Nodes *next; } Nodes; typedef struct _CubeInfo { NodeInfo *root; size_t colors, maximum_colors; ssize_t transparent_index; MagickSizeType transparent_pixels; DoublePixelPacket target; MagickRealType distance, pruning_threshold, next_threshold; size_t nodes, free_nodes, color_number; NodeInfo *next_node; Nodes *node_queue; MemoryInfo *memory_info; ssize_t *cache; DoublePixelPacket error[ErrorQueueLength]; MagickRealType weights[ErrorQueueLength]; QuantizeInfo *quantize_info; MagickBooleanType associate_alpha; ssize_t x, y; size_t depth; MagickOffsetType offset; MagickSizeType span; } CubeInfo; /* Method prototypes. */ static CubeInfo *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t); static NodeInfo *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *); static MagickBooleanType AssignImageColors(Image *,CubeInfo *), ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *), DitherImage(Image *,CubeInfo *), SetGrayscaleImage(Image *); static size_t DefineImageColormap(Image *,CubeInfo *,NodeInfo *); static void ClosestColor(const Image *,CubeInfo *,const NodeInfo *), DestroyCubeInfo(CubeInfo *), PruneLevel(CubeInfo *,const NodeInfo *), PruneToCubeDepth(CubeInfo *,const NodeInfo *), ReduceImageColors(const Image *,CubeInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantizeInfo() allocates the QuantizeInfo structure. % % The format of the AcquireQuantizeInfo method is: % % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info) { QuantizeInfo *quantize_info; quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info)); if (quantize_info == (QuantizeInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); GetQuantizeInfo(quantize_info); if (image_info != (ImageInfo *) NULL) { const char *option; quantize_info->dither=image_info->dither; option=GetImageOption(image_info,"dither"); if (option != (const char *) NULL) quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,option); quantize_info->measure_error=image_info->verbose; } return(quantize_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A s s i g n I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AssignImageColors() generates the output image from the pruned tree. The % output image consists of two parts: (1) A color map, which is an array % of color descriptions (RGB triples) for each color present in the % output image; (2) A pixel array, which represents each pixel as an % index into the color map array. % % First, the assignment phase makes one pass over the pruned color % description tree to establish the image's color map. For each node % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean % color of all pixels that classify no lower than this node. Each of % these colors becomes an entry in the color map. % % Finally, the assignment phase reclassifies each pixel in the pruned % tree to identify the deepest node containing the pixel's color. The % pixel's value in the pixel array becomes the index of this node's mean % color in the color map. % % The format of the AssignImageColors() method is: % % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static inline void AssociateAlphaPixel(const CubeInfo *cube_info, const PixelPacket *pixel,DoublePixelPacket *alpha_pixel) { MagickRealType alpha; alpha_pixel->index=0; if ((cube_info->associate_alpha == MagickFalse) || (pixel->opacity == OpaqueOpacity)) { alpha_pixel->red=(MagickRealType) GetPixelRed(pixel); alpha_pixel->green=(MagickRealType) GetPixelGreen(pixel); alpha_pixel->blue=(MagickRealType) GetPixelBlue(pixel); alpha_pixel->opacity=(MagickRealType) GetPixelOpacity(pixel); return; } alpha=(MagickRealType) (QuantumScale*(QuantumRange-GetPixelOpacity(pixel))); alpha_pixel->red=alpha*GetPixelRed(pixel); alpha_pixel->green=alpha*GetPixelGreen(pixel); alpha_pixel->blue=alpha*GetPixelBlue(pixel); alpha_pixel->opacity=(MagickRealType) GetPixelOpacity(pixel); } static inline size_t ColorToNodeId(const CubeInfo *cube_info, const DoublePixelPacket *pixel,size_t index) { size_t id; id=(size_t) (((ScaleQuantumToChar(ClampPixel(GetPixelRed(pixel))) >> index) & 0x01) | ((ScaleQuantumToChar(ClampPixel(GetPixelGreen(pixel))) >> index) & 0x01) << 1 | ((ScaleQuantumToChar(ClampPixel(GetPixelBlue(pixel))) >> index) & 0x01) << 2); if (cube_info->associate_alpha != MagickFalse) id|=((ScaleQuantumToChar(ClampPixel(GetPixelOpacity(pixel))) >> index) & 0x1) << 3; return(id); } static inline MagickBooleanType IsSameColor(const Image *image, const PixelPacket *p,const PixelPacket *q) { if ((GetPixelRed(p) != GetPixelRed(q)) || (GetPixelGreen(p) != GetPixelGreen(q)) || (GetPixelBlue(p) != GetPixelBlue(q))) return(MagickFalse); if ((image->matte != MagickFalse) && (GetPixelOpacity(p) != GetPixelOpacity(q))) return(MagickFalse); return(MagickTrue); } static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info) { #define AssignImageTag "Assign/Image" ssize_t y; /* Allocate image colormap. */ if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace(image,cube_info->quantize_info->colorspace); else if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); if (AcquireImageColormap(image,cube_info->colors) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); image->colors=0; cube_info->transparent_pixels=0; cube_info->transparent_index=(-1); (void) DefineImageColormap(image,cube_info,cube_info->root); /* Create a reduced color image. */ if ((cube_info->quantize_info->dither != MagickFalse) && (cube_info->quantize_info->dither_method != NoDitherMethod)) (void) DitherImage(image,cube_info); else { CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CubeInfo cube; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t count; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); cube=(*cube_info); for (x=0; x < (ssize_t) image->columns; x+=count) { DoublePixelPacket pixel; register const NodeInfo *node_info; register ssize_t i; size_t id, index; /* Identify the deepest node containing the pixel's color. */ for (count=1; (x+count) < (ssize_t) image->columns; count++) if (IsSameColor(image,q,q+count) == MagickFalse) break; AssociateAlphaPixel(&cube,q,&pixel); node_info=cube.root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(&cube,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ cube.target=pixel; cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)* (QuantumRange+1.0)+1.0); ClosestColor(image,&cube,node_info->parent); index=cube.color_number; for (i=0; i < (ssize_t) count; i++) { if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+i,index); if (cube.quantize_info->measure_error == MagickFalse) { SetPixelRgb(q,image->colormap+index); if (cube.associate_alpha != MagickFalse) SetPixelOpacity(q,image->colormap[index].opacity); } q++; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AssignImageColors) #endif proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); } if (cube_info->quantize_info->measure_error != MagickFalse) (void) GetImageQuantizeError(image); if ((cube_info->quantize_info->number_colors == 2) && (cube_info->quantize_info->colorspace == GRAYColorspace)) { double intensity; /* Monochrome image. */ intensity=0.0; if ((image->colors > 1) && (GetPixelLuma(image,image->colormap+0) > GetPixelLuma(image,image->colormap+1))) intensity=(double) QuantumRange; image->colormap[0].red=intensity; image->colormap[0].green=intensity; image->colormap[0].blue=intensity; if (image->colors > 1) { image->colormap[1].red=(double) QuantumRange-intensity; image->colormap[1].green=(double) QuantumRange-intensity; image->colormap[1].blue=(double) QuantumRange-intensity; } } (void) SyncImage(image); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace((Image *) image,sRGBColorspace); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l a s s i f y I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClassifyImageColors() begins by initializing a color description tree % of sufficient depth to represent each possible input color in a leaf. % However, it is impractical to generate a fully-formed color % description tree in the storage_class phase for realistic values of % Cmax. If colors components in the input image are quantized to k-bit % precision, so that Cmax= 2k-1, the tree would need k levels below the % root node to allow representing each possible input color in a leaf. % This becomes prohibitive because the tree's total number of nodes is % 1 + sum(i=1,k,8k). % % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255. % Therefore, to avoid building a fully populated tree, QUANTIZE: (1) % Initializes data structures for nodes only as they are needed; (2) % Chooses a maximum depth for the tree as a function of the desired % number of colors in the output image (currently log2(colormap size)). % % For each pixel in the input image, storage_class scans downward from % the root of the color description tree. At each level of the tree it % identifies the single node which represents a cube in RGB space % containing It updates the following data for each such node: % % n1 : Number of pixels whose color is contained in the RGB cube % which this node represents; % % n2 : Number of pixels whose color is not represented in a node at % lower depth in the tree; initially, n2 = 0 for all nodes except % leaves of the tree. % % Sr, Sg, Sb : Sums of the red, green, and blue component values for % all pixels not classified at a lower depth. The combination of % these sums and n2 will ultimately characterize the mean color of a % set of pixels represented by this node. % % E: the distance squared in RGB space between each pixel contained % within a node and the nodes' center. This represents the quantization % error for a node. % % The format of the ClassifyImageColors() method is: % % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info, % const Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o image: the image. % */ static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info) { MagickBooleanType associate_alpha; associate_alpha=image->matte; if ((cube_info->quantize_info->number_colors == 2) && (cube_info->quantize_info->colorspace == GRAYColorspace)) associate_alpha=MagickFalse; cube_info->associate_alpha=associate_alpha; } static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info, const Image *image,ExceptionInfo *exception) { #define ClassifyImageTag "Classify/Image" CacheView *image_view; DoublePixelPacket error, mid, midpoint, pixel; MagickBooleanType proceed; MagickRealType bisect; NodeInfo *node_info; size_t count, id, index, level; ssize_t y; /* Classify the first cube_info->maximum_colors colors to a tree depth of 8. */ SetAssociatedAlpha(image,cube_info); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace((Image *) image, cube_info->quantize_info->colorspace); else if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace((Image *) image,sRGBColorspace); midpoint.red=(MagickRealType) QuantumRange/2.0; midpoint.green=(MagickRealType) QuantumRange/2.0; midpoint.blue=(MagickRealType) QuantumRange/2.0; midpoint.opacity=(MagickRealType) QuantumRange/2.0; midpoint.index=(MagickRealType) QuantumRange/2.0; error.opacity=0.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; if (cube_info->nodes > MaxNodes) { /* Prune one level if the color tree is too large. */ PruneLevel(cube_info,cube_info->root); cube_info->depth--; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count) { /* Start at the root and descend the color cube tree. */ for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++) if (IsSameColor(image,p,p+count) == MagickFalse) break; AssociateAlphaPixel(cube_info,p,&pixel); index=MaxTreeDepth-1; bisect=((MagickRealType) QuantumRange+1.0)/2.0; mid=midpoint; node_info=cube_info->root; for (level=1; level <= MaxTreeDepth; level++) { double distance; bisect*=0.5; id=ColorToNodeId(cube_info,&pixel,index); mid.red+=(id & 1) != 0 ? bisect : -bisect; mid.green+=(id & 2) != 0 ? bisect : -bisect; mid.blue+=(id & 4) != 0 ? bisect : -bisect; mid.opacity+=(id & 8) != 0 ? bisect : -bisect; if (node_info->child[id] == (NodeInfo *) NULL) { /* Set colors of new node to contain pixel. */ node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info); if (node_info->child[id] == (NodeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); continue; } if (level == MaxTreeDepth) cube_info->colors++; } /* Approximate the quantization error represented by this node. */ node_info=node_info->child[id]; error.red=QuantumScale*(pixel.red-mid.red); error.green=QuantumScale*(pixel.green-mid.green); error.blue=QuantumScale*(pixel.blue-mid.blue); if (cube_info->associate_alpha != MagickFalse) error.opacity=QuantumScale*(pixel.opacity-mid.opacity); distance=(double) (error.red*error.red+error.green*error.green+ error.blue*error.blue+error.opacity*error.opacity); if (IsNaN(distance)) distance=0.0; node_info->quantize_error+=count*sqrt(distance); cube_info->root->quantize_error+=node_info->quantize_error; index--; } /* Sum RGB for this leaf for later derivation of the mean cube color. */ node_info->number_unique+=count; node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red); node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green); node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) node_info->total_color.opacity+=count*QuantumScale* ClampPixel(pixel.opacity); else node_info->total_color.opacity+=count*QuantumScale* ClampPixel(OpaqueOpacity); p+=count; } if (cube_info->colors > cube_info->maximum_colors) { PruneToCubeDepth(cube_info,cube_info->root); break; } proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } for (y++; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; if (cube_info->nodes > MaxNodes) { /* Prune one level if the color tree is too large. */ PruneLevel(cube_info,cube_info->root); cube_info->depth--; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count) { /* Start at the root and descend the color cube tree. */ for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++) if (IsSameColor(image,p,p+count) == MagickFalse) break; AssociateAlphaPixel(cube_info,p,&pixel); index=MaxTreeDepth-1; bisect=((MagickRealType) QuantumRange+1.0)/2.0; mid=midpoint; node_info=cube_info->root; for (level=1; level <= cube_info->depth; level++) { double distance; bisect*=0.5; id=ColorToNodeId(cube_info,&pixel,index); mid.red+=(id & 1) != 0 ? bisect : -bisect; mid.green+=(id & 2) != 0 ? bisect : -bisect; mid.blue+=(id & 4) != 0 ? bisect : -bisect; mid.opacity+=(id & 8) != 0 ? bisect : -bisect; if (node_info->child[id] == (NodeInfo *) NULL) { /* Set colors of new node to contain pixel. */ node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info); if (node_info->child[id] == (NodeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","%s", image->filename); continue; } if (level == cube_info->depth) cube_info->colors++; } /* Approximate the quantization error represented by this node. */ node_info=node_info->child[id]; error.red=QuantumScale*(pixel.red-mid.red); error.green=QuantumScale*(pixel.green-mid.green); error.blue=QuantumScale*(pixel.blue-mid.blue); if (cube_info->associate_alpha != MagickFalse) error.opacity=QuantumScale*(pixel.opacity-mid.opacity); distance=(double) (error.red*error.red+error.green*error.green+ error.blue*error.blue+error.opacity*error.opacity); if (IsNaN(distance)) distance=0.0; node_info->quantize_error+=count*sqrt(distance); cube_info->root->quantize_error+=node_info->quantize_error; index--; } /* Sum RGB for this leaf for later derivation of the mean cube color. */ node_info->number_unique+=count; node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red); node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green); node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) node_info->total_color.opacity+=count*QuantumScale*ClampPixel( pixel.opacity); else node_info->total_color.opacity+=count*QuantumScale* ClampPixel(OpaqueOpacity); p+=count; } proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } image_view=DestroyCacheView(image_view); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace((Image *) image,sRGBColorspace); return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneQuantizeInfo() makes a duplicate of the given quantize info structure, % or if quantize info is NULL, a new one. % % The format of the CloneQuantizeInfo method is: % % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given % quantize info, or if image info is NULL a new one. % % o quantize_info: a structure of type info. % */ MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info) { QuantizeInfo *clone_info; clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info)); if (clone_info == (QuantizeInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); GetQuantizeInfo(clone_info); if (quantize_info == (QuantizeInfo *) NULL) return(clone_info); clone_info->number_colors=quantize_info->number_colors; clone_info->tree_depth=quantize_info->tree_depth; clone_info->dither=quantize_info->dither; clone_info->dither_method=quantize_info->dither_method; clone_info->colorspace=quantize_info->colorspace; clone_info->measure_error=quantize_info->measure_error; return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o s e s t C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClosestColor() traverses the color cube tree at a particular node and % determines which colormap entry best represents the input color. % % The format of the ClosestColor method is: % % void ClosestColor(const Image *image,CubeInfo *cube_info, % const NodeInfo *node_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o node_info: the address of a structure of type NodeInfo which points to a % node in the color cube tree that is to be pruned. % */ static void ClosestColor(const Image *image,CubeInfo *cube_info, const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) ClosestColor(image,cube_info,node_info->child[i]); if (node_info->number_unique != 0) { MagickRealType pixel; register DoublePixelPacket *magick_restrict q; register MagickRealType alpha, beta, distance; register PixelPacket *magick_restrict p; /* Determine if this color is "closest". */ p=image->colormap+node_info->color_number; q=(&cube_info->target); alpha=1.0; beta=1.0; if (cube_info->associate_alpha != MagickFalse) { alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p)); beta=(MagickRealType) (QuantumScale*GetPixelAlpha(q)); } pixel=alpha*GetPixelRed(p)-beta*GetPixelRed(q); distance=pixel*pixel; if (distance <= cube_info->distance) { pixel=alpha*GetPixelGreen(p)-beta*GetPixelGreen(q); distance+=pixel*pixel; if (distance <= cube_info->distance) { pixel=alpha*GetPixelBlue(p)-beta*GetPixelBlue(q); distance+=pixel*pixel; if (distance <= cube_info->distance) { if (cube_info->associate_alpha != MagickFalse) { pixel=GetPixelAlpha(p)-GetPixelAlpha(q); distance+=pixel*pixel; } if (distance <= cube_info->distance) { cube_info->distance=distance; cube_info->color_number=node_info->color_number; } } } } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p r e s s I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompressImageColormap() compresses an image colormap by removing any % duplicate or unused color entries. % % The format of the CompressImageColormap method is: % % MagickBooleanType CompressImageColormap(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType CompressImageColormap(Image *image) { QuantizeInfo quantize_info; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (IsPaletteImage(image,&image->exception) == MagickFalse) return(MagickFalse); GetQuantizeInfo(&quantize_info); quantize_info.number_colors=image->colors; quantize_info.tree_depth=MaxTreeDepth; return(QuantizeImage(&quantize_info,image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e f i n e I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DefineImageColormap() traverses the color cube tree and notes each colormap % entry. A colormap entry is any node in the color cube tree where the % of unique colors is not zero. DefineImageColormap() returns the number of % colors in the image colormap. % % The format of the DefineImageColormap method is: % % size_t DefineImageColormap(Image *image,CubeInfo *cube_info, % NodeInfo *node_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o node_info: the address of a structure of type NodeInfo which points to a % node in the color cube tree that is to be pruned. % */ static size_t DefineImageColormap(Image *image,CubeInfo *cube_info, NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) (void) DefineImageColormap(image,cube_info,node_info->child[i]); if (node_info->number_unique != 0) { register MagickRealType alpha; register PixelPacket *magick_restrict q; /* Colormap entry is defined by the mean color in this cube. */ q=image->colormap+image->colors; alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique); alpha=PerceptibleReciprocal(alpha); if (cube_info->associate_alpha == MagickFalse) { SetPixelRed(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.red))); SetPixelGreen(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.green))); SetPixelBlue(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.blue))); SetPixelOpacity(q,OpaqueOpacity); } else { MagickRealType opacity; opacity=(MagickRealType) (alpha*QuantumRange* node_info->total_color.opacity); SetPixelOpacity(q,ClampToQuantum(opacity)); if (q->opacity == OpaqueOpacity) { SetPixelRed(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.red))); SetPixelGreen(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.green))); SetPixelBlue(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.blue))); } else { double gamma; gamma=(double) (QuantumScale*(QuantumRange-(double) q->opacity)); gamma=PerceptibleReciprocal(gamma); SetPixelRed(q,ClampToQuantum((MagickRealType) (alpha* gamma*QuantumRange*node_info->total_color.red))); SetPixelGreen(q,ClampToQuantum((MagickRealType) (alpha* gamma*QuantumRange*node_info->total_color.green))); SetPixelBlue(q,ClampToQuantum((MagickRealType) (alpha* gamma*QuantumRange*node_info->total_color.blue))); if (node_info->number_unique > cube_info->transparent_pixels) { cube_info->transparent_pixels=node_info->number_unique; cube_info->transparent_index=(ssize_t) image->colors; } } } node_info->color_number=image->colors++; } return(image->colors); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y C u b e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyCubeInfo() deallocates memory associated with an image. % % The format of the DestroyCubeInfo method is: % % DestroyCubeInfo(CubeInfo *cube_info) % % A description of each parameter follows: % % o cube_info: the address of a structure of type CubeInfo. % */ static void DestroyCubeInfo(CubeInfo *cube_info) { register Nodes *nodes; /* Release color cube tree storage. */ do { nodes=cube_info->node_queue->next; cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory( cube_info->node_queue->nodes); cube_info->node_queue=(Nodes *) RelinquishMagickMemory( cube_info->node_queue); cube_info->node_queue=nodes; } while (cube_info->node_queue != (Nodes *) NULL); if (cube_info->memory_info != (MemoryInfo *) NULL) cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info); cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info); cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo % structure. % % The format of the DestroyQuantizeInfo method is: % % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % */ MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(quantize_info != (QuantizeInfo *) NULL); assert(quantize_info->signature == MagickSignature); quantize_info->signature=(~MagickSignature); quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info); return(quantize_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DitherImage() distributes the difference between an original image and % the corresponding color reduced algorithm to neighboring pixels using % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns % MagickTrue if the image is dithered otherwise MagickFalse. % % The format of the DitherImage method is: % % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static DoublePixelPacket **DestroyPixelThreadSet(DoublePixelPacket **pixels) { register ssize_t i; assert(pixels != (DoublePixelPacket **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (DoublePixelPacket *) NULL) pixels[i]=(DoublePixelPacket *) RelinquishMagickMemory(pixels[i]); pixels=(DoublePixelPacket **) RelinquishMagickMemory(pixels); return(pixels); } static DoublePixelPacket **AcquirePixelThreadSet(const size_t count) { DoublePixelPacket **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(DoublePixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (DoublePixelPacket **) NULL) return((DoublePixelPacket **) NULL); (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(DoublePixelPacket *) AcquireQuantumMemory(count, 2*sizeof(**pixels)); if (pixels[i] == (DoublePixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); } return(pixels); } static inline ssize_t CacheOffset(CubeInfo *cube_info, const DoublePixelPacket *pixel) { #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift))) #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift))) #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift))) #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift))) ssize_t offset; offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) | GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) | BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue)))); if (cube_info->associate_alpha != MagickFalse) offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->opacity))); return(offset); } static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info) { #define DitherImageTag "Dither/Image" CacheView *image_view; DoublePixelPacket **pixels; ExceptionInfo *exception; MagickBooleanType status; ssize_t y; /* Distribute quantization error using Floyd-Steinberg. */ pixels=AcquirePixelThreadSet(image->columns); if (pixels == (DoublePixelPacket **) NULL) return(MagickFalse); exception=(&image->exception); status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); CubeInfo cube; DoublePixelPacket *current, *previous; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; size_t index; ssize_t v; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); cube=(*cube_info); current=pixels[id]+(y & 0x01)*image->columns; previous=pixels[id]+((y+1) & 0x01)*image->columns; v=(ssize_t) ((y & 0x01) ? -1 : 1); for (x=0; x < (ssize_t) image->columns; x++) { DoublePixelPacket color, pixel; register ssize_t i; ssize_t u; u=(y & 0x01) ? (ssize_t) image->columns-1-x : x; AssociateAlphaPixel(&cube,q+u,&pixel); if (x > 0) { pixel.red+=7*current[u-v].red/16; pixel.green+=7*current[u-v].green/16; pixel.blue+=7*current[u-v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.opacity+=7*current[u-v].opacity/16; } if (y > 0) { if (x < (ssize_t) (image->columns-1)) { pixel.red+=previous[u+v].red/16; pixel.green+=previous[u+v].green/16; pixel.blue+=previous[u+v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.opacity+=previous[u+v].opacity/16; } pixel.red+=5*previous[u].red/16; pixel.green+=5*previous[u].green/16; pixel.blue+=5*previous[u].blue/16; if (cube.associate_alpha != MagickFalse) pixel.opacity+=5*previous[u].opacity/16; if (x > 0) { pixel.red+=3*previous[u-v].red/16; pixel.green+=3*previous[u-v].green/16; pixel.blue+=3*previous[u-v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.opacity+=3*previous[u-v].opacity/16; } } pixel.red=(MagickRealType) ClampPixel(pixel.red); pixel.green=(MagickRealType) ClampPixel(pixel.green); pixel.blue=(MagickRealType) ClampPixel(pixel.blue); if (cube.associate_alpha != MagickFalse) pixel.opacity=(MagickRealType) ClampPixel(pixel.opacity); i=CacheOffset(&cube,&pixel); if (cube.cache[i] < 0) { register NodeInfo *node_info; register size_t id; /* Identify the deepest node containing the pixel's color. */ node_info=cube.root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(&cube,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ cube.target=pixel; cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+ 1.0)+1.0); ClosestColor(image,&cube,node_info->parent); cube.cache[i]=(ssize_t) cube.color_number; } /* Assign pixel to closest colormap entry. */ index=(size_t) cube.cache[i]; if (image->storage_class == PseudoClass) SetPixelIndex(indexes+u,index); if (cube.quantize_info->measure_error == MagickFalse) { SetPixelRgb(q+u,image->colormap+index); if (cube.associate_alpha != MagickFalse) SetPixelOpacity(q+u,image->colormap[index].opacity); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; /* Store the error. */ AssociateAlphaPixel(&cube,image->colormap+index,&color); current[u].red=pixel.red-color.red; current[u].green=pixel.green-color.green; current[u].blue=pixel.blue-color.blue; if (cube.associate_alpha != MagickFalse) current[u].opacity=pixel.opacity-color.opacity; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } image_view=DestroyCacheView(image_view); pixels=DestroyPixelThreadSet(pixels); return(MagickTrue); } static MagickBooleanType RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int); static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info, const size_t level,const unsigned int direction) { if (level == 1) switch (direction) { case WestGravity: { (void) RiemersmaDither(image,image_view,cube_info,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); break; } case EastGravity: { (void) RiemersmaDither(image,image_view,cube_info,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); break; } case NorthGravity: { (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); break; } case SouthGravity: { (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); break; } default: break; } else switch (direction) { case WestGravity: { Riemersma(image,image_view,cube_info,level-1,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); Riemersma(image,image_view,cube_info,level-1,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); Riemersma(image,image_view,cube_info,level-1,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); Riemersma(image,image_view,cube_info,level-1,SouthGravity); break; } case EastGravity: { Riemersma(image,image_view,cube_info,level-1,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); Riemersma(image,image_view,cube_info,level-1,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); Riemersma(image,image_view,cube_info,level-1,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); Riemersma(image,image_view,cube_info,level-1,NorthGravity); break; } case NorthGravity: { Riemersma(image,image_view,cube_info,level-1,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); Riemersma(image,image_view,cube_info,level-1,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); Riemersma(image,image_view,cube_info,level-1,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); Riemersma(image,image_view,cube_info,level-1,EastGravity); break; } case SouthGravity: { Riemersma(image,image_view,cube_info,level-1,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); Riemersma(image,image_view,cube_info,level-1,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); Riemersma(image,image_view,cube_info,level-1,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); Riemersma(image,image_view,cube_info,level-1,WestGravity); break; } default: break; } } static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view, CubeInfo *cube_info,const unsigned int direction) { #define DitherImageTag "Dither/Image" DoublePixelPacket color, pixel; MagickBooleanType proceed; register CubeInfo *p; size_t index; p=cube_info; if ((p->x >= 0) && (p->x < (ssize_t) image->columns) && (p->y >= 0) && (p->y < (ssize_t) image->rows)) { ExceptionInfo *exception; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t i; /* Distribute error. */ exception=(&image->exception); q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickFalse); indexes=GetCacheViewAuthenticIndexQueue(image_view); AssociateAlphaPixel(cube_info,q,&pixel); for (i=0; i < ErrorQueueLength; i++) { pixel.red+=p->weights[i]*p->error[i].red; pixel.green+=p->weights[i]*p->error[i].green; pixel.blue+=p->weights[i]*p->error[i].blue; if (cube_info->associate_alpha != MagickFalse) pixel.opacity+=p->weights[i]*p->error[i].opacity; } pixel.red=(MagickRealType) ClampPixel(pixel.red); pixel.green=(MagickRealType) ClampPixel(pixel.green); pixel.blue=(MagickRealType) ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) pixel.opacity=(MagickRealType) ClampPixel(pixel.opacity); i=CacheOffset(cube_info,&pixel); if (p->cache[i] < 0) { register NodeInfo *node_info; register size_t id; /* Identify the deepest node containing the pixel's color. */ node_info=p->root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(cube_info,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ p->target=pixel; p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType) QuantumRange+1.0)+1.0); ClosestColor(image,p,node_info->parent); p->cache[i]=(ssize_t) p->color_number; } /* Assign pixel to closest colormap entry. */ index=(size_t) (1*p->cache[i]); if (image->storage_class == PseudoClass) *indexes=(IndexPacket) index; if (cube_info->quantize_info->measure_error == MagickFalse) { SetPixelRgb(q,image->colormap+index); if (cube_info->associate_alpha != MagickFalse) SetPixelOpacity(q,image->colormap[index].opacity); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) return(MagickFalse); /* Propagate the error as the last entry of the error queue. */ (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)* sizeof(p->error[0])); AssociateAlphaPixel(cube_info,image->colormap+index,&color); p->error[ErrorQueueLength-1].red=pixel.red-color.red; p->error[ErrorQueueLength-1].green=pixel.green-color.green; p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue; if (cube_info->associate_alpha != MagickFalse) p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity; proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span); if (proceed == MagickFalse) return(MagickFalse); p->offset++; } switch (direction) { case WestGravity: p->x--; break; case EastGravity: p->x++; break; case NorthGravity: p->y--; break; case SouthGravity: p->y++; break; } return(MagickTrue); } static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info) { CacheView *image_view; MagickBooleanType status; register ssize_t i; size_t depth; if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod) return(FloydSteinbergDither(image,cube_info)); /* Distribute quantization error along a Hilbert curve. */ (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength* sizeof(*cube_info->error)); cube_info->x=0; cube_info->y=0; i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows); for (depth=1; i != 0; depth++) i>>=1; if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows)) depth++; cube_info->offset=0; cube_info->span=(MagickSizeType) image->columns*image->rows; image_view=AcquireAuthenticCacheView(image,&image->exception); if (depth > 1) Riemersma(image,image_view,cube_info,depth-1,NorthGravity); status=RiemersmaDither(image,image_view,cube_info,ForgetGravity); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t C u b e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetCubeInfo() initialize the Cube data structure. % % The format of the GetCubeInfo method is: % % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info, % const size_t depth,const size_t maximum_colors) % % A description of each parameter follows. % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o depth: Normally, this integer value is zero or one. A zero or % one tells Quantize to choose a optimal tree depth of Log4(number_colors). % A tree of this depth generally allows the best representation of the % reference image with the least amount of memory and the fastest % computational speed. In some cases, such as an image with low color % dispersion (a few number of colors), a value other than % Log4(number_colors) is required. To expand the color tree completely, % use a value of 8. % % o maximum_colors: maximum colors. % */ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info, const size_t depth,const size_t maximum_colors) { CubeInfo *cube_info; MagickRealType sum, weight; register ssize_t i; size_t length; /* Initialize tree to describe color cube_info. */ cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info)); if (cube_info == (CubeInfo *) NULL) return((CubeInfo *) NULL); (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info)); cube_info->depth=depth; if (cube_info->depth > MaxTreeDepth) cube_info->depth=MaxTreeDepth; if (cube_info->depth < 2) cube_info->depth=2; cube_info->maximum_colors=maximum_colors; /* Initialize root node. */ cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL); if (cube_info->root == (NodeInfo *) NULL) return((CubeInfo *) NULL); cube_info->root->parent=cube_info->root; cube_info->quantize_info=CloneQuantizeInfo(quantize_info); if (cube_info->quantize_info->dither == MagickFalse) return(cube_info); /* Initialize dither resources. */ length=(size_t) (1UL << (4*(8-CacheShift))); cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache)); if (cube_info->memory_info == (MemoryInfo *) NULL) return((CubeInfo *) NULL); cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info); /* Initialize color cache. */ (void) ResetMagickMemory(cube_info->cache,(-1),sizeof(*cube_info->cache)* length); /* Distribute weights along a curve of exponential decay. */ weight=1.0; for (i=0; i < ErrorQueueLength; i++) { cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight); weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0)); } /* Normalize the weighting factors. */ weight=0.0; for (i=0; i < ErrorQueueLength; i++) weight+=cube_info->weights[i]; sum=0.0; for (i=0; i < ErrorQueueLength; i++) { cube_info->weights[i]/=weight; sum+=cube_info->weights[i]; } cube_info->weights[0]+=1.0-sum; return(cube_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t N o d e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNodeInfo() allocates memory for a new node in the color cube tree and % presets all fields to zero. % % The format of the GetNodeInfo method is: % % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id, % const size_t level,NodeInfo *parent) % % A description of each parameter follows. % % o node: The GetNodeInfo method returns a pointer to a queue of nodes. % % o id: Specifies the child number of the node. % % o level: Specifies the level in the storage_class the node resides. % */ static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id, const size_t level,NodeInfo *parent) { NodeInfo *node_info; if (cube_info->free_nodes == 0) { Nodes *nodes; /* Allocate a new queue of nodes. */ nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes)); if (nodes == (Nodes *) NULL) return((NodeInfo *) NULL); nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList, sizeof(*nodes->nodes)); if (nodes->nodes == (NodeInfo *) NULL) return((NodeInfo *) NULL); nodes->next=cube_info->node_queue; cube_info->node_queue=nodes; cube_info->next_node=nodes->nodes; cube_info->free_nodes=NodesInAList; } cube_info->nodes++; cube_info->free_nodes--; node_info=cube_info->next_node++; (void) ResetMagickMemory(node_info,0,sizeof(*node_info)); node_info->parent=parent; node_info->id=id; node_info->level=level; return(node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e Q u a n t i z e E r r o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageQuantizeError() measures the difference between the original % and quantized images. This difference is the total quantization error. % The error is computed by summing over all pixels in an image the distance % squared in RGB space between each reference pixel value and its quantized % value. These values are computed: % % o mean_error_per_pixel: This value is the mean error for any single % pixel in the image. % % o normalized_mean_square_error: This value is the normalized mean % quantization error for any single pixel in the image. This distance % measure is normalized to a range between 0 and 1. It is independent % of the range of red, green, and blue values in the image. % % o normalized_maximum_square_error: Thsi value is the normalized % maximum quantization error for any single pixel in the image. This % distance measure is normalized to a range between 0 and 1. It is % independent of the range of red, green, and blue values in your image. % % The format of the GetImageQuantizeError method is: % % MagickBooleanType GetImageQuantizeError(Image *image) % % A description of each parameter follows. % % o image: the image. % */ MagickExport MagickBooleanType GetImageQuantizeError(Image *image) { CacheView *image_view; ExceptionInfo *exception; IndexPacket *indexes; MagickRealType alpha, area, beta, distance, gamma, maximum_error, mean_error, mean_error_per_pixel; size_t index; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception); (void) ResetMagickMemory(&image->error,0,sizeof(image->error)); if (image->storage_class == DirectClass) return(MagickTrue); alpha=1.0; beta=1.0; area=3.0*image->columns*image->rows; maximum_error=0.0; mean_error_per_pixel=0.0; mean_error=0.0; exception=(&image->exception); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { index=1UL*GetPixelIndex(indexes+x); if (image->matte != MagickFalse) { alpha=(MagickRealType) (QuantumScale*(GetPixelAlpha(p))); beta=(MagickRealType) (QuantumScale*(QuantumRange- image->colormap[index].opacity)); } distance=fabs((double) (alpha*GetPixelRed(p)-beta* image->colormap[index].red)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; distance=fabs((double) (alpha*GetPixelGreen(p)-beta* image->colormap[index].green)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; distance=fabs((double) (alpha*GetPixelBlue(p)-beta* image->colormap[index].blue)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; p++; } } image_view=DestroyCacheView(image_view); gamma=PerceptibleReciprocal(area); image->error.mean_error_per_pixel=gamma*mean_error_per_pixel; image->error.normalized_mean_error=gamma*QuantumScale*QuantumScale*mean_error; image->error.normalized_maximum_error=QuantumScale*maximum_error; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantizeInfo() initializes the QuantizeInfo structure. % % The format of the GetQuantizeInfo method is: % % GetQuantizeInfo(QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to a QuantizeInfo structure. % */ MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(quantize_info != (QuantizeInfo *) NULL); (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info)); quantize_info->number_colors=256; quantize_info->dither=MagickTrue; quantize_info->dither_method=RiemersmaDitherMethod; quantize_info->colorspace=UndefinedColorspace; quantize_info->measure_error=MagickFalse; quantize_info->signature=MagickSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o s t e r i z e I m a g e C h a n n e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PosterizeImage() reduces the image to a limited number of colors for a % "poster" effect. % % The format of the PosterizeImage method is: % % MagickBooleanType PosterizeImage(Image *image,const size_t levels, % const MagickBooleanType dither) % MagickBooleanType PosterizeImageChannel(Image *image, % const ChannelType channel,const size_t levels, % const MagickBooleanType dither) % % A description of each parameter follows: % % o image: Specifies a pointer to an Image structure. % % o levels: Number of color levels allowed in each channel. Very low values % (2, 3, or 4) have the most visible effect. % % o dither: Set this integer value to something other than zero to dither % the mapped image. % */ static inline double MagickRound(double x) { /* Round the fraction to nearest integer. */ if ((x-floor(x)) < (ceil(x)-x)) return(floor(x)); return(ceil(x)); } MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels, const MagickBooleanType dither) { MagickBooleanType status; status=PosterizeImageChannel(image,DefaultChannels,levels,dither); return(status); } MagickExport MagickBooleanType PosterizeImageChannel(Image *image, const ChannelType channel,const size_t levels,const MagickBooleanType dither) { #define PosterizeImageTag "Posterize/Image" #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \ QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1)) CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; QuantizeInfo *quantize_info; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,1,1) #endif for (i=0; i < (ssize_t) image->colors; i++) { /* Posterize colormap. */ if ((channel & RedChannel) != 0) image->colormap[i].red=PosterizePixel(image->colormap[i].red); if ((channel & GreenChannel) != 0) image->colormap[i].green=PosterizePixel(image->colormap[i].green); if ((channel & BlueChannel) != 0) image->colormap[i].blue=PosterizePixel(image->colormap[i].blue); if ((channel & OpacityChannel) != 0) image->colormap[i].opacity=PosterizePixel(image->colormap[i].opacity); } /* Posterize image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,PosterizePixel(GetPixelRed(q))); if ((channel & GreenChannel) != 0) SetPixelGreen(q,PosterizePixel(GetPixelGreen(q))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,PosterizePixel(GetPixelBlue(q))); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetPixelOpacity(q,PosterizePixel(GetPixelOpacity(q))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,PosterizePixel(GetPixelIndex(indexes+x))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_PosterizeImageChannel) #endif proceed=SetImageProgress(image,PosterizeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL); quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels* levels,MaxColormapSize+1); quantize_info->dither=dither; quantize_info->tree_depth=MaxTreeDepth; status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e C h i l d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneChild() deletes the given node and merges its statistics into its % parent. % % The format of the PruneSubtree method is: % % PruneChild(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneChild(CubeInfo *cube_info,const NodeInfo *node_info) { NodeInfo *parent; register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneChild(cube_info,node_info->child[i]); /* Merge color statistics into parent. */ parent=node_info->parent; parent->number_unique+=node_info->number_unique; parent->total_color.red+=node_info->total_color.red; parent->total_color.green+=node_info->total_color.green; parent->total_color.blue+=node_info->total_color.blue; parent->total_color.opacity+=node_info->total_color.opacity; parent->child[node_info->id]=(NodeInfo *) NULL; cube_info->nodes--; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e L e v e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneLevel() deletes all nodes at the bottom level of the color tree merging % their color statistics into their parent node. % % The format of the PruneLevel method is: % % PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneLevel(cube_info,node_info->child[i]); if (node_info->level == cube_info->depth) PruneChild(cube_info,node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e T o C u b e D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneToCubeDepth() deletes any nodes at a depth greater than % cube_info->depth while merging their color statistics into their parent % node. % % The format of the PruneToCubeDepth method is: % % PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneToCubeDepth(cube_info,node_info->child[i]); if (node_info->level > cube_info->depth) PruneChild(cube_info,node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u a n t i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeImage() analyzes the colors within a reference image and chooses a % fixed number of colors to represent the image. The goal of the algorithm % is to minimize the color difference between the input and output image while % minimizing the processing time. % % The format of the QuantizeImage method is: % % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info, % Image *image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o image: the image. % */ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info, Image *image) { CubeInfo *cube_info; MagickBooleanType status; size_t depth, maximum_colors; assert(quantize_info != (const QuantizeInfo *) NULL); assert(quantize_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); maximum_colors=quantize_info->number_colors; if (maximum_colors == 0) maximum_colors=MaxColormapSize; if (maximum_colors > MaxColormapSize) maximum_colors=MaxColormapSize; if (image->matte == MagickFalse) { if (SetImageGray(image,&image->exception) != MagickFalse) (void) SetGrayscaleImage(image); } if ((image->storage_class == PseudoClass) && (image->colors <= maximum_colors)) { if ((quantize_info->colorspace != UndefinedColorspace) && (quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace(image,quantize_info->colorspace); return(MagickTrue); } depth=quantize_info->tree_depth; if (depth == 0) { size_t colors; /* Depth of color tree is: Log4(colormap size)+2. */ colors=maximum_colors; for (depth=1; colors != 0; depth++) colors>>=2; if ((quantize_info->dither != MagickFalse) && (depth > 2)) depth--; if ((image->matte != MagickFalse) && (depth > 5)) depth--; if (SetImageGray(image,&image->exception) != MagickFalse) depth=MaxTreeDepth; } /* Initialize color cube. */ cube_info=GetCubeInfo(quantize_info,depth,maximum_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,image,&image->exception); if (status != MagickFalse) { /* Reduce the number of colors in the image if it contains more than the maximum, otherwise we can disable dithering to improve the performance. */ if (cube_info->colors > cube_info->maximum_colors) ReduceImageColors(image,cube_info); else cube_info->quantize_info->dither_method=NoDitherMethod; status=AssignImageColors(image,cube_info); } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u a n t i z e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeImages() analyzes the colors within a set of reference images and % chooses a fixed number of colors to represent the set. The goal of the % algorithm is to minimize the color difference between the input and output % images while minimizing the processing time. % % The format of the QuantizeImages method is: % % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info, % Image *images) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o images: Specifies a pointer to a list of Image structures. % */ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info, Image *images) { CubeInfo *cube_info; Image *image; MagickBooleanType proceed, status; MagickProgressMonitor progress_monitor; register ssize_t i; size_t depth, maximum_colors, number_images; assert(quantize_info != (const QuantizeInfo *) NULL); assert(quantize_info->signature == MagickSignature); assert(images != (Image *) NULL); assert(images->signature == MagickSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); if (GetNextImageInList(images) == (Image *) NULL) { /* Handle a single image with QuantizeImage. */ status=QuantizeImage(quantize_info,images); return(status); } status=MagickFalse; maximum_colors=quantize_info->number_colors; if (maximum_colors == 0) maximum_colors=MaxColormapSize; if (maximum_colors > MaxColormapSize) maximum_colors=MaxColormapSize; depth=quantize_info->tree_depth; if (depth == 0) { size_t colors; /* Depth of color tree is: Log4(colormap size)+2. */ colors=maximum_colors; for (depth=1; colors != 0; depth++) colors>>=2; if (quantize_info->dither != MagickFalse) depth--; } /* Initialize color cube. */ cube_info=GetCubeInfo(quantize_info,depth,maximum_colors); if (cube_info == (CubeInfo *) NULL) { (void) ThrowMagickException(&images->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return(MagickFalse); } number_images=GetImageListLength(images); image=images; for (i=0; image != (Image *) NULL; i++) { progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL, image->client_data); status=ClassifyImageColors(cube_info,image,&image->exception); if (status == MagickFalse) break; (void) SetImageProgressMonitor(image,progress_monitor,image->client_data); proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); } if (status != MagickFalse) { /* Reduce the number of colors in an image sequence. */ ReduceImageColors(images,cube_info); image=images; for (i=0; image != (Image *) NULL; i++) { progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,image->client_data); status=AssignImageColors(image,cube_info); if (status == MagickFalse) break; (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); } } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u a n t i z e E r r o r F l a t t e n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeErrorFlatten() traverses the color cube and flattens the quantization % error into a sorted 1D array. This accelerates the color reduction process. % % Contributed by Yoya. % % The format of the QuantizeErrorFlatten method is: % % size_t QuantizeErrorFlatten(const CubeInfo *cube_info, % const NodeInfo *node_info,const ssize_t offset, % MagickRealType *quantize_error) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is current pointer. % % o offset: quantize error offset. % % o quantize_error: the quantization error vector. % */ static size_t QuantizeErrorFlatten(const CubeInfo *cube_info, const NodeInfo *node_info,const ssize_t offset, MagickRealType *quantize_error) { register ssize_t i; size_t n, number_children; if (offset >= (ssize_t) cube_info->nodes) return(0); quantize_error[offset]=node_info->quantize_error; n=1; number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children ; i++) if (node_info->child[i] != (NodeInfo *) NULL) n+=QuantizeErrorFlatten(cube_info,node_info->child[i],offset+n, quantize_error); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e d u c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Reduce() traverses the color cube tree and prunes any node whose % quantization error falls below a particular threshold. % % The format of the Reduce method is: % % Reduce(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void Reduce(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) Reduce(cube_info,node_info->child[i]); if (node_info->quantize_error <= cube_info->pruning_threshold) PruneChild(cube_info,node_info); else { /* Find minimum pruning threshold. */ if (node_info->number_unique > 0) cube_info->colors++; if (node_info->quantize_error < cube_info->next_threshold) cube_info->next_threshold=node_info->quantize_error; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e d u c e I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReduceImageColors() repeatedly prunes the tree until the number of nodes % with n2 > 0 is less than or equal to the maximum number of colors allowed % in the output image. On any given iteration over the tree, it selects % those nodes whose E value is minimal for pruning and merges their % color statistics upward. It uses a pruning threshold, Ep, to govern % node selection as follows: % % Ep = 0 % while number of nodes with (n2 > 0) > required maximum number of colors % prune all nodes such that E <= Ep % Set Ep to minimum E in remaining nodes % % This has the effect of minimizing any quantization error when merging % two nodes together. % % When a node to be pruned has offspring, the pruning procedure invokes % itself recursively in order to prune the tree from the leaves upward. % n2, Sr, Sg, and Sb in a node being pruned are always added to the % corresponding data in that node's parent. This retains the pruned % node's color characteristics for later averaging. % % For each node, n2 pixels exist for which that node represents the % smallest volume in RGB space containing those pixel's colors. When n2 % > 0 the node will uniquely define a color in the output image. At the % beginning of reduction, n2 = 0 for all nodes except a the leaves of % the tree which represent colors present in the input image. % % The other pixel count, n1, indicates the total number of colors % within the cubic volume which the node represents. This includes n1 - % n2 pixels whose colors should be defined by nodes at a lower level in % the tree. % % The format of the ReduceImageColors method is: % % ReduceImageColors(const Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static int MagickRealTypeCompare(const void *error_p,const void *error_q) { MagickRealType *p, *q; p=(MagickRealType *) error_p; q=(MagickRealType *) error_q; if (*p > *q) return(1); if (fabs((double) (*q-*p)) <= MagickEpsilon) return(0); return(-1); } static void ReduceImageColors(const Image *image,CubeInfo *cube_info) { #define ReduceImageTag "Reduce/Image" MagickBooleanType proceed; MagickOffsetType offset; size_t span; cube_info->next_threshold=0.0; if (cube_info->colors > cube_info->maximum_colors) { MagickRealType *quantize_error; /* Enable rapid reduction of the number of unique colors. */ quantize_error=(MagickRealType *) AcquireQuantumMemory(cube_info->nodes, sizeof(*quantize_error)); if (quantize_error != (MagickRealType *) NULL) { (void) QuantizeErrorFlatten(cube_info,cube_info->root,0, quantize_error); qsort(quantize_error,cube_info->nodes,sizeof(MagickRealType), MagickRealTypeCompare); if (cube_info->nodes > (110*(cube_info->maximum_colors+1)/100)) cube_info->next_threshold=quantize_error[cube_info->nodes-110* (cube_info->maximum_colors+1)/100]; quantize_error=(MagickRealType *) RelinquishMagickMemory( quantize_error); } } for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; ) { cube_info->pruning_threshold=cube_info->next_threshold; cube_info->next_threshold=cube_info->root->quantize_error-1; cube_info->colors=0; Reduce(cube_info,cube_info->root); offset=(MagickOffsetType) span-cube_info->colors; proceed=SetImageProgress(image,ReduceImageTag,offset,span- cube_info->maximum_colors+1); if (proceed == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m a p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemapImage() replaces the colors of an image with the closest color from % a reference image. % % The format of the RemapImage method is: % % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info, % Image *image,const Image *remap_image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o image: the image. % % o remap_image: the reference image. % */ MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info, Image *image,const Image *remap_image) { CubeInfo *cube_info; MagickBooleanType status; /* Initialize color cube. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(remap_image != (Image *) NULL); assert(remap_image->signature == MagickSignature); cube_info=GetCubeInfo(quantize_info,MaxTreeDepth, quantize_info->number_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,remap_image,&image->exception); if (status != MagickFalse) { /* Classify image colors from the reference image. */ cube_info->quantize_info->number_colors=cube_info->colors; status=AssignImageColors(image,cube_info); } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m a p I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemapImages() replaces the colors of a sequence of images with the % closest color from a reference image. % % The format of the RemapImage method is: % % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info, % Image *images,Image *remap_image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o images: the image sequence. % % o remap_image: the reference image. % */ MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info, Image *images,const Image *remap_image) { CubeInfo *cube_info; Image *image; MagickBooleanType status; assert(images != (Image *) NULL); assert(images->signature == MagickSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); image=images; if (remap_image == (Image *) NULL) { /* Create a global colormap for an image sequence. */ status=QuantizeImages(quantize_info,images); return(status); } /* Classify image colors from the reference image. */ cube_info=GetCubeInfo(quantize_info,MaxTreeDepth, quantize_info->number_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,remap_image,&image->exception); if (status != MagickFalse) { /* Classify image colors from the reference image. */ cube_info->quantize_info->number_colors=cube_info->colors; image=images; for ( ; image != (Image *) NULL; image=GetNextImageInList(image)) { status=AssignImageColors(image,cube_info); if (status == MagickFalse) break; } } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t G r a y s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetGrayscaleImage() converts an image to a PseudoClass grayscale image. % % The format of the SetGrayscaleImage method is: % % MagickBooleanType SetGrayscaleImage(Image *image) % % A description of each parameter follows: % % o image: The image. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { PixelPacket *color_1, *color_2; int intensity; color_1=(PixelPacket *) x; color_2=(PixelPacket *) y; intensity=PixelPacketIntensity(color_1)-(int) PixelPacketIntensity(color_2); return((int) intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickBooleanType SetGrayscaleImage(Image *image) { CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; PixelPacket *colormap; register ssize_t i; ssize_t *colormap_index, j, y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->type != GrayscaleType) (void) TransformImageColorspace(image,GRAYColorspace); colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize, sizeof(*colormap_index)); if (colormap_index == (ssize_t *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); if (image->storage_class != PseudoClass) { ExceptionInfo *exception; (void) ResetMagickMemory(colormap_index,(-1),MaxColormapSize* sizeof(*colormap_index)); if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse) { colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } image->colors=0; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { register size_t intensity; intensity=ScaleQuantumToMap(GetPixelRed(q)); if (colormap_index[intensity] < 0) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SetGrayscaleImage) #endif if (colormap_index[intensity] < 0) { colormap_index[intensity]=(ssize_t) image->colors; image->colormap[image->colors].red=GetPixelRed(q); image->colormap[image->colors].green=GetPixelGreen(q); image->colormap[image->colors].blue=GetPixelBlue(q); image->colors++; } } SetPixelIndex(indexes+x,colormap_index[intensity]); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); } for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].opacity=(unsigned short) i; qsort((void *) image->colormap,image->colors,sizeof(PixelPacket), IntensityCompare); colormap=(PixelPacket *) AcquireQuantumMemory(image->colors, sizeof(*colormap)); if (colormap == (PixelPacket *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); j=0; colormap[j]=image->colormap[0]; for (i=0; i < (ssize_t) image->colors; i++) { if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse) { j++; colormap[j]=image->colormap[i]; } colormap_index[(ssize_t) image->colormap[i].opacity]=j; } image->colors=(size_t) (j+1); image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap); image->colormap=colormap; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,colormap_index[ScaleQuantumToMap(GetPixelIndex( indexes+x))]); if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); image->type=GrayscaleType; if (SetImageMonochrome(image,&image->exception) != MagickFalse) image->type=BilevelType; return(status); }
./CrossVul/dataset_final_sorted/CWE-772/c/good_2618_1
crossvul-cpp_data_bad_2613_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N GGGG % % P P NN N G % % PPPP N N N G GG % % P N NN G G % % P N N GGG % % % % % % Read/Write Portable Network Graphics Image Format % % % % Software Design % % Cristy % % Glenn Randers-Pehrson % % November 1997 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/histogram.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/layer.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/transform.h" #include "magick/utility.h" #if defined(MAGICKCORE_PNG_DELEGATE) /* Suppress libpng pedantic warnings that were added in * libpng-1.2.41 and libpng-1.4.0. If you are working on * migration to libpng-1.5, remove these defines and then * fix any code that generates warnings. */ /* #define PNG_DEPRECATED Use of this function is deprecated */ /* #define PNG_USE_RESULT The result of this function must be checked */ /* #define PNG_NORETURN This function does not return */ /* #define PNG_ALLOCATED The result of the function is new memory */ /* #define PNG_DEPSTRUCT Access to this struct member is deprecated */ /* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */ #define PNG_PTR_NORETURN #include "png.h" #include "zlib.h" /* ImageMagick differences */ #define first_scene scene #if PNG_LIBPNG_VER > 10011 /* Optional declarations. Define or undefine them as you like. */ /* #define PNG_DEBUG -- turning this on breaks VisualC compiling */ /* Features under construction. Define these to work on them. */ #undef MNG_OBJECT_BUFFERS #undef MNG_BASI_SUPPORTED #define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */ #define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */ #if defined(MAGICKCORE_JPEG_DELEGATE) # define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */ #endif #if !defined(RGBColorMatchExact) #define IsPNGColorEqual(color,target) \ (((color).red == (target).red) && \ ((color).green == (target).green) && \ ((color).blue == (target).blue)) #endif /* Table of recognized sRGB ICC profiles */ struct sRGB_info_struct { png_uint_32 len; png_uint_32 crc; png_byte intent; }; const struct sRGB_info_struct sRGB_info[] = { /* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */ { 3048, 0x3b8772b9UL, 0}, /* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */ { 3052, 0x427ebb21UL, 1}, /* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */ {60988, 0x306fd8aeUL, 0}, /* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */ {60960, 0xbbef7812UL, 0}, /* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */ { 3024, 0x5d5129ceUL, 1}, /* HP-Microsoft sRGB v2 perceptual */ { 3144, 0x182ea552UL, 0}, /* HP-Microsoft sRGB v2 media-relative */ { 3144, 0xf29e526dUL, 1}, /* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */ { 524, 0xd4938c39UL, 0}, /* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */ { 3212, 0x034af5a1UL, 0}, /* Not recognized */ { 0, 0x00000000UL, 0}, }; /* Macros for left-bit-replication to ensure that pixels * and PixelPackets all have the same image->depth, and for use * in PNG8 quantization. */ /* LBR01: Replicate top bit */ #define LBR01PacketRed(pixelpacket) \ (pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketGreen(pixelpacket) \ (pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketBlue(pixelpacket) \ (pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketOpacity(pixelpacket) \ (pixelpacket).opacity=(ScaleQuantumToChar((pixelpacket).opacity) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketRGB(pixelpacket) \ { \ LBR01PacketRed((pixelpacket)); \ LBR01PacketGreen((pixelpacket)); \ LBR01PacketBlue((pixelpacket)); \ } #define LBR01PacketRGBO(pixelpacket) \ { \ LBR01PacketRGB((pixelpacket)); \ LBR01PacketOpacity((pixelpacket)); \ } #define LBR01PixelRed(pixel) \ (SetPixelRed((pixel), \ ScaleQuantumToChar(GetPixelRed((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelGreen(pixel) \ (SetPixelGreen((pixel), \ ScaleQuantumToChar(GetPixelGreen((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelBlue(pixel) \ (SetPixelBlue((pixel), \ ScaleQuantumToChar(GetPixelBlue((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelOpacity(pixel) \ (SetPixelOpacity((pixel), \ ScaleQuantumToChar(GetPixelOpacity((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelRGB(pixel) \ { \ LBR01PixelRed((pixel)); \ LBR01PixelGreen((pixel)); \ LBR01PixelBlue((pixel)); \ } #define LBR01PixelRGBO(pixel) \ { \ LBR01PixelRGB((pixel)); \ LBR01PixelOpacity((pixel)); \ } /* LBR02: Replicate top 2 bits */ #define LBR02PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketOpacity(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xc0; \ (pixelpacket).opacity=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketRGB(pixelpacket) \ { \ LBR02PacketRed((pixelpacket)); \ LBR02PacketGreen((pixelpacket)); \ LBR02PacketBlue((pixelpacket)); \ } #define LBR02PacketRGBO(pixelpacket) \ { \ LBR02PacketRGB((pixelpacket)); \ LBR02PacketOpacity((pixelpacket)); \ } #define LBR02PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xc0; \ SetPixelRed((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xc0; \ SetPixelGreen((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xc0; \ SetPixelBlue((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02Opacity(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xc0; \ SetPixelOpacity((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelRGB(pixel) \ { \ LBR02PixelRed((pixel)); \ LBR02PixelGreen((pixel)); \ LBR02PixelBlue((pixel)); \ } #define LBR02PixelRGBO(pixel) \ { \ LBR02PixelRGB((pixel)); \ LBR02Opacity((pixel)); \ } /* LBR03: Replicate top 3 bits (only used with opaque pixels during PNG8 quantization) */ #define LBR03PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketRGB(pixelpacket) \ { \ LBR03PacketRed((pixelpacket)); \ LBR03PacketGreen((pixelpacket)); \ LBR03PacketBlue((pixelpacket)); \ } #define LBR03PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xe0; \ SetPixelRed((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xe0; \ SetPixelGreen((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelBlue(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue((pixel))) \ & 0xe0; \ SetPixelBlue((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelRGB(pixel) \ { \ LBR03PixelRed((pixel)); \ LBR03PixelGreen((pixel)); \ LBR03PixelBlue((pixel)); \ } /* LBR04: Replicate top 4 bits */ #define LBR04PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \ (pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \ (pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \ (pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketOpacity(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xf0; \ (pixelpacket).opacity=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketRGB(pixelpacket) \ { \ LBR04PacketRed((pixelpacket)); \ LBR04PacketGreen((pixelpacket)); \ LBR04PacketBlue((pixelpacket)); \ } #define LBR04PacketRGBO(pixelpacket) \ { \ LBR04PacketRGB((pixelpacket)); \ LBR04PacketOpacity((pixelpacket)); \ } #define LBR04PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xf0; \ SetPixelRed((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xf0; \ SetPixelGreen((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xf0; \ SetPixelBlue((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelOpacity(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xf0; \ SetPixelOpacity((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelRGB(pixel) \ { \ LBR04PixelRed((pixel)); \ LBR04PixelGreen((pixel)); \ LBR04PixelBlue((pixel)); \ } #define LBR04PixelRGBO(pixel) \ { \ LBR04PixelRGB((pixel)); \ LBR04PixelOpacity((pixel)); \ } /* Establish thread safety. setjmp/longjmp is claimed to be safe on these platforms: setjmp/longjmp is alleged to be unsafe on these platforms: */ #ifdef PNG_SETJMP_SUPPORTED # ifndef IMPNG_SETJMP_IS_THREAD_SAFE # define IMPNG_SETJMP_NOT_THREAD_SAFE # endif # ifdef IMPNG_SETJMP_NOT_THREAD_SAFE static SemaphoreInfo *ping_semaphore = (SemaphoreInfo *) NULL; # endif #endif /* This temporary until I set up malloc'ed object attributes array. Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but waste more memory. */ #define MNG_MAX_OBJECTS 256 /* If this not defined, spec is interpreted strictly. If it is defined, an attempt will be made to recover from some errors, including o global PLTE too short */ #undef MNG_LOOSE /* Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8, PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here. PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and will be enabled by default in libpng-1.2.0. */ #ifdef PNG_MNG_FEATURES_SUPPORTED # ifndef PNG_READ_EMPTY_PLTE_SUPPORTED # define PNG_READ_EMPTY_PLTE_SUPPORTED # endif # ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED # define PNG_WRITE_EMPTY_PLTE_SUPPORTED # endif #endif /* Maximum valid size_t in PNG/MNG chunks is (2^31)-1 This macro is only defined in libpng-1.0.3 and later. Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6 */ #ifndef PNG_UINT_31_MAX #define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL #endif /* Constant strings for known chunk types. If you need to add a chunk, add a string holding the name here. To make the code more portable, we use ASCII numbers like this, not characters. */ /* until registration of eXIf */ static const png_byte mng_exIf[5]={101, 120, 73, 102, (png_byte) '\0'}; /* after registration of eXIf */ static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'}; static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'}; static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'}; static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'}; static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'}; static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'}; static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'}; static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'}; static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'}; static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'}; static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'}; static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'}; static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'}; static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'}; static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'}; static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'}; static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'}; static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'}; static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'}; static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'}; static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'}; static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'}; static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'}; static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'}; static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'}; static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'}; static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'}; static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'}; static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'}; static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'}; #if defined(JNG_SUPPORTED) static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'}; static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'}; static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'}; static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'}; #endif #if 0 /* Other known chunks that are not yet supported by ImageMagick: */ static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'}; static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'}; static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'}; static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'}; static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'}; static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'}; static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'}; #endif typedef struct _MngBox { long left, right, top, bottom; } MngBox; typedef struct _MngPair { volatile long a, b; } MngPair; #ifdef MNG_OBJECT_BUFFERS typedef struct _MngBuffer { size_t height, width; Image *image; png_color plte[256]; int reference_count; unsigned char alpha_sample_depth, compression_method, color_type, concrete, filter_method, frozen, image_type, interlace_method, pixel_sample_depth, plte_length, sample_depth, viewable; } MngBuffer; #endif typedef struct _MngInfo { #ifdef MNG_OBJECT_BUFFERS MngBuffer *ob[MNG_MAX_OBJECTS]; #endif Image * image; RectangleInfo page; int adjoin, #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED bytes_in_read_buffer, found_empty_plte, #endif equal_backgrounds, equal_chrms, equal_gammas, #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) equal_palettes, #endif equal_physs, equal_srgbs, framing_mode, have_global_bkgd, have_global_chrm, have_global_gama, have_global_phys, have_global_sbit, have_global_srgb, have_saved_bkgd_index, have_write_global_chrm, have_write_global_gama, have_write_global_plte, have_write_global_srgb, need_fram, object_id, old_framing_mode, saved_bkgd_index; int new_number_colors; ssize_t image_found, loop_count[256], loop_iteration[256], scenes_found, x_off[MNG_MAX_OBJECTS], y_off[MNG_MAX_OBJECTS]; MngBox clip, frame, image_box, object_clip[MNG_MAX_OBJECTS]; unsigned char /* These flags could be combined into one byte */ exists[MNG_MAX_OBJECTS], frozen[MNG_MAX_OBJECTS], loop_active[256], invisible[MNG_MAX_OBJECTS], viewable[MNG_MAX_OBJECTS]; MagickOffsetType loop_jump[256]; png_colorp global_plte; png_color_8 global_sbit; png_byte #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED read_buffer[8], #endif global_trns[256]; float global_gamma; ChromaticityInfo global_chrm; RenderingIntent global_srgb_intent; unsigned int delay, global_plte_length, global_trns_length, global_x_pixels_per_unit, global_y_pixels_per_unit, mng_width, mng_height, ticks_per_second; MagickBooleanType need_blob; unsigned int IsPalette, global_phys_unit_type, basi_warning, clon_warning, dhdr_warning, jhdr_warning, magn_warning, past_warning, phyg_warning, phys_warning, sbit_warning, show_warning, mng_type, write_mng, write_png_colortype, write_png_depth, write_png_compression_level, write_png_compression_strategy, write_png_compression_filter, write_png8, write_png24, write_png32, write_png48, write_png64; #ifdef MNG_BASI_SUPPORTED size_t basi_width, basi_height; unsigned int basi_depth, basi_color_type, basi_compression_method, basi_filter_type, basi_interlace_method, basi_red, basi_green, basi_blue, basi_alpha, basi_viewable; #endif png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; PixelPacket mng_global_bkgd; /* Added at version 6.6.6-7 */ MagickBooleanType ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, ping_exclude_eXIf, ping_exclude_EXIF, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tRNS, ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, /* Added at version 6.8.5-7 */ ping_preserve_iCCP, /* Added at version 6.8.9-9 */ ping_exclude_tIME; } MngInfo; #endif /* VER */ /* Forward declarations. */ static MagickBooleanType WritePNGImage(const ImageInfo *,Image *); static MagickBooleanType WriteMNGImage(const ImageInfo *,Image *); #if defined(JNG_SUPPORTED) static MagickBooleanType WriteJNGImage(const ImageInfo *,Image *); #endif #if PNG_LIBPNG_VER > 10011 #if (MAGICKCORE_QUANTUM_DEPTH >= 16) static MagickBooleanType LosslessReduceDepthOK(Image *image) { /* Reduce bit depth if it can be reduced losslessly from 16+ to 8. * * This is true if the high byte and the next highest byte of * each sample of the image, the colormap, and the background color * are equal to each other. We check this by seeing if the samples * are unchanged when we scale them down to 8 and back up to Quantum. * * We don't use the method GetImageDepth() because it doesn't check * background and doesn't handle PseudoClass specially. */ #define QuantumToCharToQuantumEqQuantum(quantum) \ ((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum) MagickBooleanType ok_to_reduce=MagickFalse; if (image->depth >= 16) { const PixelPacket *p; ok_to_reduce= QuantumToCharToQuantumEqQuantum(image->background_color.red) && QuantumToCharToQuantumEqQuantum(image->background_color.green) && QuantumToCharToQuantumEqQuantum(image->background_color.blue) ? MagickTrue : MagickFalse; if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass) { int indx; for (indx=0; indx < (ssize_t) image->colors; indx++) { ok_to_reduce=( QuantumToCharToQuantumEqQuantum( image->colormap[indx].red) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].green) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].blue)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; } } if ((ok_to_reduce != MagickFalse) && (image->storage_class != PseudoClass)) { ssize_t y; register ssize_t x; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) { ok_to_reduce = MagickFalse; break; } for (x=(ssize_t) image->columns-1; x >= 0; x--) { ok_to_reduce= QuantumToCharToQuantumEqQuantum(GetPixelRed(p)) && QuantumToCharToQuantumEqQuantum(GetPixelGreen(p)) && QuantumToCharToQuantumEqQuantum(GetPixelBlue(p)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; p++; } if (x >= 0) break; } } if (ok_to_reduce != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " OK to reduce PNG bit depth to 8 without loss of info"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Not OK to reduce PNG bit depth to 8 without loss of info"); } } return ok_to_reduce; } #endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */ static const char* PngColorTypeToString(const unsigned int color_type) { const char *result = "Unknown"; switch (color_type) { case PNG_COLOR_TYPE_GRAY: result = "Gray"; break; case PNG_COLOR_TYPE_GRAY_ALPHA: result = "Gray+Alpha"; break; case PNG_COLOR_TYPE_PALETTE: result = "Palette"; break; case PNG_COLOR_TYPE_RGB: result = "RGB"; break; case PNG_COLOR_TYPE_RGB_ALPHA: result = "RGB+Alpha"; break; } return result; } static int Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent) { switch (intent) { case PerceptualIntent: return 0; case RelativeIntent: return 1; case SaturationIntent: return 2; case AbsoluteIntent: return 3; default: return -1; } } static RenderingIntent Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return PerceptualIntent; case 1: return RelativeIntent; case 2: return SaturationIntent; case 3: return AbsoluteIntent; default: return UndefinedIntent; } } static const char * Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return "Perceptual Intent"; case 1: return "Relative Intent"; case 2: return "Saturation Intent"; case 3: return "Absolute Intent"; default: return "Undefined Intent"; } } static const char * Magick_ColorType_from_PNG_ColorType(const int ping_colortype) { switch (ping_colortype) { case 0: return "Grayscale"; case 2: return "Truecolor"; case 3: return "Indexed"; case 4: return "GrayAlpha"; case 6: return "RGBA"; default: return "UndefinedColorType"; } } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* MAGICKCORE_PNG_DELEGATE */ /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMNG() returns MagickTrue if the image format type, identified by the % magick string, is MNG. % % The format of the IsMNG method is: % % MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJNG() returns MagickTrue if the image format type, identified by the % magick string, is JNG. % % The format of the IsJNG method is: % % MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNG() returns MagickTrue if the image format type, identified by the % magick string, is PNG. % % The format of the IsPNG method is: % % MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_PNG_DELEGATE) #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if (PNG_LIBPNG_VER > 10011) static size_t WriteBlobMSBULong(Image *image,const size_t value) { unsigned char buffer[4]; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; return((size_t) WriteBlob(image,4,buffer)); } static void PNGLong(png_bytep p,png_uint_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGsLong(png_bytep p,png_int_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGShort(png_bytep p,png_uint_16 value) { *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGType(png_bytep p,const png_byte *type) { (void) CopyMagickMemory(p,type,4*sizeof(png_byte)); } static void LogPNGChunk(MagickBooleanType logging, const png_byte *type, size_t length) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing %c%c%c%c chunk, length: %.20g", type[0],type[1],type[2],type[3],(double) length); } #endif /* PNG_LIBPNG_VER > 10011 */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNGImage() reads a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image or set of images. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadPNGImage method is: % % Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % % To do, more or less in chronological order (as of version 5.5.2, % November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage): % % Get 16-bit cheap transparency working. % % (At this point, PNG decoding is supposed to be in full MNG-LC compliance) % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % (At this point, PNG encoding should be in full MNG compliance) % % Provide options for choice of background to use when the MNG BACK % chunk is not present or is not mandatory (i.e., leave transparent, % user specified, MNG BACK, PNG bKGD) % % Implement LOOP/ENDL [done, but could do discretionary loops more % efficiently by linking in the duplicate frames.]. % % Decode and act on the MHDR simplicity profile (offer option to reject % files or attempt to process them anyway when the profile isn't LC or VLC). % % Upgrade to full MNG without Delta-PNG. % % o BACK [done a while ago except for background image ID] % o MOVE [done 15 May 1999] % o CLIP [done 15 May 1999] % o DISC [done 19 May 1999] % o SAVE [partially done 19 May 1999 (marks objects frozen)] % o SEEK [partially done 19 May 1999 (discard function only)] % o SHOW % o PAST % o BASI % o MNG-level tEXt/iTXt/zTXt % o pHYg % o pHYs % o sBIT % o bKGD % o iTXt (wait for libpng implementation). % % Use the scene signature to discover when an identical scene is % being reused, and just point to the original image->exception instead % of storing another set of pixels. This not specific to MNG % but could be applied generally. % % Upgrade to full MNG with Delta-PNG. % % JNG tEXt/iTXt/zTXt % % We will not attempt to read files containing the CgBI chunk. % They are really Xcode files meant for display on the iPhone. % These are not valid PNG files and it is impossible to recover % the original PNG from files that have been converted to Xcode-PNG, % since irretrievable loss of color data has occurred due to the % use of premultiplied alpha. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* This the function that does the actual reading of data. It is the same as the one supplied in libpng, except that it receives the datastream from the ReadBlob() function instead of standard input. */ static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) ReadBlob(image,(size_t) length,data); if (check != length) { char msg[MaxTextExtent]; (void) FormatLocaleString(msg,MaxTextExtent, "Expected %.20g bytes; found %.20g bytes",(double) length, (double) check); png_warning(png_ptr,msg); png_error(png_ptr,"Read Exception"); } } } #if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \ !defined(PNG_MNG_FEATURES_SUPPORTED) /* We use mng_get_data() instead of png_get_data() if we have a libpng * older than libpng-1.0.3a, which was the first to allow the empty * PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was * ifdef'ed out. Earlier versions would crash if the bKGD chunk was * encountered after an empty PLTE, so we have to look ahead for bKGD * chunks and remove them from the datastream that is passed to libpng, * and store their contents for later use. */ static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { MngInfo *mng_info; Image *image; png_size_t check; register ssize_t i; i=0; mng_info=(MngInfo *) png_get_io_ptr(png_ptr); image=(Image *) mng_info->image; while (mng_info->bytes_in_read_buffer && length) { data[i]=mng_info->read_buffer[i]; mng_info->bytes_in_read_buffer--; length--; i++; } if (length != 0) { check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data); if (check != length) png_error(png_ptr,"Read Exception"); if (length == 4) { if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 0)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0) mng_info->found_empty_plte=MagickTrue; if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0) { mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; } } if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 1)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0) if (mng_info->found_empty_plte) { /* Skip the bKGD data byte and CRC. */ check=(png_size_t) ReadBlob(image,5,(char *) mng_info->read_buffer); check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->saved_bkgd_index=mng_info->read_buffer[0]; mng_info->have_saved_bkgd_index=MagickTrue; mng_info->bytes_in_read_buffer=0; } } } } } #endif static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) WriteBlob(image,(size_t) length,data); if (check != length) png_error(png_ptr,"WriteBlob Failed"); } } static void png_flush_data(png_structp png_ptr) { (void) png_ptr; } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED static int PalettesAreEqual(Image *a,Image *b) { ssize_t i; if ((a == (Image *) NULL) || (b == (Image *) NULL)) return((int) MagickFalse); if (a->storage_class != PseudoClass || b->storage_class != PseudoClass) return((int) MagickFalse); if (a->colors != b->colors) return((int) MagickFalse); for (i=0; i < (ssize_t) a->colors; i++) { if ((a->colormap[i].red != b->colormap[i].red) || (a->colormap[i].green != b->colormap[i].green) || (a->colormap[i].blue != b->colormap[i].blue)) return((int) MagickFalse); } return((int) MagickTrue); } #endif static void MngInfoDiscardObject(MngInfo *mng_info,int i) { if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) && mng_info->exists[i] && !mng_info->frozen[i]) { #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) { if (mng_info->ob[i]->reference_count > 0) mng_info->ob[i]->reference_count--; if (mng_info->ob[i]->reference_count == 0) { if (mng_info->ob[i]->image != (Image *) NULL) mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image); mng_info->ob[i]=DestroyString(mng_info->ob[i]); } } mng_info->ob[i]=(MngBuffer *) NULL; #endif mng_info->exists[i]=MagickFalse; mng_info->invisible[i]=MagickFalse; mng_info->viewable[i]=MagickFalse; mng_info->frozen[i]=MagickFalse; mng_info->x_off[i]=0; mng_info->y_off[i]=0; mng_info->object_clip[i].left=0; mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].top=0; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } } static MngInfo *MngInfoFreeStruct(MngInfo *mng_info) { register ssize_t i; if (mng_info == (MngInfo *) NULL) return((MngInfo *) NULL); for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); if (mng_info->global_plte != (png_colorp) NULL) mng_info->global_plte=(png_colorp) RelinquishMagickMemory(mng_info->global_plte); return((MngInfo *) RelinquishMagickMemory(mng_info)); } static MngBox mng_minimum_box(MngBox box1,MngBox box2) { MngBox box; box=box1; if (box.left < box2.left) box.left=box2.left; if (box.top < box2.top) box.top=box2.top; if (box.right > box2.right) box.right=box2.right; if (box.bottom > box2.bottom) box.bottom=box2.bottom; return box; } static MngBox mng_read_box(MngBox previous_box,char delta_type,unsigned char *p) { MngBox box; /* Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk. */ box.left=(ssize_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); box.right=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); box.top=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); box.bottom=(ssize_t) ((p[12] << 24) | (p[13] << 16) | (p[14] << 8) | p[15]); if (delta_type != 0) { box.left+=previous_box.left; box.right+=previous_box.right; box.top+=previous_box.top; box.bottom+=previous_box.bottom; } return(box); } static MngPair mng_read_pair(MngPair previous_pair,int delta_type, unsigned char *p) { MngPair pair; /* Read two ssize_ts from CLON, MOVE or PAST chunk */ pair.a=(long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); pair.b=(long) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (delta_type != 0) { pair.a+=previous_pair.a; pair.b+=previous_pair.b; } return(pair); } static long mng_get_long(unsigned char *p) { return((long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3])); } typedef struct _PNGErrorInfo { Image *image; ExceptionInfo *exception; } PNGErrorInfo; static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message) { Image *image; image=(Image *) png_get_error_ptr(ping); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s error: %s", PNG_LIBPNG_VER_STRING,message); (void) ThrowMagickException(&image->exception,GetMagickModule(),CoderError, message,"`%s'",image->filename); #if (PNG_LIBPNG_VER < 10500) /* A warning about deprecated use of jmpbuf here is unavoidable if you * are building with libpng-1.4.x and can be ignored. */ longjmp(ping->jmpbuf,1); #else png_longjmp(ping,1); #endif } static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message) { Image *image; if (LocaleCompare(message, "Missing PLTE before tRNS") == 0) png_error(ping, message); image=(Image *) png_get_error_ptr(ping); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s warning: %s", PNG_LIBPNG_VER_STRING,message); (void) ThrowMagickException(&image->exception,GetMagickModule(),CoderWarning, message,"`%s'",image->filename); } #ifdef PNG_USER_MEM_SUPPORTED #if PNG_LIBPNG_VER >= 10400 static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size) #else static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size) #endif { (void) png_ptr; return((png_voidp) AcquireMagickMemory((size_t) size)); } /* Free a pointer. It is removed from the list at the same time. */ static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr) { (void) png_ptr; ptr=RelinquishMagickMemory(ptr); return((png_free_ptr) NULL); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static int Magick_png_read_raw_profile(png_struct *ping,Image *image, const ImageInfo *image_info, png_textp text,int ii) { register ssize_t i; register unsigned char *dp; register png_charp sp; png_uint_32 length, nibbles; StringInfo *profile; const unsigned char unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12, 13,14,15}; sp=text[ii].text+1; /* look for newline */ while (*sp != '\n') sp++; /* look for length */ while (*sp == '\0' || *sp == ' ' || *sp == '\n') sp++; length=(png_uint_32) StringToLong(sp); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu",(unsigned long) length); while (*sp != ' ' && *sp != '\n') sp++; /* allocate space */ if (length == 0) { png_warning(ping,"invalid profile length"); return(MagickFalse); } profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { png_warning(ping, "unable to copy profile"); return(MagickFalse); } /* copy profile, skipping white space and column 1 "=" signs */ dp=GetStringInfoDatum(profile); nibbles=length*2; for (i=0; i < (ssize_t) nibbles; i++) { while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f') { if (*sp == '\0') { png_warning(ping, "ran out of profile data"); return(MagickFalse); } sp++; } if (i%2 == 0) *dp=(unsigned char) (16*unhex[(int) *sp++]); else (*dp++)+=unhex[(int) *sp++]; } /* We have already read "Raw profile type. */ (void) SetImageProfile(image,&text[ii].key[17],profile); profile=DestroyStringInfo(profile); if (image_info->verbose) (void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]); return MagickTrue; } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk) { Image *image; /* The unknown chunk structure contains the chunk data: png_byte name[5]; png_byte *data; png_size_t size; Note that libpng has already taken care of the CRC handling. */ LogMagickEvent(CoderEvent,GetMagickModule(), " read_user_chunk: found %c%c%c%c chunk", chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]); if (chunk->name[0] == 101 && (chunk->name[1] == 88 || chunk->name[1] == 120 ) && chunk->name[2] == 73 && chunk-> name[3] == 102) { /* process eXIf or exIf chunk */ PNGErrorInfo *error_info; StringInfo *profile; unsigned char *p; png_byte *s; int i; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " recognized eXIf|exIf chunk"); image=(Image *) png_get_user_chunk_ptr(ping); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); profile=BlobToStringInfo((const void *) NULL,chunk->size+6); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(error_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1); } p=GetStringInfoDatum(profile); /* Initialize profile with "Exif\0\0" */ *p++ ='E'; *p++ ='x'; *p++ ='i'; *p++ ='f'; *p++ ='\0'; *p++ ='\0'; /* copy chunk->data to profile */ s=chunk->data; for (i=0; i < (ssize_t) chunk->size; i++) *p++ = *s++; (void) SetImageProfile(image,"exif",profile); return(1); } /* vpAg (deprecated, replaced by caNv) */ if (chunk->name[0] == 118 && chunk->name[1] == 112 && chunk->name[2] == 65 && chunk->name[3] == 103) { /* recognized vpAg */ if (chunk->size != 9) return(-1); /* Error return */ if (chunk->data[8] != 0) return(0); /* ImageMagick requires pixel units */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); return(1); } /* caNv */ if (chunk->name[0] == 99 && chunk->name[1] == 97 && chunk->name[2] == 78 && chunk->name[3] == 118) { /* recognized caNv */ if (chunk->size != 16) return(-1); /* Error return */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); image->page.x=(size_t) ((chunk->data[8] << 24) | (chunk->data[9] << 16) | (chunk->data[10] << 8) | chunk->data[11]); image->page.y=(size_t) ((chunk->data[12] << 24) | (chunk->data[13] << 16) | (chunk->data[14] << 8) | chunk->data[15]); /* Return one of the following: */ /* return(-n); chunk had an error */ /* return(0); did not recognize */ /* return(n); success */ return(1); } return(0); /* Did not recognize */ } #endif #if defined(PNG_tIME_SUPPORTED) static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info) { png_timep time; if (png_get_tIME(ping,info,&time)) { char timestamp[21]; FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ", time->year,time->month,time->day,time->hour,time->minute,time->second); SetImageProperty(image,"png:tIME",timestamp); } } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the ReadOnePNGImage method is: % % Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { /* Read one PNG image */ /* To do: Read the tEXt/Creation Time chunk into the date:create property */ Image *image; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; int intent, /* "PNG Rendering intent", which is ICC intent + 1 */ num_raw_profiles, num_text, num_text_total, num_passes, number_colors, pass, ping_bit_depth, ping_color_type, ping_file_depth, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans, unit_type; double file_gamma; LongPixelPacket transparent_color; MagickBooleanType logging, ping_found_cHRM, ping_found_gAMA, ping_found_iCCP, ping_found_sRGB, ping_found_sRGB_cHRM, ping_preserve_iCCP, status; MemoryInfo *volatile pixel_info; png_bytep ping_trans_alpha; png_color_16p ping_background, ping_trans_color; png_info *end_info, *ping_info; png_struct *ping; png_textp text; png_uint_32 ping_height, ping_width, x_resolution, y_resolution; ssize_t ping_rowbytes, y; register unsigned char *p; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; size_t length, row_offset; ssize_t j; unsigned char *ping_pixels; #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED png_byte unused_chunks[]= { 104, 73, 83, 84, (png_byte) '\0', /* hIST */ 105, 84, 88, 116, (png_byte) '\0', /* iTXt */ 112, 67, 65, 76, (png_byte) '\0', /* pCAL */ 115, 67, 65, 76, (png_byte) '\0', /* sCAL */ 115, 80, 76, 84, (png_byte) '\0', /* sPLT */ #if !defined(PNG_tIME_SUPPORTED) 116, 73, 77, 69, (png_byte) '\0', /* tIME */ #endif #ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */ /* ignore the APNG chunks */ 97, 99, 84, 76, (png_byte) '\0', /* acTL */ 102, 99, 84, 76, (png_byte) '\0', /* fcTL */ 102, 100, 65, 84, (png_byte) '\0', /* fdAT */ #endif }; #endif /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,32); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,32); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOnePNGImage()\n" " IM version = %s\n" " Libpng version = %s", im_vers, libpng_vers); if (logging != MagickFalse) { if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif #if (PNG_LIBPNG_VER >= 10400) # ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */ if (image_info->verbose) { printf("Your PNG library (libpng-%s) is an old beta version.\n", PNG_LIBPNG_VER_STRING); printf("Please update it.\n"); } # endif #endif image=mng_info->image; if (logging != MagickFalse) { (void)LogMagickEvent(CoderEvent,GetMagickModule(), " Before reading:\n" " image->matte=%d\n" " image->rendering_intent=%d\n" " image->colorspace=%d\n" " image->gamma=%f", (int) image->matte, (int) image->rendering_intent, (int) image->colorspace, image->gamma); } intent=Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent); /* Set to an out-of-range color unless tRNS chunk is present */ transparent_color.red=65537; transparent_color.green=65537; transparent_color.blue=65537; transparent_color.opacity=65537; number_colors=0; num_text = 0; num_text_total = 0; num_raw_profiles = 0; ping_found_cHRM = MagickFalse; ping_found_gAMA = MagickFalse; ping_found_iCCP = MagickFalse; ping_found_sRGB = MagickFalse; ping_found_sRGB_cHRM = MagickFalse; ping_preserve_iCCP = MagickFalse; /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING, image, MagickPNGErrorHandler,MagickPNGWarningHandler, NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } end_info=png_create_info_struct(ping); if (end_info == (png_info *) NULL) { png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG image is corrupt. */ png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() with error."); if (image != (Image *) NULL) InheritException(exception,&image->exception); return(GetFirstImageInList(image)); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for reading. */ mng_info->image_found++; png_set_sig_bytes(ping,8); if (LocaleCompare(image_info->magick,"MNG") == 0) { #if defined(PNG_MNG_FEATURES_SUPPORTED) (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); png_set_read_fn(ping,image,png_get_data); #else #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) png_permit_empty_plte(ping,MagickTrue); png_set_read_fn(ping,image,png_get_data); #else mng_info->image=image; mng_info->bytes_in_read_buffer=0; mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; png_set_read_fn(ping,mng_info,mng_get_data); #endif #endif } else png_set_read_fn(ping,image,png_get_data); { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",value) == MagickFalse) { value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) ping_preserve_iCCP=MagickTrue; #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) /* Don't let libpng check for ICC/sRGB profile because we're going * to do that anyway. This feature was added at libpng-1.6.12. * If logging, go ahead and check and issue a warning as appropriate. */ if (logging == MagickFalse) png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) else { /* Ignore the iCCP chunk */ png_set_keep_unknown_chunks(ping, 1, mng_iCCP, 1); } #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* Ignore unused chunks and all unknown chunks except for exIf, caNv, and vpAg */ # if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */ png_set_keep_unknown_chunks(ping, 2, NULL, 0); # else png_set_keep_unknown_chunks(ping, 1, NULL, 0); # endif png_set_keep_unknown_chunks(ping, 2, mng_exIf, 1); png_set_keep_unknown_chunks(ping, 2, mng_caNv, 1); png_set_keep_unknown_chunks(ping, 2, mng_vpAg, 1); png_set_keep_unknown_chunks(ping, 1, unused_chunks, (int)sizeof(unused_chunks)/5); /* Callback for other unknown chunks */ png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED #if (PNG_LIBPNG_VER >= 10400) /* Limit the size of the chunk storage cache used for sPLT, text, * and unknown chunks. */ png_set_chunk_cache_max(ping, 32767); #endif #endif #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature */ png_set_check_for_invalid_index (ping, 0); #endif #if (PNG_LIBPNG_VER < 10400) # if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \ (PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__) /* Disable thread-unsafe features of pnggccrd */ if (png_access_version_number() >= 10200) { png_uint_32 mmx_disable_mask=0; png_uint_32 asm_flags; mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \ | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \ | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \ | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ); asm_flags=png_get_asm_flags(ping); png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask); } # endif #endif png_read_info(ping,ping_info); /* Read and check IHDR chunk data */ png_get_IHDR(ping,ping_info,&ping_width,&ping_height, &ping_bit_depth,&ping_color_type, &ping_interlace_method,&ping_compression_method, &ping_filter_method); ping_file_depth = ping_bit_depth; /* Swap bytes if requested */ if (ping_file_depth == 16) { const char *value; value=GetImageOption(image_info,"png:swap-bytes"); if (value == NULL) value=GetImageArtifact(image,"png:swap-bytes"); if (value != NULL) png_set_swap(ping); } /* Save bit-depth and color-type in case we later want to write a PNG00 */ { char msg[MaxTextExtent]; (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_color_type); (void) SetImageProperty(image,"png:IHDR.color-type-orig",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_bit_depth); (void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg); } (void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans, &ping_trans_color); (void) png_get_bKGD(ping, ping_info, &ping_background); if (ping_bit_depth < 8) { png_set_packing(ping); ping_bit_depth = 8; } image->depth=ping_bit_depth; image->depth=GetImageQuantumDepth(image,MagickFalse); image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { image->rendering_intent=UndefinedIntent; intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent); (void) ResetMagickMemory(&image->chromaticity,0, sizeof(image->chromaticity)); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG width: %.20g, height: %.20g\n" " PNG color_type: %d, bit_depth: %d\n" " PNG compression_method: %d\n" " PNG interlace_method: %d, filter_method: %d", (double) ping_width, (double) ping_height, ping_color_type, ping_bit_depth, ping_compression_method, ping_interlace_method,ping_filter_method); } if (png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_gAMA)) { ping_found_gAMA=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG gAMA chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { ping_found_cHRM=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG cHRM chunk."); } if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { ping_found_sRGB=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG sRGB chunk."); } #ifdef PNG_READ_iCCP_SUPPORTED if (ping_found_iCCP !=MagickTrue && ping_found_sRGB != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_iCCP)) { int compression; #if (PNG_LIBPNG_VER < 10500) png_charp info; #else png_bytep info; #endif png_charp name; png_uint_32 profile_length; (void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info, &profile_length); if (profile_length != 0) { StringInfo *profile; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG iCCP chunk."); profile=BlobToStringInfo(info,profile_length); if (profile == (StringInfo *) NULL) { png_warning(ping, "ICC profile is NULL"); profile=DestroyStringInfo(profile); } else { if (ping_preserve_iCCP == MagickFalse) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } break; } } } if (sRGB_info[icheck].len == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); (void) SetImageProfile(image,"icc",profile); } } else /* Preserve-iCCP */ { (void) SetImageProfile(image,"icc",profile); } profile=DestroyStringInfo(profile); } } } #endif #if defined(PNG_READ_sRGB_SUPPORTED) { if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { if (png_get_sRGB(ping,ping_info,&intent)) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (intent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG sRGB chunk: rendering_intent: %d",intent); } } else if (mng_info->have_global_srgb) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (mng_info->global_srgb_intent); } } #endif { if (!png_get_gAMA(ping,ping_info,&file_gamma)) if (mng_info->have_global_gama) png_set_gAMA(ping,ping_info,mng_info->global_gamma); if (png_get_gAMA(ping,ping_info,&file_gamma)) { image->gamma=(float) file_gamma; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG gAMA chunk: gamma: %f",file_gamma); } } if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { if (mng_info->have_global_chrm != MagickFalse) { (void) png_set_cHRM(ping,ping_info, mng_info->global_chrm.white_point.x, mng_info->global_chrm.white_point.y, mng_info->global_chrm.red_primary.x, mng_info->global_chrm.red_primary.y, mng_info->global_chrm.green_primary.x, mng_info->global_chrm.green_primary.y, mng_info->global_chrm.blue_primary.x, mng_info->global_chrm.blue_primary.y); } } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { (void) png_get_cHRM(ping,ping_info, &image->chromaticity.white_point.x, &image->chromaticity.white_point.y, &image->chromaticity.red_primary.x, &image->chromaticity.red_primary.y, &image->chromaticity.green_primary.x, &image->chromaticity.green_primary.y, &image->chromaticity.blue_primary.x, &image->chromaticity.blue_primary.y); ping_found_cHRM=MagickTrue; if (image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f) ping_found_sRGB_cHRM=MagickTrue; } if (image->rendering_intent != UndefinedIntent) { if (ping_found_sRGB != MagickTrue && (ping_found_gAMA != MagickTrue || (image->gamma > .45 && image->gamma < .46)) && (ping_found_cHRM != MagickTrue || ping_found_sRGB_cHRM != MagickFalse) && ping_found_iCCP != MagickTrue) { png_set_sRGB(ping,ping_info, Magick_RenderingIntent_to_PNG_RenderingIntent (image->rendering_intent)); file_gamma=1.000f/2.200f; ping_found_sRGB=MagickTrue; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting sRGB as if in input"); } } #if defined(PNG_oFFs_SUPPORTED) if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info); image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info); if (logging != MagickFalse) if (image->page.x || image->page.y) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double) image->page.x,(double) image->page.y); } #endif #if defined(PNG_pHYs_SUPPORTED) if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { if (mng_info->have_global_phys) { png_set_pHYs(ping,ping_info, mng_info->global_x_pixels_per_unit, mng_info->global_y_pixels_per_unit, mng_info->global_phys_unit_type); } } x_resolution=0; y_resolution=0; unit_type=0; if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { /* Set image resolution. */ (void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution, &unit_type); image->x_resolution=(double) x_resolution; image->y_resolution=(double) y_resolution; if (unit_type == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=(double) x_resolution/100.0; image->y_resolution=(double) y_resolution/100.0; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) x_resolution,(double) y_resolution,unit_type); } #endif if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); if ((number_colors == 0) && ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)) { if (mng_info->global_plte_length) { png_set_PLTE(ping,ping_info,mng_info->global_plte, (int) mng_info->global_plte_length); if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS)) if (mng_info->global_trns_length) { if (mng_info->global_trns_length > mng_info->global_plte_length) { png_warning(ping, "global tRNS has more entries than global PLTE"); } else { png_set_tRNS(ping,ping_info,mng_info->global_trns, (int) mng_info->global_trns_length,NULL); } } #ifdef PNG_READ_bKGD_SUPPORTED if ( #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED mng_info->have_saved_bkgd_index || #endif png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { png_color_16 background; #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED if (mng_info->have_saved_bkgd_index) background.index=mng_info->saved_bkgd_index; #endif if (png_get_valid(ping, ping_info, PNG_INFO_bKGD)) background.index=ping_background->index; background.red=(png_uint_16) mng_info->global_plte[background.index].red; background.green=(png_uint_16) mng_info->global_plte[background.index].green; background.blue=(png_uint_16) mng_info->global_plte[background.index].blue; background.gray=(png_uint_16) mng_info->global_plte[background.index].green; png_set_bKGD(ping,ping_info,&background); } #endif } else png_error(ping,"No global PLTE in file"); } } #ifdef PNG_READ_bKGD_SUPPORTED if (mng_info->have_global_bkgd && (!png_get_valid(ping,ping_info,PNG_INFO_bKGD))) image->background_color=mng_info->mng_global_bkgd; if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { unsigned int bkgd_scale; /* Set image background color. * Scale background components to 16-bit, then scale * to quantum depth */ bkgd_scale = 1; if (ping_file_depth == 1) bkgd_scale = 255; else if (ping_file_depth == 2) bkgd_scale = 85; else if (ping_file_depth == 4) bkgd_scale = 17; if (ping_file_depth <= 8) bkgd_scale *= 257; ping_background->red *= bkgd_scale; ping_background->green *= bkgd_scale; ping_background->blue *= bkgd_scale; if (logging != MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d).\n" " bkgd_scale=%d. ping_background=(%d,%d,%d).", ping_background->red,ping_background->green, ping_background->blue, bkgd_scale,ping_background->red, ping_background->green,ping_background->blue); } image->background_color.red= ScaleShortToQuantum(ping_background->red); image->background_color.green= ScaleShortToQuantum(ping_background->green); image->background_color.blue= ScaleShortToQuantum(ping_background->blue); image->background_color.opacity=OpaqueOpacity; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->background_color=(%.20g,%.20g,%.20g).", (double) image->background_color.red, (double) image->background_color.green, (double) image->background_color.blue); } #endif /* PNG_READ_bKGD_SUPPORTED */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { /* Image has a tRNS chunk. */ int max_sample; size_t one=1; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG tRNS chunk."); max_sample = (int) ((one << ping_file_depth) - 1); if ((ping_color_type == PNG_COLOR_TYPE_GRAY && (int)ping_trans_color->gray > max_sample) || (ping_color_type == PNG_COLOR_TYPE_RGB && ((int)ping_trans_color->red > max_sample || (int)ping_trans_color->green > max_sample || (int)ping_trans_color->blue > max_sample))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Ignoring PNG tRNS chunk with out-of-range sample."); png_free_data(ping, ping_info, PNG_FREE_TRNS, 0); png_set_invalid(ping,ping_info,PNG_INFO_tRNS); image->matte=MagickFalse; } else { int scale_to_short; scale_to_short = 65535L/((1UL << ping_file_depth)-1); /* Scale transparent_color to short */ transparent_color.red= scale_to_short*ping_trans_color->red; transparent_color.green= scale_to_short*ping_trans_color->green; transparent_color.blue= scale_to_short*ping_trans_color->blue; transparent_color.opacity= scale_to_short*ping_trans_color->gray; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Raw tRNS graylevel = %d, scaled graylevel = %d.", ping_trans_color->gray,transparent_color.opacity); } transparent_color.red=transparent_color.opacity; transparent_color.green=transparent_color.opacity; transparent_color.blue=transparent_color.opacity; } } } #if defined(PNG_READ_sBIT_SUPPORTED) if (mng_info->have_global_sbit) { if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT)) png_set_sBIT(ping,ping_info,&mng_info->global_sbit); } #endif num_passes=png_set_interlace_handling(ping); png_read_update_info(ping,ping_info); ping_rowbytes=png_get_rowbytes(ping,ping_info); /* Initialize image structure. */ mng_info->image_box.left=0; mng_info->image_box.right=(ssize_t) ping_width; mng_info->image_box.top=0; mng_info->image_box.bottom=(ssize_t) ping_height; if (mng_info->mng_type == 0) { mng_info->mng_width=ping_width; mng_info->mng_height=ping_height; mng_info->frame=mng_info->image_box; mng_info->clip=mng_info->image_box; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } image->compression=ZipCompression; image->columns=ping_width; image->rows=ping_height; if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || ((int) ping_bit_depth < 16 && (int) ping_color_type == PNG_COLOR_TYPE_GRAY)) { size_t one; image->storage_class=PseudoClass; one=1; image->colors=one << ping_file_depth; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->colors > 256) image->colors=256; #else if (image->colors > 65536L) image->colors=65536L; #endif if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); image->colors=(size_t) number_colors; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG PLTE chunk: number_colors: %d.",number_colors); } } if (image->storage_class == PseudoClass) { /* Initialize image colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) png_error(ping,"Memory allocation failed"); if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); for (i=0; i < (ssize_t) number_colors; i++) { image->colormap[i].red=ScaleCharToQuantum(palette[i].red); image->colormap[i].green=ScaleCharToQuantum(palette[i].green); image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue); } for ( ; i < (ssize_t) image->colors; i++) { image->colormap[i].red=0; image->colormap[i].green=0; image->colormap[i].blue=0; } } else { Quantum scale; scale = 65535/((1UL << ping_file_depth)-1); #if (MAGICKCORE_QUANTUM_DEPTH > 16) scale = ScaleShortToQuantum(scale); #endif for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(Quantum) (i*scale); image->colormap[i].green=(Quantum) (i*scale); image->colormap[i].blue=(Quantum) (i*scale); } } } /* Set some properties for reporting by "identify" */ { char msg[MaxTextExtent]; /* encode ping_width, ping_height, ping_file_depth, ping_color_type, ping_interlace_method in value */ (void) FormatLocaleString(msg,MaxTextExtent, "%d, %d",(int) ping_width, (int) ping_height); (void) SetImageProperty(image,"png:IHDR.width,height",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_file_depth); (void) SetImageProperty(image,"png:IHDR.bit_depth",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d (%s)", (int) ping_color_type, Magick_ColorType_from_PNG_ColorType((int)ping_color_type)); (void) SetImageProperty(image,"png:IHDR.color_type",msg); if (ping_interlace_method == 0) { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Not interlaced)", (int) ping_interlace_method); } else if (ping_interlace_method == 1) { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Adam7 method)", (int) ping_interlace_method); } else { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Unknown method)", (int) ping_interlace_method); } (void) SetImageProperty(image,"png:IHDR.interlace_method",msg); if (number_colors != 0) { (void) FormatLocaleString(msg,MaxTextExtent,"%d", (int) number_colors); (void) SetImageProperty(image,"png:PLTE.number_colors",msg); } } #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,ping_info); #endif /* Read image scanlines. */ if (image->delay != 0) mng_info->scenes_found++; if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || ( (image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)))) { /* This happens later in non-ping decodes */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) image->storage_class=DirectClass; image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping PNG image data for scene %.20g",(double) mng_info->scenes_found-1); png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()."); return(image); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG IDAT chunk(s)"); if (num_passes > 1) pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes* sizeof(*ping_pixels)); else pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Memory allocation failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting PNG pixels to pixel packets"); /* Convert PNG pixels to pixel packets. */ { MagickBooleanType found_transparent_pixel; found_transparent_pixel=MagickFalse; if (image->storage_class == DirectClass) { QuantumInfo *quantum_info; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Failed to allocate quantum_info"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (pass=0; pass < num_passes; pass++) { /* Convert image to DirectClass pixel packets. */ image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; for (y=0; y < (ssize_t) image->rows; y++) { if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; else { if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayAlphaQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBAQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, IndexQuantum,ping_pixels+row_offset,exception); else /* ping_color_type == PNG_COLOR_TYPE_RGB */ (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBQuantum,ping_pixels+row_offset,exception); } if (found_transparent_pixel == MagickFalse) { /* Is there a transparent pixel in the row? */ if (y== 0 && logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Looking for cheap transparent pixel"); for (x=(ssize_t) image->columns-1; x >= 0; x--) { if ((ping_color_type == PNG_COLOR_TYPE_RGBA || ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) && (GetPixelOpacity(q) != OpaqueOpacity)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } if ((ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_GRAY) && (ScaleQuantumToShort(GetPixelRed(q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(q)) == transparent_color.blue)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } q++; } } if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag, (MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); } else /* image->storage_class != DirectClass */ for (pass=0; pass < num_passes; pass++) { Quantum *quantum_scanline; register Quantum *r; /* Convert grayscale image to PseudoClass pixel packets. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting grayscale pixels to pixel packets"); image->matte=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ? MagickTrue : MagickFalse; quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns, (image->matte ? 2 : 1)*sizeof(*quantum_scanline)); if (quantum_scanline == (Quantum *) NULL) png_error(ping,"Memory allocation failed"); for (y=0; y < (ssize_t) image->rows; y++) { Quantum alpha; if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=ping_pixels+row_offset; r=quantum_scanline; switch (ping_bit_depth) { case 8: { if (ping_color_type == 4) for (x=(ssize_t) image->columns-1; x >= 0; x--) { *r++=*p++; /* In image.h, OpaqueOpacity is 0 * TransparentOpacity is QuantumRange * In a PNG datastream, Opaque is QuantumRange * and Transparent is 0. */ alpha=ScaleCharToQuantum((unsigned char)*p++); SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; q++; } else for (x=(ssize_t) image->columns-1; x >= 0; x--) *r++=*p++; break; } case 16: { for (x=(ssize_t) image->columns-1; x >= 0; x--) { #if (MAGICKCORE_QUANTUM_DEPTH >= 16) size_t quantum; if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); *r=ScaleShortToQuantum(quantum); r++; if (ping_color_type == 4) { if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); alpha=ScaleShortToQuantum(quantum); SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; q++; } #else /* MAGICKCORE_QUANTUM_DEPTH == 8 */ *r++=(*p++); p++; /* strip low byte */ if (ping_color_type == 4) { alpha=*p++; SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; p++; q++; } #endif } break; } default: break; } /* Transfer image scanline. */ r=quantum_scanline; for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*r++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline); } image->matte=found_transparent_pixel; if (logging != MagickFalse) { if (found_transparent_pixel != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found transparent pixel"); else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No transparent pixel was found"); ping_color_type&=0x03; } } } if (image->storage_class == PseudoClass) { MagickBooleanType matte; matte=image->matte; image->matte=MagickFalse; (void) SyncImage(image); image->matte=matte; } png_read_end(ping,end_info); if (image_info->number_scenes != 0 && mng_info->scenes_found-1 < (ssize_t) image_info->first_scene && image->delay != 0) { png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); image->colors=2; (void) SetImageBackgroundColor(image); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() early."); return(image); } if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { ClassType storage_class; /* Image has a transparent background. */ storage_class=image->storage_class; image->matte=MagickTrue; /* Balfour fix from imagemagick discourse server, 5 Feb 2010 */ if (storage_class == PseudoClass) { if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { for (x=0; x < ping_num_trans; x++) { image->colormap[x].opacity = ScaleCharToQuantum((unsigned char)(255-ping_trans_alpha[x])); } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY) { for (x=0; x < (int) image->colors; x++) { if (ScaleQuantumToShort(image->colormap[x].red) == transparent_color.opacity) { image->colormap[x].opacity = (Quantum) TransparentOpacity; } } } (void) SyncImage(image); } #if 1 /* Should have already been done above, but glennrp problem P10 * needs this. */ else { for (y=0; y < (ssize_t) image->rows; y++) { image->storage_class=storage_class; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); /* Caution: on a Q8 build, this does not distinguish between * 16-bit colors that differ only in the low byte */ for (x=(ssize_t) image->columns-1; x >= 0; x--) { if (ScaleQuantumToShort(GetPixelRed(q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(q)) == transparent_color.blue) { SetPixelOpacity(q,TransparentOpacity); } #if 0 /* I have not found a case where this is needed. */ else { SetPixelOpacity(q)=(Quantum) OpaqueOpacity; } #endif q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif image->storage_class=DirectClass; } if ((ping_color_type == PNG_COLOR_TYPE_GRAY) || (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { double image_gamma = image->gamma; (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%f",(float) image_gamma); if (image_gamma > 0.75) { /* Set image->rendering_intent to Undefined, * image->colorspace to GRAY, and reset image->chromaticity. */ image->intensity = Rec709LuminancePixelIntensityMethod; SetImageColorspace(image,GRAYColorspace); } else { RenderingIntent save_rendering_intent = image->rendering_intent; ChromaticityInfo save_chromaticity = image->chromaticity; SetImageColorspace(image,GRAYColorspace); image->rendering_intent = save_rendering_intent; image->chromaticity = save_chromaticity; } image->gamma = image_gamma; } (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace=%d",(int) image->colorspace); for (j = 0; j < 2; j++) { if (j == 0) status = png_get_text(ping,ping_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; else status = png_get_text(ping,end_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) for (i=0; i < (ssize_t) num_text; i++) { /* Check for a profile */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG text chunk"); if (strlen(text[i].key) > 16 && memcmp(text[i].key, "Raw profile type ",17) == 0) { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember(text[i].key+17,value) == MagickFalse) { (void) Magick_png_read_raw_profile(ping,image,image_info,text, (int) i); num_raw_profiles++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Read raw profile %s",text[i].key+17); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping raw profile %s",text[i].key+17); } } else { char *value; length=text[i].text_length; value=(char *) AcquireQuantumMemory(length+MaxTextExtent, sizeof(*value)); if (value == (char *) NULL) png_error(ping,"Memory allocation failed"); *value='\0'; (void) ConcatenateMagickString(value,text[i].text,length+2); /* Don't save "density" or "units" property if we have a pHYs * chunk */ if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) || (LocaleCompare(text[i].key,"density") != 0 && LocaleCompare(text[i].key,"units") != 0)) (void) SetImageProperty(image,text[i].key,value); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu\n" " Keyword: %s", (unsigned long) length, text[i].key); } value=DestroyString(value); } } num_text_total += num_text; } #ifdef MNG_OBJECT_BUFFERS /* Store the object if necessary. */ if (object_id && !mng_info->frozen[object_id]) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) { /* create a new object buffer. */ mng_info->ob[object_id]=(MngBuffer *) AcquireMagickMemory(sizeof(MngBuffer)); if (mng_info->ob[object_id] != (MngBuffer *) NULL) { mng_info->ob[object_id]->image=(Image *) NULL; mng_info->ob[object_id]->reference_count=1; } } if ((mng_info->ob[object_id] == (MngBuffer *) NULL) || mng_info->ob[object_id]->frozen) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) png_error(ping,"Memory allocation failed"); if (mng_info->ob[object_id]->frozen) png_error(ping,"Cannot overwrite frozen MNG object buffer"); } else { if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image=DestroyImage (mng_info->ob[object_id]->image); mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue, &image->exception); if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image->file=(FILE *) NULL; else png_error(ping, "Cloning image for object buffer failed"); if (ping_width > 250000L || ping_height > 250000L) png_error(ping,"PNG Image dimensions are too large."); mng_info->ob[object_id]->width=ping_width; mng_info->ob[object_id]->height=ping_height; mng_info->ob[object_id]->color_type=ping_color_type; mng_info->ob[object_id]->sample_depth=ping_bit_depth; mng_info->ob[object_id]->interlace_method=ping_interlace_method; mng_info->ob[object_id]->compression_method= ping_compression_method; mng_info->ob[object_id]->filter_method=ping_filter_method; if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp plte; /* Copy the PLTE to the object buffer. */ png_get_PLTE(ping,ping_info,&plte,&number_colors); mng_info->ob[object_id]->plte_length=number_colors; for (i=0; i < number_colors; i++) { mng_info->ob[object_id]->plte[i]=plte[i]; } } else mng_info->ob[object_id]->plte_length=0; } } #endif /* Set image->matte to MagickTrue if the input colortype supports * alpha or if a valid tRNS chunk is present, no matter whether there * is actual transparency present. */ image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; #if 0 /* I'm not sure what's wrong here but it does not work. */ if (image->matte != MagickFalse) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) SetImageType(image,GrayscaleMatteType); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteMatteType); else (void) SetImageType(image,TrueColorMatteType); } else { if (ping_color_type == PNG_COLOR_TYPE_GRAY) (void) SetImageType(image,GrayscaleType); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteType); else (void) SetImageType(image,TrueColorType); } #endif /* Set more properties for identify to retrieve */ { char msg[MaxTextExtent]; if (num_text_total != 0) { /* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */ (void) FormatLocaleString(msg,MaxTextExtent, "%d tEXt/zTXt/iTXt chunks were found", num_text_total); (void) SetImageProperty(image,"png:text",msg); } if (num_raw_profiles != 0) { (void) FormatLocaleString(msg,MaxTextExtent, "%d were found", num_raw_profiles); (void) SetImageProperty(image,"png:text-encoded profiles",msg); } /* cHRM chunk: */ if (ping_found_cHRM != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found (see Chromaticity, above)"); (void) SetImageProperty(image,"png:cHRM",msg); } /* bKGD chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found (see Background color, above)"); (void) SetImageProperty(image,"png:bKGD",msg); } (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found"); /* iCCP chunk: */ if (ping_found_iCCP != MagickFalse) (void) SetImageProperty(image,"png:iCCP",msg); if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) (void) SetImageProperty(image,"png:tRNS",msg); #if defined(PNG_sRGB_SUPPORTED) /* sRGB chunk: */ if (ping_found_sRGB != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent, "intent=%d (%s)", (int) intent, Magick_RenderingIntentString_from_PNG_RenderingIntent(intent)); (void) SetImageProperty(image,"png:sRGB",msg); } #endif /* gAMA chunk: */ if (ping_found_gAMA != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent, "gamma=%.8g (See Gamma, above)", file_gamma); (void) SetImageProperty(image,"png:gAMA",msg); } #if defined(PNG_pHYs_SUPPORTED) /* pHYs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { (void) FormatLocaleString(msg,MaxTextExtent, "x_res=%.10g, y_res=%.10g, units=%d", (double) x_resolution,(double) y_resolution, unit_type); (void) SetImageProperty(image,"png:pHYs",msg); } #endif #if defined(PNG_oFFs_SUPPORTED) /* oFFs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { (void) FormatLocaleString(msg,MaxTextExtent,"x_off=%.20g, y_off=%.20g", (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:oFFs",msg); } #endif #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,end_info); #endif /* caNv chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || (image->page.x != 0 || image->page.y != 0)) { (void) FormatLocaleString(msg,MaxTextExtent, "width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:caNv",msg); } /* vpAg chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { (void) FormatLocaleString(msg,MaxTextExtent, "width=%.20g, height=%.20g", (double) image->page.width,(double) image->page.height); (void) SetImageProperty(image,"png:vpAg",msg); } } /* Relinquish resources. */ png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block, revert to * Throwing an Exception when an error occurs. */ return(image); /* end of reading one PNG image */ } static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; ssize_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) ThrowReaderException(FileOpenError,"UnableToOpenFile"); /* Verify PNG signature. */ count=ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a PNG datastream. */ if (GetBlobSize(image) < 61) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOnePNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if ((image->columns == 0) || (image->rows == 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if ((IssRGBColorspace(image->colorspace) != MagickFalse) && ((image->gamma < .45) || (image->gamma > .46)) && !(image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f)) SetImageColorspace(image,RGBColorspace); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()"); return(image); } #if defined(JNG_SUPPORTED) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadOneJNGImage method is: % % Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJNGImage() reads a JPEG Network Graphics (JNG) image file % (including the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadJNGImage method is: % % Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo % *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; size_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); if (LocaleCompare(image_info->magick,"JNG") != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify JNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a JNG datastream. */ if (GetBlobSize(image) < 147) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneJNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (image->columns == 0 || image->rows == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); ThrowReaderException(CorruptImageError,"CorruptImage"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()"); return(image); } #endif static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream", "`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, "object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters ", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage();"); return(image); } static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneMNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadMNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()"); return(GetFirstImageInList(image)); } #else /* PNG_LIBPNG_VER > 10011 */ static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "PNG library is too old","`%s'",image_info->filename); return(Image *) NULL; } static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { return(ReadPNGImage(image_info,exception)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNGImage() adds properties for the PNG image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNGImage method is: % % size_t RegisterPNGImage(void) % */ ModuleExport size_t RegisterPNGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char *PNGNote= { "See http://www.libpng.org/ for details about the PNG format." }, *JNGNote= { "See http://www.libpng.org/pub/mng/ for details about the JNG\n" "format." }, *MNGNote= { "See http://www.libpng.org/pub/mng/ for details about the MNG\n" "format." }; *version='\0'; #if defined(PNG_LIBPNG_VER_STRING) (void) ConcatenateMagickString(version,"libpng ",MaxTextExtent); (void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING,MaxTextExtent); if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0) { (void) ConcatenateMagickString(version,",",MaxTextExtent); (void) ConcatenateMagickString(version,png_get_libpng_ver(NULL), MaxTextExtent); } #endif entry=SetMagickInfo("MNG"); entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMNGImage; entry->encoder=(EncodeImageHandler *) WriteMNGImage; #endif entry->magick=(IsImageFormatHandler *) IsMNG; entry->description=ConstantString("Multiple-image Network Graphics"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("video/x-mng"); entry->module=ConstantString("PNG"); entry->note=ConstantString(MNGNote); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("Portable Network Graphics"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); if (*version != '\0') entry->version=ConstantString(version); entry->note=ConstantString(PNGNote); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG8"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString( "8-bit indexed with optional binary transparency"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG24"); *version='\0'; #if defined(ZLIB_VERSION) (void) ConcatenateMagickString(version,"zlib ",MaxTextExtent); (void) ConcatenateMagickString(version,ZLIB_VERSION,MaxTextExtent); if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0) { (void) ConcatenateMagickString(version,",",MaxTextExtent); (void) ConcatenateMagickString(version,zlib_version,MaxTextExtent); } #endif if (*version != '\0') entry->version=ConstantString(version); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or binary transparent 24-bit RGB"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG32"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or transparent 32-bit RGBA"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG48"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or binary transparent 48-bit RGB"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG64"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or transparent 64-bit RGBA"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG00"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString( "PNG inheriting bit-depth, color-type from original if possible"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JNG"); #if defined(JNG_SUPPORTED) #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJNGImage; entry->encoder=(EncodeImageHandler *) WriteJNGImage; #endif #endif entry->magick=(IsImageFormatHandler *) IsJNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("JPEG Network Graphics"); entry->mime_type=ConstantString("image/x-jng"); entry->module=ConstantString("PNG"); entry->note=ConstantString(JNGNote); (void) RegisterMagickInfo(entry); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE ping_semaphore=AllocateSemaphoreInfo(); #endif return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNGImage() removes format registrations made by the % PNG module from the list of supported formats. % % The format of the UnregisterPNGImage method is: % % UnregisterPNGImage(void) % */ ModuleExport void UnregisterPNGImage(void) { (void) UnregisterMagickInfo("MNG"); (void) UnregisterMagickInfo("PNG"); (void) UnregisterMagickInfo("PNG8"); (void) UnregisterMagickInfo("PNG24"); (void) UnregisterMagickInfo("PNG32"); (void) UnregisterMagickInfo("PNG48"); (void) UnregisterMagickInfo("PNG64"); (void) UnregisterMagickInfo("PNG00"); (void) UnregisterMagickInfo("JNG"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE if (ping_semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&ping_semaphore); #endif } #if defined(MAGICKCORE_PNG_DELEGATE) #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMNGImage() writes an image in the Portable Network Graphics % Group's "Multiple-image Network Graphics" encoded image format. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteMNGImage method is: % % MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % % To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also % "To do" under ReadPNGImage): % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % Write the iCCP chunk at MNG level when (icc profile length > 0) % % Improve selection of color type (use indexed-colour or indexed-colour % with tRNS when 256 or fewer unique RGBA values are present). % % Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3) % This will be complicated if we limit ourselves to generating MNG-LC % files. For now we ignore disposal method 3 and simply overlay the next % image on it. % % Check for identical PLTE's or PLTE/tRNS combinations and use a % global MNG PLTE or PLTE/tRNS combination when appropriate. % [mostly done 15 June 1999 but still need to take care of tRNS] % % Check for identical sRGB and replace with a global sRGB (and remove % gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and % replace with global gAMA/cHRM (or with sRGB if appropriate; replace % local gAMA/cHRM with local sRGB if appropriate). % % Check for identical sBIT chunks and write global ones. % % Provide option to skip writing the signature tEXt chunks. % % Use signatures to detect identical objects and reuse the first % instance of such objects instead of writing duplicate objects. % % Use a smaller-than-32k value of compression window size when % appropriate. % % Encode JNG datastreams. Mostly done as of 5.5.2; need to write % ancillary text chunks and save profiles. % % Provide an option to force LC files (to ensure exact framing rate) % instead of VLC. % % Provide an option to force VLC files instead of LC, even when offsets % are present. This will involve expanding the embedded images with a % transparent region at the top and/or left. */ static void Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping, png_info *ping_info, unsigned char *profile_type, unsigned char *profile_description, unsigned char *profile_data, png_uint_32 length) { png_textp text; register ssize_t i; unsigned char *sp; png_charp dp; png_uint_32 allocated_length, description_length; unsigned char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0) return; if (image_info->verbose) { (void) printf("writing raw profile: type=%s, length=%.20g\n", (char *) profile_type, (double) length); } #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif description_length=(png_uint_32) strlen((const char *) profile_description); allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20 + description_length); #if PNG_LIBPNG_VER >= 10400 text[0].text=(png_charp) png_malloc(ping, (png_alloc_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80); #else text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80); #endif text[0].key[0]='\0'; (void) ConcatenateMagickString(text[0].key, "Raw profile type ",MaxTextExtent); (void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62); sp=profile_data; dp=text[0].text; *dp++='\n'; (void) CopyMagickString(dp,(const char *) profile_description, allocated_length); dp+=description_length; *dp++='\n'; (void) FormatLocaleString(dp,allocated_length- (png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length); dp+=8; for (i=0; i < (ssize_t) length; i++) { if (i%36 == 0) *dp++='\n'; *(dp++)=(char) hex[((*sp >> 4) & 0x0f)]; *(dp++)=(char) hex[((*sp++ ) & 0x0f)]; } *dp++='\n'; *dp='\0'; text[0].text_length=(png_size_t) (dp-text[0].text); text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? -1 : 0; if (text[0].text_length <= allocated_length) png_set_text(ping,ping_info,text,1); png_free(ping,text[0].text); png_free(ping,text[0].key); png_free(ping,text); } static MagickBooleanType Magick_png_write_chunk_from_profile(Image *image, const char *string, MagickBooleanType logging) { char *name; const StringInfo *profile; unsigned char *data; png_uint_32 length; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (const StringInfo *) NULL) { StringInfo *ping_profile; if (LocaleNCompare(name,string,11) == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found %s profile",name); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); data[4]=data[3]; data[3]=data[2]; data[2]=data[1]; data[1]=data[0]; (void) WriteBlobMSBULong(image,length-5); /* data length */ (void) WriteBlob(image,length-1,data+1); (void) WriteBlobMSBULong(image,crc32(0,data+1,(uInt) length-1)); ping_profile=DestroyStringInfo(ping_profile); } } name=GetNextImageProfile(image); } return(MagickTrue); } #if defined(PNG_tIME_SUPPORTED) static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info, const char *date) { unsigned int day, hour, minute, month, second, year; png_time ptime; time_t ttime; if (date != (const char *) NULL) { if (sscanf(date,"%d-%d-%dT%d:%d:%dZ",&year,&month,&day,&hour,&minute, &second) != 6) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError, "Invalid date format specified for png:tIME","`%s'", image->filename); return; } ptime.year=(png_uint_16) year; ptime.month=(png_byte) month; ptime.day=(png_byte) day; ptime.hour=(png_byte) hour; ptime.minute=(png_byte) minute; ptime.second=(png_byte) second; } else { time(&ttime); png_convert_from_time_t(&ptime,ttime); } png_set_tIME(ping,info,&ptime); } #endif /* Write one PNG image */ static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { char s[2]; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MaxTextExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MaxTextExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; /* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; */ ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_vpAg=mng_info->ping_exclude_vpAg; ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; property=(const char *) NULL; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->magick= %s",image_info->magick); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register PixelPacket *r; ExceptionInfo *exception; exception=(&image->exception); if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->matte == MagickFalse))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ number_opaque = (int) image->colors; if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; else ping_have_color=MagickTrue; ping_have_non_bw=MagickFalse; if (image->matte != MagickFalse) { number_transparent = 2; number_semitransparent = 1; } else { number_transparent = 0; number_semitransparent = 0; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->matte is MagickFalse, we ignore the opacity channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ ExceptionInfo *exception; int n; PixelPacket opaque[260], semitransparent[260], transparent[260]; register IndexPacket *indexes; register const PixelPacket *s, *q; register PixelPacket *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->matte=%.20g",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,opacity)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } exception=(&image->exception); image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte == MagickFalse || GetPixelOpacity(q) == OpaqueOpacity) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelRGB(q, opaque); opaque[0].opacity=OpaqueOpacity; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(q, opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelRGB(q, opaque+i); opaque[i].opacity=OpaqueOpacity; } } } else if (q->opacity == TransparentOpacity) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelRGBO(q, transparent); ping_trans_color.red= (unsigned short) GetPixelRed(q); ping_trans_color.green= (unsigned short) GetPixelGreen(q); ping_trans_color.blue= (unsigned short) GetPixelBlue(q); ping_trans_color.gray= (unsigned short) GetPixelRed(q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(q, transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelRGBO(q, transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelRGBO(q, semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(q, semitransparent+i) && GetPixelOpacity(q) == semitransparent[i].opacity) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelRGBO(q, semitransparent+i); } } } q++; } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != GetPixelGreen(s) || GetPixelRed(s) != GetPixelBlue(s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s++; } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != 0 && GetPixelRed(s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s++; } } } } } if (image_colors < 257) { PixelPacket colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors) == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->matte == MagickFalse || image->colormap[i].opacity == GetPixelOpacity(q)) && image->colormap[i].red == GetPixelRed(q) && image->colormap[i].green == GetPixelGreen(q) && image->colormap[i].blue == GetPixelBlue(q)) { SetPixelIndex(indexes+x,i); break; } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,opacity)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) > TransparentOpacity/2) { SetPixelOpacity(r,TransparentOpacity); SetPixelRgb(r,&image->background_color); } else SetPixelOpacity(r,OpaqueOpacity); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].opacity = (image->colormap[i].opacity > TransparentOpacity/2 ? TransparentOpacity : OpaqueOpacity); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR04PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR03PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR02PixelBlue(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(r)) == 0x00 && GetPixelOpacity(r) == OpaqueOpacity) { SetPixelRed(r,ScaleCharToQuantum(0x24)); } r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { ExceptionInfo *exception; register const PixelPacket *q; exception=(&image->exception); for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (q->opacity != TransparentOpacity && (unsigned short) GetPixelRed(q) == ping_trans_color.red && (unsigned short) GetPixelGreen(q) == ping_trans_color.green && (unsigned short) GetPixelBlue(q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q++; } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->matte; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",image->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->x_resolution != 0) && (image->y_resolution != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->x_resolution+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->y_resolution+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->x_resolution+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->y_resolution+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->x_resolution; ping_pHYs_y_resolution=(png_uint_32) image->y_resolution; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorMatteType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteMatteType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->matte == MagickFalse && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image, image->colormap))) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) (255- ScaleQuantumToChar(image->colormap[i].opacity)); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)*(ScaleQuantumToShort((Quantum) GetPixelLuma(image,&image->background_color)))+.5); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_background.index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_background.gray is %d", (int) ping_background.gray); } ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This is addressed by using "-define png:compression-strategy", etc., which takes precedence over -quality. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->matte == MagickFalse) { /* Add an opaque matte channel */ image->matte = MagickTrue; (void) SetImageOpacity(image,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { if (mng_info->have_write_global_plte && matte == MagickFalse) { png_set_PLTE(ping,ping_info,NULL,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up empty PLTE chunk"); } else png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(const png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } else #endif if (ping_exclude_zCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXT chunk with uuencoded ICC"); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk with %s profile",name); name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify"); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; (void) ping_have_blob; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } /* write any png-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging); png_write_info(ping,ping_info); /* write any PNG-chunk-m profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging); ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif /* write vpAg chunk (deprecated, replaced by caNv) */ if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { unsigned char chunk[14]; (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } } #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const PixelPacket *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,&image->exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",pass); p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write any PNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging); /* write exIf profile */ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); #if 0 /* eXIf chunk is registered */ PNGType(chunk,mng_eXIf); #else /* eXIf chunk not yet registered; write exIf instead */ PNGType(chunk,mng_exIf); #endif if (length < 7) break; /* othewise crashes */ /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data+6); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data+6, (uInt) length)); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(image,"png:bit-depth-written",s); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNGImage() writes a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WritePNGImage method is: % % MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % Returns MagickTrue on success, MagickFalse on failure. % % Communicating with the PNG encoder: % % While the datastream written is always in PNG format and normally would % be given the "png" file extension, this method also writes the following % pseudo-formats which are subsets of png: % % o PNG8: An 8-bit indexed PNG datastream is written. If the image has % a depth greater than 8, the depth is reduced. If transparency % is present, the tRNS chunk must only have values 0 and 255 % (i.e., transparency is binary: fully opaque or fully % transparent). If other values are present they will be % 50%-thresholded to binary transparency. If more than 256 % colors are present, they will be quantized to the 4-4-4-1, % 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color % of any resulting fully-transparent pixels is changed to % the image's background color. % % If you want better quantization or dithering of the colors % or alpha than that, you need to do it before calling the % PNG encoder. The pixels contain 8-bit indices even if % they could be represented with 1, 2, or 4 bits. Grayscale % images will be written as indexed PNG files even though the % PNG grayscale type might be slightly more efficient. Please % note that writing to the PNG8 format may result in loss % of color and alpha data. % % o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. The only loss incurred % is reduction of sample depth to 8. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG32: An 8-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 255. The alpha % channel is present even if the image is fully opaque. % The only loss in data is the reduction of the sample depth % to 8. % % o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG64: A 16-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 65535. The alpha % channel is present even if the image is fully opaque. % % o PNG00: A PNG that inherits its colortype and bit-depth from the input % image, if the input was a PNG, is written. If these values % cannot be found, or if the pixels have been changed in a way % that makes this impossible, then "PNG00" falls back to the % regular "PNG" format. % % o -define: For more precise control of the PNG output, you can use the % Image options "png:bit-depth" and "png:color-type". These % can be set from the commandline with "-define" and also % from the application programming interfaces. The options % are case-independent and are converted to lowercase before % being passed to this encoder. % % png:color-type can be 0, 2, 3, 4, or 6. % % When png:color-type is 0 (Grayscale), png:bit-depth can % be 1, 2, 4, 8, or 16. % % When png:color-type is 2 (RGB), png:bit-depth can % be 8 or 16. % % When png:color-type is 3 (Indexed), png:bit-depth can % be 1, 2, 4, or 8. This refers to the number of bits % used to store the index. The color samples always have % bit-depth 8 in indexed PNG files. % % When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte), % png:bit-depth can be 8 or 16. % % If the image cannot be written without loss with the % requested bit-depth and color-type, a PNG file will not % be written, a warning will be issued, and the encoder will % return MagickFalse. % % Since image encoders should not be responsible for the "heavy lifting", % the user should make sure that ImageMagick has already reduced the % image depth and number of colors and limit transparency to binary % transparency prior to attempting to write the image with depth, color, % or transparency limitations. % % To do: Enforce the previous paragraph. % % Note that another definition, "png:bit-depth-written" exists, but it % is not intended for external use. It is only used internally by the % PNG encoder to inform the JNG encoder of the depth of the alpha channel. % % It is possible to request that the PNG encoder write previously-formatted % ancillary chunks in the output PNG file, using the "-profile" commandline % option as shown below or by setting the profile via a programming % interface: % % -profile PNG-chunk-x:<file> % % where x is a location flag and <file> is a file containing the chunk % name in the first 4 bytes, then a colon (":"), followed by the chunk data. % This encoder will compute the chunk length and CRC, so those must not % be included in the file. % % "x" can be "b" (before PLTE), "m" (middle, i.e., between PLTE and IDAT), % or "e" (end, i.e., after IDAT). If you want to write multiple chunks % of the same type, then add a short unique string after the "x" to prevent % subsequent profiles from overwriting the preceding ones, e.g., % % -profile PNG-chunk-b01:file01 -profile PNG-chunk-b02:file02 % % As of version 6.6.6 the following optimizations are always done: % % o 32-bit depth is reduced to 16. % o 16-bit depth is reduced to 8 if all pixels contain samples whose % high byte and low byte are identical. % o Palette is sorted to remove unused entries and to put a % transparent color first, if BUILD_PNG_PALETTE is defined. % o Opaque matte channel is removed when writing an indexed PNG. % o Grayscale images are reduced to 1, 2, or 4 bit depth if % this can be done without loss and a larger bit depth N was not % requested via the "-define png:bit-depth=N" option. % o If matte channel is present but only one transparent color is % present, RGB+tRNS is written instead of RGBA % o Opaque matte channel is removed (or added, if color-type 4 or 6 % was requested when converting an opaque image). % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) { MagickBooleanType excluding, logging, status; MngInfo *mng_info; const char *value; int source; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; mng_info->equal_backgrounds=MagickTrue; /* See if user has requested a specific PNG subformat */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0; mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0; value=GetImageOption(image_info,"png:format"); if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0) { mng_info->write_png8 = MagickFalse; mng_info->write_png24 = MagickFalse; mng_info->write_png32 = MagickFalse; mng_info->write_png48 = MagickFalse; mng_info->write_png64 = MagickFalse; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",value); if (LocaleCompare(value,"png8") == 0) mng_info->write_png8 = MagickTrue; else if (LocaleCompare(value,"png24") == 0) mng_info->write_png24 = MagickTrue; else if (LocaleCompare(value,"png32") == 0) mng_info->write_png32 = MagickTrue; else if (LocaleCompare(value,"png48") == 0) mng_info->write_png48 = MagickTrue; else if (LocaleCompare(value,"png64") == 0) mng_info->write_png64 = MagickTrue; else if ((LocaleCompare(value,"png00") == 0) || LocaleCompare(image_info->magick,"PNG00") == 0) { /* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig */ value=GetImageProperty(image,"png:IHDR.bit-depth-orig"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited bit depth=%s",value); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; } value=GetImageProperty(image,"png:IHDR.color-type-orig"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited color type=%s",value); if (value != (char *) NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; } } } if (mng_info->write_png8) { mng_info->write_png_colortype = /* 3 */ 4; mng_info->write_png_depth = 8; image->depth = 8; } if (mng_info->write_png24) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 8; image->depth = 8; if (image->matte != MagickFalse) (void) SetImageType(image,TrueColorMatteType); else (void) SetImageType(image,TrueColorType); (void) SyncImage(image); } if (mng_info->write_png32) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 8; image->depth = 8; image->matte = MagickTrue; (void) SetImageType(image,TrueColorMatteType); (void) SyncImage(image); } if (mng_info->write_png48) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 16; image->depth = 16; if (image->matte != MagickFalse) (void) SetImageType(image,TrueColorMatteType); else (void) SetImageType(image,TrueColorType); (void) SyncImage(image); } if (mng_info->write_png64) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 16; image->depth = 16; image->matte = MagickTrue; (void) SetImageType(image,TrueColorMatteType); (void) SyncImage(image); } value=GetImageOption(image_info,"png:bit-depth"); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:bit-depth", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:bit-depth=%d was defined.\n",mng_info->write_png_depth); } value=GetImageOption(image_info,"png:color-type"); if (value != (char *) NULL) { /* We must store colortype+1 because 0 is a valid colortype */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:color-type", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:color-type=%d was defined.\n",mng_info->write_png_colortype-1); } /* Check for chunks to be excluded: * * The default is to not exclude any known chunks except for any * listed in the "unused_chunks" array, above. * * Chunks can be listed for exclusion via a "png:exclude-chunk" * define (in the image properties or in the image artifacts) * or via a mng_info member. For convenience, in addition * to or instead of a comma-separated list of chunks, the * "exclude-chunk" string can be simply "all" or "none". * * The exclude-chunk define takes priority over the mng_info. * * A "png:include-chunk" define takes priority over both the * mng_info and the "png:exclude-chunk" define. Like the * "exclude-chunk" string, it can define "all" or "none" as * well as a comma-separated list. Chunks that are unknown to * ImageMagick are always excluded, regardless of their "copy-safe" * status according to the PNG specification, and even if they * appear in the "include-chunk" list. Such defines appearing among * the image options take priority over those found among the image * artifacts. * * Finally, all chunks listed in the "unused_chunks" array are * automatically excluded, regardless of the other instructions * or lack thereof. * * if you exclude sRGB but not gAMA (recommended), then sRGB chunk * will not be written and the gAMA chunk will only be written if it * is not between .45 and .46, or approximately (1.0/2.2). * * If you exclude tRNS and the image has transparency, the colortype * is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA). * * The -strip option causes StripImage() to set the png:include-chunk * artifact to "none,trns,gama". */ mng_info->ping_exclude_bKGD=MagickFalse; mng_info->ping_exclude_caNv=MagickFalse; mng_info->ping_exclude_cHRM=MagickFalse; mng_info->ping_exclude_date=MagickFalse; mng_info->ping_exclude_eXIf=MagickFalse; mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */ mng_info->ping_exclude_gAMA=MagickFalse; mng_info->ping_exclude_iCCP=MagickFalse; /* mng_info->ping_exclude_iTXt=MagickFalse; */ mng_info->ping_exclude_oFFs=MagickFalse; mng_info->ping_exclude_pHYs=MagickFalse; mng_info->ping_exclude_sRGB=MagickFalse; mng_info->ping_exclude_tEXt=MagickFalse; mng_info->ping_exclude_tIME=MagickFalse; mng_info->ping_exclude_tRNS=MagickFalse; mng_info->ping_exclude_vpAg=MagickFalse; mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */ mng_info->ping_exclude_zTXt=MagickFalse; mng_info->ping_preserve_colormap=MagickFalse; value=GetImageOption(image_info,"png:preserve-colormap"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-colormap"); if (value != NULL) mng_info->ping_preserve_colormap=MagickTrue; mng_info->ping_preserve_iCCP=MagickFalse; value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) mng_info->ping_preserve_iCCP=MagickTrue; /* These compression-level, compression-strategy, and compression-filter * defines take precedence over values from the -quality option. */ value=GetImageOption(image_info,"png:compression-level"); if (value == NULL) value=GetImageArtifact(image,"png:compression-level"); if (value != NULL) { /* To do: use a "LocaleInteger:()" function here. */ /* We have to add 1 to everything because 0 is a valid input, * and we want to use 0 (the default) to mean undefined. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_level = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_level = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_level = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_level = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_level = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_level = 6; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_compression_level = 7; else if (LocaleCompare(value,"7") == 0) mng_info->write_png_compression_level = 8; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_compression_level = 9; else if (LocaleCompare(value,"9") == 0) mng_info->write_png_compression_level = 10; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-level", "=%s",value); } value=GetImageOption(image_info,"png:compression-strategy"); if (value == NULL) value=GetImageArtifact(image,"png:compression-strategy"); if (value != NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_strategy = Z_FILTERED+1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; else if (LocaleCompare(value,"3") == 0) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy = Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else if (LocaleCompare(value,"4") == 0) #ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */ mng_info->write_png_compression_strategy = Z_FIXED+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-strategy", "=%s",value); } value=GetImageOption(image_info,"png:compression-filter"); if (value == NULL) value=GetImageArtifact(image,"png:compression-filter"); if (value != NULL) { /* To do: combinations of filters allowed by libpng * masks 0x08 through 0xf8 * * Implement this as a comma-separated list of 0,1,2,3,4,5 * where 5 is a special case meaning PNG_ALL_FILTERS. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_filter = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_filter = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_filter = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_filter = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_filter = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_filter = 6; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-filter", "=%s",value); } for (source=0; source<8; source++) { value = NULL; if (source == 0) value=GetImageOption(image_info,"png:exclude-chunks"); if (source == 1) value=GetImageArtifact(image,"png:exclude-chunks"); if (source == 2) value=GetImageOption(image_info,"png:exclude-chunk"); if (source == 3) value=GetImageArtifact(image,"png:exclude-chunk"); if (source == 4) value=GetImageOption(image_info,"png:include-chunks"); if (source == 5) value=GetImageArtifact(image,"png:include-chunks"); if (source == 6) value=GetImageOption(image_info,"png:include-chunk"); if (source == 7) value=GetImageArtifact(image,"png:include-chunk"); if (value == NULL) continue; if (source < 4) excluding = MagickTrue; else excluding = MagickFalse; if (logging != MagickFalse) { if (source == 0 || source == 2) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image options.\n", value); else if (source == 1 || source == 3) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image artifacts.\n", value); else if (source == 4 || source == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image options.\n", value); else /* if (source == 5 || source == 7) */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image artifacts.\n", value); } if (IsOptionMember("all",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding; mng_info->ping_exclude_caNv=excluding; mng_info->ping_exclude_cHRM=excluding; mng_info->ping_exclude_date=excluding; mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; mng_info->ping_exclude_gAMA=excluding; mng_info->ping_exclude_iCCP=excluding; /* mng_info->ping_exclude_iTXt=excluding; */ mng_info->ping_exclude_oFFs=excluding; mng_info->ping_exclude_pHYs=excluding; mng_info->ping_exclude_sRGB=excluding; mng_info->ping_exclude_tIME=excluding; mng_info->ping_exclude_tEXt=excluding; mng_info->ping_exclude_tRNS=excluding; mng_info->ping_exclude_vpAg=excluding; mng_info->ping_exclude_zCCP=excluding; mng_info->ping_exclude_zTXt=excluding; } if (IsOptionMember("none",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; /* mng_info->ping_exclude_iTXt=!excluding; */ mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_vpAg=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse : MagickTrue; } if (IsOptionMember("bkgd",value) != MagickFalse) mng_info->ping_exclude_bKGD=excluding; if (IsOptionMember("caNv",value) != MagickFalse) mng_info->ping_exclude_caNv=excluding; if (IsOptionMember("chrm",value) != MagickFalse) mng_info->ping_exclude_cHRM=excluding; if (IsOptionMember("date",value) != MagickFalse) mng_info->ping_exclude_date=excluding; if (IsOptionMember("exif",value) != MagickFalse) { mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; } if (IsOptionMember("gama",value) != MagickFalse) mng_info->ping_exclude_gAMA=excluding; if (IsOptionMember("iccp",value) != MagickFalse) mng_info->ping_exclude_iCCP=excluding; #if 0 if (IsOptionMember("itxt",value) != MagickFalse) mng_info->ping_exclude_iTXt=excluding; #endif if (IsOptionMember("offs",value) != MagickFalse) mng_info->ping_exclude_oFFs=excluding; if (IsOptionMember("phys",value) != MagickFalse) mng_info->ping_exclude_pHYs=excluding; if (IsOptionMember("srgb",value) != MagickFalse) mng_info->ping_exclude_sRGB=excluding; if (IsOptionMember("text",value) != MagickFalse) mng_info->ping_exclude_tEXt=excluding; if (IsOptionMember("time",value) != MagickFalse) mng_info->ping_exclude_tIME=excluding; if (IsOptionMember("trns",value) != MagickFalse) mng_info->ping_exclude_tRNS=excluding; if (IsOptionMember("vpag",value) != MagickFalse) mng_info->ping_exclude_vpAg=excluding; if (IsOptionMember("zccp",value) != MagickFalse) mng_info->ping_exclude_zCCP=excluding; if (IsOptionMember("ztxt",value) != MagickFalse) mng_info->ping_exclude_zTXt=excluding; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Chunks to be excluded from the output png:"); if (mng_info->ping_exclude_bKGD != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bKGD"); if (mng_info->ping_exclude_caNv != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " caNv"); if (mng_info->ping_exclude_cHRM != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " cHRM"); if (mng_info->ping_exclude_date != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " date"); if (mng_info->ping_exclude_EXIF != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " EXIF"); if (mng_info->ping_exclude_eXIf != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " eXIf"); if (mng_info->ping_exclude_gAMA != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " gAMA"); if (mng_info->ping_exclude_iCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iCCP"); #if 0 if (mng_info->ping_exclude_iTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iTXt"); #endif if (mng_info->ping_exclude_oFFs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " oFFs"); if (mng_info->ping_exclude_pHYs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pHYs"); if (mng_info->ping_exclude_sRGB != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " sRGB"); if (mng_info->ping_exclude_tEXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tEXt"); if (mng_info->ping_exclude_tIME != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tIME"); if (mng_info->ping_exclude_tRNS != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS"); if (mng_info->ping_exclude_vpAg != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " vpAg"); if (mng_info->ping_exclude_zCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zCCP"); if (mng_info->ping_exclude_zTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zTXt"); } mng_info->need_blob = MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image); (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()"); return(status); } #if defined(JNG_SUPPORTED) /* Write one JNG image */ static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { Image *jpeg_image; ImageInfo *jpeg_image_info; int unique_filenames; MagickBooleanType logging, status; size_t length; unsigned char *blob, chunk[80], *p; unsigned int jng_alpha_compression_method, jng_alpha_sample_depth, jng_color_type, transparent; size_t jng_alpha_quality, jng_quality; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOneJNGImage()"); blob=(unsigned char *) NULL; jpeg_image=(Image *) NULL; jpeg_image_info=(ImageInfo *) NULL; length=0; unique_filenames=0; status=MagickTrue; transparent=image_info->type==GrayscaleMatteType || image_info->type==TrueColorMatteType || image->matte != MagickFalse; jng_alpha_sample_depth = 0; jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000; jng_alpha_compression_method=image->compression==JPEGCompression? 8 : 0; jng_alpha_quality=image_info->quality == 0UL ? 75UL : image_info->quality; if (jng_alpha_quality >= 1000) jng_alpha_quality /= 1000; if (transparent != 0) { jng_color_type=14; /* Create JPEG blob, image, and image_info */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info for opacity."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); status=SeparateImageChannel(jpeg_image,OpacityChannel); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=NegateImage(jpeg_image,MagickFalse); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); jpeg_image->matte=MagickFalse; jpeg_image_info->type=GrayscaleType; jpeg_image->quality=jng_alpha_quality; (void) SetImageType(jpeg_image,GrayscaleType); (void) AcquireUniqueFilename(jpeg_image->filename); unique_filenames++; (void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent, "%s",jpeg_image->filename); } else { jng_alpha_compression_method=0; jng_color_type=10; jng_alpha_sample_depth=0; } /* To do: check bit depth of PNG alpha channel */ /* Check if image is grayscale. */ if (image_info->type != TrueColorMatteType && image_info->type != TrueColorType && SetImageGray(image,&image->exception)) jng_color_type-=2; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Quality = %d",(int) jng_quality); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Color Type = %d",jng_color_type); if (transparent != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Compression = %d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Depth = %d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Quality = %d",(int) jng_alpha_quality); } } if (transparent != 0) { if (jng_alpha_compression_method==0) { const char *value; /* Encode opacity as a grayscale PNG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating PNG blob for alpha."); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); length=0; (void) CopyMagickString(jpeg_image_info->magick,"PNG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"PNG",MaxTextExtent); jpeg_image_info->interlace=NoInterlace; /* Exclude all ancillary chunks */ (void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all"); blob=ImageToBlob(jpeg_image_info,jpeg_image,&length, &image->exception); /* Retrieve sample depth used */ value=GetImageProperty(jpeg_image,"png:bit-depth-written"); if (value != (char *) NULL) jng_alpha_sample_depth= (unsigned int) value[0]; } else { /* Encode opacity as a grayscale JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating JPEG blob for alpha."); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); jpeg_image_info->interlace=NoInterlace; blob=ImageToBlob(jpeg_image_info,jpeg_image,&length, &image->exception); jng_alpha_sample_depth=8; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); } /* Destroy JPEG image and image_info */ jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); unique_filenames--; jpeg_image_info=DestroyImageInfo(jpeg_image_info); } /* Write JHDR chunk */ (void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */ PNGType(chunk,mng_JHDR); LogPNGChunk(logging,mng_JHDR,16L); PNGLong(chunk+4,(png_uint_32) image->columns); PNGLong(chunk+8,(png_uint_32) image->rows); chunk[12]=jng_color_type; chunk[13]=8; /* sample depth */ chunk[14]=8; /*jng_image_compression_method */ chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8); chunk[16]=jng_alpha_sample_depth; chunk[17]=jng_alpha_compression_method; chunk[18]=0; /*jng_alpha_filter_method */ chunk[19]=0; /*jng_alpha_interlace_method */ (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width:%15lu",(unsigned long) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG height:%14lu",(unsigned long) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG color type:%10d",jng_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG sample depth:%8d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG compression:%9d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG interlace:%11d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha depth:%9d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha compression:%3d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha filter:%8d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha interlace:%5d",0); } /* Write any JNG-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-b",logging); /* Write leading ancillary chunks */ if (transparent != 0) { /* Write JNG bKGD chunk */ unsigned char blue, green, red; ssize_t num_bytes; if (jng_color_type == 8 || jng_color_type == 12) num_bytes=6L; else num_bytes=10L; (void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L)); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L)); red=ScaleQuantumToChar(image->background_color.red); green=ScaleQuantumToChar(image->background_color.green); blue=ScaleQuantumToChar(image->background_color.blue); *(chunk+4)=0; *(chunk+5)=red; *(chunk+6)=0; *(chunk+7)=green; *(chunk+8)=0; *(chunk+9)=blue; (void) WriteBlob(image,(size_t) num_bytes,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes)); } if ((image->colorspace == sRGBColorspace || image->rendering_intent)) { /* Write JNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { if (image->gamma != 0.0) { /* Write JNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); } if ((mng_info->equal_chrms == MagickFalse) && (image->chromaticity.red_primary.x != 0.0)) { PrimaryInfo primary; /* Write JNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); } } if (image->x_resolution && image->y_resolution && !mng_info->equal_physs) { /* Write JNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.x || image->page.y)) { /* Write JNG oFFs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_oFFs); LogPNGChunk(logging,mng_oFFs,9L); PNGsLong(chunk+4,(ssize_t) (image->page.x)); PNGsLong(chunk+8,(ssize_t) (image->page.y)); chunk[12]=0; (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.width || image->page.height)) { (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (transparent != 0) { if (jng_alpha_compression_method==0) { register ssize_t i; size_t len; /* Write IDAT chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write IDAT chunks from blob, length=%.20g.",(double) length); /* Copy IDAT chunks */ len=0; p=blob+8; for (i=8; i<(ssize_t) length; i+=len+12) { len=(size_t) (*p) << 24; len|=(size_t) (*(p+1)) << 16; len|=(size_t) (*(p+2)) << 8; len|=(size_t) (*(p+3)); p+=4; if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */ { /* Found an IDAT chunk. */ (void) WriteBlobMSBULong(image,len); LogPNGChunk(logging,mng_IDAT,len); (void) WriteBlob(image,len+4,p); (void) WriteBlobMSBULong(image,crc32(0,p,(uInt) len+4)); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping %c%c%c%c chunk, length=%.20g.", *(p),*(p+1),*(p+2),*(p+3),(double) len); } p+=(8+len); } } else if (length != 0) { /* Write JDAA chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAA chunk, length=%.20g.",(double) length); (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAA); LogPNGChunk(logging,mng_JDAA,length); /* Write JDAT chunk(s) data */ (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob, (uInt) length)); } blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Encode image as a JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); (void) AcquireUniqueFilename(jpeg_image->filename); unique_filenames++; (void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent,"%s", jpeg_image->filename); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns, (double) jpeg_image->rows); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (jng_color_type == 8 || jng_color_type == 12) jpeg_image_info->type=GrayscaleType; jpeg_image_info->quality=jng_quality; jpeg_image->quality=jng_quality; (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,&image->exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAT chunk, length=%.20g.",(double) length); } /* Write JDAT chunk(s) */ (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAT); LogPNGChunk(logging,mng_JDAT,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length)); jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); unique_filenames--; jpeg_image_info=DestroyImageInfo(jpeg_image_info); blob=(unsigned char *) RelinquishMagickMemory(blob); /* Write any JNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-e",logging); /* Write IEND chunk */ (void) WriteBlobMSBULong(image,0L); PNGType(chunk,mng_IEND); LogPNGChunk(logging,mng_IEND,0); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOneJNGImage(); unique_filenames=%d",unique_filenames); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJNGImage() writes a JPEG Network Graphics (JNG) image file. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteJNGImage method is: % % MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image) { MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; (void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n"); status=WriteOneJNGImage(mng_info,image_info,image); mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); (void) CatchImageException(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteJNGImage()"); return(status); } #endif static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) { const char *option; Image *next_image; MagickBooleanType status; volatile MagickBooleanType logging; MngInfo *mng_info; int image_count, need_iterations, need_matte; volatile int #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) need_local_plte, #endif all_images_are_gray, need_defi, use_global_plte; register ssize_t i; unsigned char chunk[800]; volatile unsigned int write_jng, write_mng; volatile size_t scene; size_t final_delay=0, initial_delay; #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; write_mng=LocaleCompare(image_info->magick,"MNG") == 0; /* * See if user has requested a specific PNG subformat to be used * for all of the PNGs in the MNG being written, e.g., * * convert *.png png8:animation.mng * * To do: check -define png:bit_depth and png:color_type as well, * or perhaps use mng:bit_depth and mng:color_type instead for * global settings. */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; write_jng=MagickFalse; if (image_info->compression == JPEGCompression) write_jng=MagickTrue; mng_info->adjoin=image_info->adjoin && (GetNextImageInList(image) != (Image *) NULL) && write_mng; if (logging != MagickFalse) { /* Log some info about the input */ Image *p; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Checking input image(s)\n" " Image_info depth: %.20g, Type: %d", (double) image_info->depth, image_info->type); scene=0; for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scene: %.20g\n, Image depth: %.20g", (double) scene++, (double) p->depth); if (p->matte) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: False"); if (p->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: PseudoClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: DirectClass"); if (p->colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) p->colors); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: unspecified"); if (mng_info->adjoin == MagickFalse) break; } } use_global_plte=MagickFalse; all_images_are_gray=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_defi=MagickFalse; need_matte=MagickFalse; mng_info->framing_mode=1; mng_info->old_framing_mode=1; if (write_mng) if (image_info->page != (char *) NULL) { /* Determine image bounding box. */ SetGeometry(image,&mng_info->page); (void) ParseMetaGeometry(image_info->page,&mng_info->page.x, &mng_info->page.y,&mng_info->page.width,&mng_info->page.height); } if (write_mng) { unsigned int need_geom; unsigned short red, green, blue; mng_info->page=image->page; need_geom=MagickTrue; if (mng_info->page.width || mng_info->page.height) need_geom=MagickFalse; /* Check all the scenes. */ initial_delay=image->delay; need_iterations=MagickFalse; mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0; mng_info->equal_physs=MagickTrue, mng_info->equal_gammas=MagickTrue; mng_info->equal_srgbs=MagickTrue; mng_info->equal_backgrounds=MagickTrue; image_count=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) all_images_are_gray=MagickTrue; mng_info->equal_palettes=MagickFalse; need_local_plte=MagickFalse; #endif for (next_image=image; next_image != (Image *) NULL; ) { if (need_geom) { if ((next_image->columns+next_image->page.x) > mng_info->page.width) mng_info->page.width=next_image->columns+next_image->page.x; if ((next_image->rows+next_image->page.y) > mng_info->page.height) mng_info->page.height=next_image->rows+next_image->page.y; } if (next_image->page.x || next_image->page.y) need_defi=MagickTrue; if (next_image->matte) need_matte=MagickTrue; if ((int) next_image->dispose >= BackgroundDispose) if (next_image->matte || next_image->page.x || next_image->page.y || ((next_image->columns < mng_info->page.width) && (next_image->rows < mng_info->page.height))) mng_info->need_fram=MagickTrue; if (next_image->iterations) need_iterations=MagickTrue; final_delay=next_image->delay; if (final_delay != initial_delay || final_delay > 1UL* next_image->ticks_per_second) mng_info->need_fram=1; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* check for global palette possibility. */ if (image->matte != MagickFalse) need_local_plte=MagickTrue; if (need_local_plte == 0) { if (SetImageGray(image,&image->exception) == MagickFalse) all_images_are_gray=MagickFalse; mng_info->equal_palettes=PalettesAreEqual(image,next_image); if (use_global_plte == 0) use_global_plte=mng_info->equal_palettes; need_local_plte=!mng_info->equal_palettes; } #endif if (GetNextImageInList(next_image) != (Image *) NULL) { if (next_image->background_color.red != next_image->next->background_color.red || next_image->background_color.green != next_image->next->background_color.green || next_image->background_color.blue != next_image->next->background_color.blue) mng_info->equal_backgrounds=MagickFalse; if (next_image->gamma != next_image->next->gamma) mng_info->equal_gammas=MagickFalse; if (next_image->rendering_intent != next_image->next->rendering_intent) mng_info->equal_srgbs=MagickFalse; if ((next_image->units != next_image->next->units) || (next_image->x_resolution != next_image->next->x_resolution) || (next_image->y_resolution != next_image->next->y_resolution)) mng_info->equal_physs=MagickFalse; if (mng_info->equal_chrms) { if (next_image->chromaticity.red_primary.x != next_image->next->chromaticity.red_primary.x || next_image->chromaticity.red_primary.y != next_image->next->chromaticity.red_primary.y || next_image->chromaticity.green_primary.x != next_image->next->chromaticity.green_primary.x || next_image->chromaticity.green_primary.y != next_image->next->chromaticity.green_primary.y || next_image->chromaticity.blue_primary.x != next_image->next->chromaticity.blue_primary.x || next_image->chromaticity.blue_primary.y != next_image->next->chromaticity.blue_primary.y || next_image->chromaticity.white_point.x != next_image->next->chromaticity.white_point.x || next_image->chromaticity.white_point.y != next_image->next->chromaticity.white_point.y) mng_info->equal_chrms=MagickFalse; } } image_count++; next_image=GetNextImageInList(next_image); } if (image_count < 2) { mng_info->equal_backgrounds=MagickFalse; mng_info->equal_chrms=MagickFalse; mng_info->equal_gammas=MagickFalse; mng_info->equal_srgbs=MagickFalse; mng_info->equal_physs=MagickFalse; use_global_plte=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_iterations=MagickFalse; } if (mng_info->need_fram == MagickFalse) { /* Only certain framing rates 100/n are exactly representable without the FRAM chunk but we'll allow some slop in VLC files */ if (final_delay == 0) { if (need_iterations != MagickFalse) { /* It's probably a GIF with loop; don't run it *too* fast. */ if (mng_info->adjoin) { final_delay=10; (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "input has zero delay between all frames; assuming", " 10 cs `%s'",""); } } else mng_info->ticks_per_second=0; } if (final_delay != 0) mng_info->ticks_per_second=(png_uint_32) (image->ticks_per_second/final_delay); if (final_delay > 50) mng_info->ticks_per_second=2; if (final_delay > 75) mng_info->ticks_per_second=1; if (final_delay > 125) mng_info->need_fram=MagickTrue; if (need_defi && final_delay > 2 && (final_delay != 4) && (final_delay != 5) && (final_delay != 10) && (final_delay != 20) && (final_delay != 25) && (final_delay != 50) && (final_delay != (size_t) image->ticks_per_second)) mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */ } if (mng_info->need_fram != MagickFalse) mng_info->ticks_per_second=1UL*image->ticks_per_second; /* If pseudocolor, we should also check to see if all the palettes are identical and write a global PLTE if they are. ../glennrp Feb 99. */ /* Write the MNG version 1.0 signature and MHDR chunk. */ (void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n"); (void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */ PNGType(chunk,mng_MHDR); LogPNGChunk(logging,mng_MHDR,28L); PNGLong(chunk+4,(png_uint_32) mng_info->page.width); PNGLong(chunk+8,(png_uint_32) mng_info->page.height); PNGLong(chunk+12,mng_info->ticks_per_second); PNGLong(chunk+16,0L); /* layer count=unknown */ PNGLong(chunk+20,0L); /* frame count=unknown */ PNGLong(chunk+24,0L); /* play time=unknown */ if (write_jng) { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,27L); /* simplicity=LC+JNG */ else PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */ else PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */ } } else { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,11L); /* simplicity=LC */ else PNGLong(chunk+28,9L); /* simplicity=VLC */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */ else PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */ } } (void) WriteBlob(image,32,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,32)); option=GetImageOption(image_info,"mng:need-cacheoff"); if (option != (const char *) NULL) { size_t length; /* Write "nEED CACHEOFF" to turn playback caching off for streaming MNG. */ PNGType(chunk,mng_nEED); length=CopyMagickString((char *) chunk+4,"CACHEOFF",20); (void) WriteBlobMSBULong(image,(size_t) length); LogPNGChunk(logging,mng_nEED,(size_t) length); length+=4; (void) WriteBlob(image,length,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length)); } if ((GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) != (Image *) NULL) && (image->iterations != 1)) { /* Write MNG TERM chunk */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_TERM); LogPNGChunk(logging,mng_TERM,10L); chunk[4]=3; /* repeat animation */ chunk[5]=0; /* show last frame when done */ PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) PNGLong(chunk+10,PNG_UINT_31_MAX); else PNGLong(chunk+10,(png_uint_32) image->iterations); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM delay: %.20g",(double) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM iterations: %.20g",(double) PNG_UINT_31_MAX); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image iterations: %.20g",(double) image->iterations); } (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); } /* To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if ((image->colorspace == sRGBColorspace || image->rendering_intent) && mng_info->equal_srgbs) { /* Write MNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); mng_info->have_write_global_srgb=MagickTrue; } else { if (image->gamma && mng_info->equal_gammas) { /* Write MNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); mng_info->have_write_global_gama=MagickTrue; } if (mng_info->equal_chrms) { PrimaryInfo primary; /* Write MNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); mng_info->have_write_global_chrm=MagickTrue; } } if (image->x_resolution && image->y_resolution && mng_info->equal_physs) { /* Write MNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } /* Write MNG BACK chunk and global bKGD chunk, if the image is transparent or does not cover the entire frame. */ if (write_mng && (image->matte || image->page.x > 0 || image->page.y > 0 || (image->page.width && (image->page.width+image->page.x < mng_info->page.width)) || (image->page.height && (image->page.height+image->page.y < mng_info->page.height)))) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_BACK); LogPNGChunk(logging,mng_BACK,6L); red=ScaleQuantumToShort(image->background_color.red); green=ScaleQuantumToShort(image->background_color.green); blue=ScaleQuantumToShort(image->background_color.blue); PNGShort(chunk+4,red); PNGShort(chunk+6,green); PNGShort(chunk+8,blue); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); if (mng_info->equal_backgrounds) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,6L); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); } } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if ((need_local_plte == MagickFalse) && (image->storage_class == PseudoClass) && (all_images_are_gray == MagickFalse)) { size_t data_length; /* Write MNG PLTE chunk */ data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red) & 0xff; chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green) & 0xff; chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue) & 0xff; } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } #endif } scene=0; mng_info->delay=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) mng_info->equal_palettes=MagickFalse; #endif do { if (mng_info->adjoin) { #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* If we aren't using a global palette for the entire MNG, check to see if we can use one for two or more consecutive images. */ if (need_local_plte && use_global_plte && !all_images_are_gray) { if (mng_info->IsPalette) { /* When equal_palettes is true, this image has the same palette as the previous PseudoClass image */ mng_info->have_write_global_plte=mng_info->equal_palettes; mng_info->equal_palettes=PalettesAreEqual(image,image->next); if (mng_info->equal_palettes && !mng_info->have_write_global_plte) { /* Write MNG PLTE chunk */ size_t data_length; data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red); chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green); chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk, (uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } } else mng_info->have_write_global_plte=MagickFalse; } #endif if (need_defi) { ssize_t previous_x, previous_y; if (scene != 0) { previous_x=mng_info->page.x; previous_y=mng_info->page.y; } else { previous_x=0; previous_y=0; } mng_info->page=image->page; if ((mng_info->page.x != previous_x) || (mng_info->page.y != previous_y)) { (void) WriteBlobMSBULong(image,12L); /* data length=12 */ PNGType(chunk,mng_DEFI); LogPNGChunk(logging,mng_DEFI,12L); chunk[4]=0; /* object 0 MSB */ chunk[5]=0; /* object 0 LSB */ chunk[6]=0; /* visible */ chunk[7]=0; /* abstract */ PNGLong(chunk+8,(png_uint_32) mng_info->page.x); PNGLong(chunk+12,(png_uint_32) mng_info->page.y); (void) WriteBlob(image,16,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,16)); } } } mng_info->write_mng=write_mng; if ((int) image->dispose >= 3) mng_info->framing_mode=3; if (mng_info->need_fram && mng_info->adjoin && ((image->delay != mng_info->delay) || (mng_info->framing_mode != mng_info->old_framing_mode))) { if (image->delay == mng_info->delay) { /* Write a MNG FRAM chunk with the new framing mode. */ (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,1L); chunk[4]=(unsigned char) mng_info->framing_mode; (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { /* Write a MNG FRAM chunk with the delay. */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,10L); chunk[4]=(unsigned char) mng_info->framing_mode; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=2; /* flag for changing default delay */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=0; /* flag for changing frame clipping */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) ((mng_info->ticks_per_second* image->delay)/MagickMax(image->ticks_per_second,1))); (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); mng_info->delay=(png_uint_32) image->delay; } mng_info->old_framing_mode=mng_info->framing_mode; } #if defined(JNG_SUPPORTED) if (image_info->compression == JPEGCompression) { ImageInfo *write_info; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing JNG object."); /* To do: specify the desired alpha compression method. */ write_info=CloneImageInfo(image_info); write_info->compression=UndefinedCompression; status=WriteOneJNGImage(mng_info,write_info,image); write_info=DestroyImageInfo(write_info); } else #endif { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG object."); mng_info->need_blob = MagickFalse; mng_info->ping_preserve_colormap = MagickFalse; /* We don't want any ancillary chunks written */ mng_info->ping_exclude_bKGD=MagickTrue; mng_info->ping_exclude_caNv=MagickTrue; mng_info->ping_exclude_cHRM=MagickTrue; mng_info->ping_exclude_date=MagickTrue; mng_info->ping_exclude_EXIF=MagickTrue; mng_info->ping_exclude_eXIf=MagickTrue; mng_info->ping_exclude_gAMA=MagickTrue; mng_info->ping_exclude_iCCP=MagickTrue; /* mng_info->ping_exclude_iTXt=MagickTrue; */ mng_info->ping_exclude_oFFs=MagickTrue; mng_info->ping_exclude_pHYs=MagickTrue; mng_info->ping_exclude_sRGB=MagickTrue; mng_info->ping_exclude_tEXt=MagickTrue; mng_info->ping_exclude_tRNS=MagickTrue; mng_info->ping_exclude_vpAg=MagickTrue; mng_info->ping_exclude_zCCP=MagickTrue; mng_info->ping_exclude_zTXt=MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image); } if (status == MagickFalse) { mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); return(MagickFalse); } (void) CatchImageException(image); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (mng_info->adjoin); if (write_mng) { while (GetPreviousImageInList(image) != (Image *) NULL) image=GetPreviousImageInList(image); /* Write the MEND chunk. */ (void) WriteBlobMSBULong(image,0x00000000L); PNGType(chunk,mng_MEND); LogPNGChunk(logging,mng_MEND,0L); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); } /* Relinquish resources. */ (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()"); return(MagickTrue); } #else /* PNG_LIBPNG_VER > 10011 */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) { (void) image; printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); ThrowBinaryException(CoderError,"PNG library is too old", image_info->filename); } static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) { return(WritePNGImage(image_info,image)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2613_1
crossvul-cpp_data_bad_3364_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % AAA RRRR TTTTT % % A A R R T % % AAAAA RRRR T % % A A R R T % % A A R R T % % % % % % Support PFS: 1st Publisher Clip Art Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" /* Forward declarations. */ static MagickBooleanType WriteARTImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d A R T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadARTImage() reads an image of raw bits in LSB order and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadARTImage method is: % % Image *ReadARTImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception) { const unsigned char *pixels; Image *image; QuantumInfo *quantum_info; QuantumType quantum_type; MagickBooleanType status; size_t length; ssize_t count, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=1; image->endian=MSBEndian; (void) ReadBlobLSBShort(image); image->columns=(size_t) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); image->rows=(size_t) ReadBlobLSBShort(image); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image colormap. */ if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Convert bi-level image to pixel packets. */ SetImageColorspace(image,GRAYColorspace); quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) ReadBlobStream(image,(size_t) (-(ssize_t) length) & 0x01, GetQuantumPixels(quantum_info),&count); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r A R T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterARTImage() adds attributes for the ART image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterARTImage method is: % % size_t RegisterARTImage(void) % */ ModuleExport size_t RegisterARTImage(void) { MagickInfo *entry; entry=SetMagickInfo("ART"); entry->decoder=(DecodeImageHandler *) ReadARTImage; entry->encoder=(EncodeImageHandler *) WriteARTImage; entry->raw=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("PFS: 1st Publisher Clip Art"); entry->module=ConstantString("ART"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r A R T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterARTImage() removes format registrations made by the % ART module from the list of supported formats. % % The format of the UnregisterARTImage method is: % % UnregisterARTImage(void) % */ ModuleExport void UnregisterARTImage(void) { (void) UnregisterMagickInfo("ART"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e A R T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteARTImage() writes an image of raw bits in LSB order to a file. % % The format of the WriteARTImage method is: % % MagickBooleanType WriteARTImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteARTImage(const ImageInfo *image_info,Image *image) { MagickBooleanType status; QuantumInfo *quantum_info; register const PixelPacket *p; size_t length; ssize_t count, y; unsigned char *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); image->endian=MSBEndian; image->depth=1; (void) WriteBlobLSBShort(image,0); (void) WriteBlobLSBShort(image,(unsigned short) image->columns); (void) WriteBlobLSBShort(image,0); (void) WriteBlobLSBShort(image,(unsigned short) image->rows); (void) TransformImageColorspace(image,sRGBColorspace); length=(image->columns+7)/8; pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert image to a bi-level image. */ (void) SetImageType(image,BilevelType); quantum_info=AcquireQuantumInfo(image_info,image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, GrayQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) ThrowWriterException(CorruptImageError,"UnableToWriteImageData"); (void) WriteBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_3364_0
crossvul-cpp_data_bad_2604_0
/* * Copyright (C) 2001 Jens Axboe <axboe@kernel.dk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public Licens * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111- * */ #include <linux/mm.h> #include <linux/swap.h> #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/uio.h> #include <linux/iocontext.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/export.h> #include <linux/mempool.h> #include <linux/workqueue.h> #include <linux/cgroup.h> #include <trace/events/block.h> #include "blk.h" /* * Test patch to inline a certain number of bi_io_vec's inside the bio * itself, to shrink a bio data allocation from two mempool calls to one */ #define BIO_INLINE_VECS 4 /* * if you change this list, also change bvec_alloc or things will * break badly! cannot be bigger than what you can fit into an * unsigned short */ #define BV(x) { .nr_vecs = x, .name = "biovec-"__stringify(x) } static struct biovec_slab bvec_slabs[BVEC_POOL_NR] __read_mostly = { BV(1), BV(4), BV(16), BV(64), BV(128), BV(BIO_MAX_PAGES), }; #undef BV /* * fs_bio_set is the bio_set containing bio and iovec memory pools used by * IO code that does not need private memory pools. */ struct bio_set *fs_bio_set; EXPORT_SYMBOL(fs_bio_set); /* * Our slab pool management */ struct bio_slab { struct kmem_cache *slab; unsigned int slab_ref; unsigned int slab_size; char name[8]; }; static DEFINE_MUTEX(bio_slab_lock); static struct bio_slab *bio_slabs; static unsigned int bio_slab_nr, bio_slab_max; static struct kmem_cache *bio_find_or_create_slab(unsigned int extra_size) { unsigned int sz = sizeof(struct bio) + extra_size; struct kmem_cache *slab = NULL; struct bio_slab *bslab, *new_bio_slabs; unsigned int new_bio_slab_max; unsigned int i, entry = -1; mutex_lock(&bio_slab_lock); i = 0; while (i < bio_slab_nr) { bslab = &bio_slabs[i]; if (!bslab->slab && entry == -1) entry = i; else if (bslab->slab_size == sz) { slab = bslab->slab; bslab->slab_ref++; break; } i++; } if (slab) goto out_unlock; if (bio_slab_nr == bio_slab_max && entry == -1) { new_bio_slab_max = bio_slab_max << 1; new_bio_slabs = krealloc(bio_slabs, new_bio_slab_max * sizeof(struct bio_slab), GFP_KERNEL); if (!new_bio_slabs) goto out_unlock; bio_slab_max = new_bio_slab_max; bio_slabs = new_bio_slabs; } if (entry == -1) entry = bio_slab_nr++; bslab = &bio_slabs[entry]; snprintf(bslab->name, sizeof(bslab->name), "bio-%d", entry); slab = kmem_cache_create(bslab->name, sz, ARCH_KMALLOC_MINALIGN, SLAB_HWCACHE_ALIGN, NULL); if (!slab) goto out_unlock; bslab->slab = slab; bslab->slab_ref = 1; bslab->slab_size = sz; out_unlock: mutex_unlock(&bio_slab_lock); return slab; } static void bio_put_slab(struct bio_set *bs) { struct bio_slab *bslab = NULL; unsigned int i; mutex_lock(&bio_slab_lock); for (i = 0; i < bio_slab_nr; i++) { if (bs->bio_slab == bio_slabs[i].slab) { bslab = &bio_slabs[i]; break; } } if (WARN(!bslab, KERN_ERR "bio: unable to find slab!\n")) goto out; WARN_ON(!bslab->slab_ref); if (--bslab->slab_ref) goto out; kmem_cache_destroy(bslab->slab); bslab->slab = NULL; out: mutex_unlock(&bio_slab_lock); } unsigned int bvec_nr_vecs(unsigned short idx) { return bvec_slabs[idx].nr_vecs; } void bvec_free(mempool_t *pool, struct bio_vec *bv, unsigned int idx) { if (!idx) return; idx--; BIO_BUG_ON(idx >= BVEC_POOL_NR); if (idx == BVEC_POOL_MAX) { mempool_free(bv, pool); } else { struct biovec_slab *bvs = bvec_slabs + idx; kmem_cache_free(bvs->slab, bv); } } struct bio_vec *bvec_alloc(gfp_t gfp_mask, int nr, unsigned long *idx, mempool_t *pool) { struct bio_vec *bvl; /* * see comment near bvec_array define! */ switch (nr) { case 1: *idx = 0; break; case 2 ... 4: *idx = 1; break; case 5 ... 16: *idx = 2; break; case 17 ... 64: *idx = 3; break; case 65 ... 128: *idx = 4; break; case 129 ... BIO_MAX_PAGES: *idx = 5; break; default: return NULL; } /* * idx now points to the pool we want to allocate from. only the * 1-vec entry pool is mempool backed. */ if (*idx == BVEC_POOL_MAX) { fallback: bvl = mempool_alloc(pool, gfp_mask); } else { struct biovec_slab *bvs = bvec_slabs + *idx; gfp_t __gfp_mask = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_IO); /* * Make this allocation restricted and don't dump info on * allocation failures, since we'll fallback to the mempool * in case of failure. */ __gfp_mask |= __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN; /* * Try a slab allocation. If this fails and __GFP_DIRECT_RECLAIM * is set, retry with the 1-entry mempool */ bvl = kmem_cache_alloc(bvs->slab, __gfp_mask); if (unlikely(!bvl && (gfp_mask & __GFP_DIRECT_RECLAIM))) { *idx = BVEC_POOL_MAX; goto fallback; } } (*idx)++; return bvl; } void bio_uninit(struct bio *bio) { bio_disassociate_task(bio); } EXPORT_SYMBOL(bio_uninit); static void bio_free(struct bio *bio) { struct bio_set *bs = bio->bi_pool; void *p; bio_uninit(bio); if (bs) { bvec_free(bs->bvec_pool, bio->bi_io_vec, BVEC_POOL_IDX(bio)); /* * If we have front padding, adjust the bio pointer before freeing */ p = bio; p -= bs->front_pad; mempool_free(p, bs->bio_pool); } else { /* Bio was allocated by bio_kmalloc() */ kfree(bio); } } /* * Users of this function have their own bio allocation. Subsequently, * they must remember to pair any call to bio_init() with bio_uninit() * when IO has completed, or when the bio is released. */ void bio_init(struct bio *bio, struct bio_vec *table, unsigned short max_vecs) { memset(bio, 0, sizeof(*bio)); atomic_set(&bio->__bi_remaining, 1); atomic_set(&bio->__bi_cnt, 1); bio->bi_io_vec = table; bio->bi_max_vecs = max_vecs; } EXPORT_SYMBOL(bio_init); /** * bio_reset - reinitialize a bio * @bio: bio to reset * * Description: * After calling bio_reset(), @bio will be in the same state as a freshly * allocated bio returned bio bio_alloc_bioset() - the only fields that are * preserved are the ones that are initialized by bio_alloc_bioset(). See * comment in struct bio. */ void bio_reset(struct bio *bio) { unsigned long flags = bio->bi_flags & (~0UL << BIO_RESET_BITS); bio_uninit(bio); memset(bio, 0, BIO_RESET_BYTES); bio->bi_flags = flags; atomic_set(&bio->__bi_remaining, 1); } EXPORT_SYMBOL(bio_reset); static struct bio *__bio_chain_endio(struct bio *bio) { struct bio *parent = bio->bi_private; if (!parent->bi_status) parent->bi_status = bio->bi_status; bio_put(bio); return parent; } static void bio_chain_endio(struct bio *bio) { bio_endio(__bio_chain_endio(bio)); } /** * bio_chain - chain bio completions * @bio: the target bio * @parent: the @bio's parent bio * * The caller won't have a bi_end_io called when @bio completes - instead, * @parent's bi_end_io won't be called until both @parent and @bio have * completed; the chained bio will also be freed when it completes. * * The caller must not set bi_private or bi_end_io in @bio. */ void bio_chain(struct bio *bio, struct bio *parent) { BUG_ON(bio->bi_private || bio->bi_end_io); bio->bi_private = parent; bio->bi_end_io = bio_chain_endio; bio_inc_remaining(parent); } EXPORT_SYMBOL(bio_chain); static void bio_alloc_rescue(struct work_struct *work) { struct bio_set *bs = container_of(work, struct bio_set, rescue_work); struct bio *bio; while (1) { spin_lock(&bs->rescue_lock); bio = bio_list_pop(&bs->rescue_list); spin_unlock(&bs->rescue_lock); if (!bio) break; generic_make_request(bio); } } static void punt_bios_to_rescuer(struct bio_set *bs) { struct bio_list punt, nopunt; struct bio *bio; if (WARN_ON_ONCE(!bs->rescue_workqueue)) return; /* * In order to guarantee forward progress we must punt only bios that * were allocated from this bio_set; otherwise, if there was a bio on * there for a stacking driver higher up in the stack, processing it * could require allocating bios from this bio_set, and doing that from * our own rescuer would be bad. * * Since bio lists are singly linked, pop them all instead of trying to * remove from the middle of the list: */ bio_list_init(&punt); bio_list_init(&nopunt); while ((bio = bio_list_pop(&current->bio_list[0]))) bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio); current->bio_list[0] = nopunt; bio_list_init(&nopunt); while ((bio = bio_list_pop(&current->bio_list[1]))) bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio); current->bio_list[1] = nopunt; spin_lock(&bs->rescue_lock); bio_list_merge(&bs->rescue_list, &punt); spin_unlock(&bs->rescue_lock); queue_work(bs->rescue_workqueue, &bs->rescue_work); } /** * bio_alloc_bioset - allocate a bio for I/O * @gfp_mask: the GFP_ mask given to the slab allocator * @nr_iovecs: number of iovecs to pre-allocate * @bs: the bio_set to allocate from. * * Description: * If @bs is NULL, uses kmalloc() to allocate the bio; else the allocation is * backed by the @bs's mempool. * * When @bs is not NULL, if %__GFP_DIRECT_RECLAIM is set then bio_alloc will * always be able to allocate a bio. This is due to the mempool guarantees. * To make this work, callers must never allocate more than 1 bio at a time * from this pool. Callers that need to allocate more than 1 bio must always * submit the previously allocated bio for IO before attempting to allocate * a new one. Failure to do so can cause deadlocks under memory pressure. * * Note that when running under generic_make_request() (i.e. any block * driver), bios are not submitted until after you return - see the code in * generic_make_request() that converts recursion into iteration, to prevent * stack overflows. * * This would normally mean allocating multiple bios under * generic_make_request() would be susceptible to deadlocks, but we have * deadlock avoidance code that resubmits any blocked bios from a rescuer * thread. * * However, we do not guarantee forward progress for allocations from other * mempools. Doing multiple allocations from the same mempool under * generic_make_request() should be avoided - instead, use bio_set's front_pad * for per bio allocations. * * RETURNS: * Pointer to new bio on success, NULL on failure. */ struct bio *bio_alloc_bioset(gfp_t gfp_mask, unsigned int nr_iovecs, struct bio_set *bs) { gfp_t saved_gfp = gfp_mask; unsigned front_pad; unsigned inline_vecs; struct bio_vec *bvl = NULL; struct bio *bio; void *p; if (!bs) { if (nr_iovecs > UIO_MAXIOV) return NULL; p = kmalloc(sizeof(struct bio) + nr_iovecs * sizeof(struct bio_vec), gfp_mask); front_pad = 0; inline_vecs = nr_iovecs; } else { /* should not use nobvec bioset for nr_iovecs > 0 */ if (WARN_ON_ONCE(!bs->bvec_pool && nr_iovecs > 0)) return NULL; /* * generic_make_request() converts recursion to iteration; this * means if we're running beneath it, any bios we allocate and * submit will not be submitted (and thus freed) until after we * return. * * This exposes us to a potential deadlock if we allocate * multiple bios from the same bio_set() while running * underneath generic_make_request(). If we were to allocate * multiple bios (say a stacking block driver that was splitting * bios), we would deadlock if we exhausted the mempool's * reserve. * * We solve this, and guarantee forward progress, with a rescuer * workqueue per bio_set. If we go to allocate and there are * bios on current->bio_list, we first try the allocation * without __GFP_DIRECT_RECLAIM; if that fails, we punt those * bios we would be blocking to the rescuer workqueue before * we retry with the original gfp_flags. */ if (current->bio_list && (!bio_list_empty(&current->bio_list[0]) || !bio_list_empty(&current->bio_list[1])) && bs->rescue_workqueue) gfp_mask &= ~__GFP_DIRECT_RECLAIM; p = mempool_alloc(bs->bio_pool, gfp_mask); if (!p && gfp_mask != saved_gfp) { punt_bios_to_rescuer(bs); gfp_mask = saved_gfp; p = mempool_alloc(bs->bio_pool, gfp_mask); } front_pad = bs->front_pad; inline_vecs = BIO_INLINE_VECS; } if (unlikely(!p)) return NULL; bio = p + front_pad; bio_init(bio, NULL, 0); if (nr_iovecs > inline_vecs) { unsigned long idx = 0; bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx, bs->bvec_pool); if (!bvl && gfp_mask != saved_gfp) { punt_bios_to_rescuer(bs); gfp_mask = saved_gfp; bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx, bs->bvec_pool); } if (unlikely(!bvl)) goto err_free; bio->bi_flags |= idx << BVEC_POOL_OFFSET; } else if (nr_iovecs) { bvl = bio->bi_inline_vecs; } bio->bi_pool = bs; bio->bi_max_vecs = nr_iovecs; bio->bi_io_vec = bvl; return bio; err_free: mempool_free(p, bs->bio_pool); return NULL; } EXPORT_SYMBOL(bio_alloc_bioset); void zero_fill_bio(struct bio *bio) { unsigned long flags; struct bio_vec bv; struct bvec_iter iter; bio_for_each_segment(bv, bio, iter) { char *data = bvec_kmap_irq(&bv, &flags); memset(data, 0, bv.bv_len); flush_dcache_page(bv.bv_page); bvec_kunmap_irq(data, &flags); } } EXPORT_SYMBOL(zero_fill_bio); /** * bio_put - release a reference to a bio * @bio: bio to release reference to * * Description: * Put a reference to a &struct bio, either one you have gotten with * bio_alloc, bio_get or bio_clone_*. The last put of a bio will free it. **/ void bio_put(struct bio *bio) { if (!bio_flagged(bio, BIO_REFFED)) bio_free(bio); else { BIO_BUG_ON(!atomic_read(&bio->__bi_cnt)); /* * last put frees it */ if (atomic_dec_and_test(&bio->__bi_cnt)) bio_free(bio); } } EXPORT_SYMBOL(bio_put); inline int bio_phys_segments(struct request_queue *q, struct bio *bio) { if (unlikely(!bio_flagged(bio, BIO_SEG_VALID))) blk_recount_segments(q, bio); return bio->bi_phys_segments; } EXPORT_SYMBOL(bio_phys_segments); /** * __bio_clone_fast - clone a bio that shares the original bio's biovec * @bio: destination bio * @bio_src: bio to clone * * Clone a &bio. Caller will own the returned bio, but not * the actual data it points to. Reference count of returned * bio will be one. * * Caller must ensure that @bio_src is not freed before @bio. */ void __bio_clone_fast(struct bio *bio, struct bio *bio_src) { BUG_ON(bio->bi_pool && BVEC_POOL_IDX(bio)); /* * most users will be overriding ->bi_disk with a new target, * so we don't set nor calculate new physical/hw segment counts here */ bio->bi_disk = bio_src->bi_disk; bio_set_flag(bio, BIO_CLONED); bio->bi_opf = bio_src->bi_opf; bio->bi_write_hint = bio_src->bi_write_hint; bio->bi_iter = bio_src->bi_iter; bio->bi_io_vec = bio_src->bi_io_vec; bio_clone_blkcg_association(bio, bio_src); } EXPORT_SYMBOL(__bio_clone_fast); /** * bio_clone_fast - clone a bio that shares the original bio's biovec * @bio: bio to clone * @gfp_mask: allocation priority * @bs: bio_set to allocate from * * Like __bio_clone_fast, only also allocates the returned bio */ struct bio *bio_clone_fast(struct bio *bio, gfp_t gfp_mask, struct bio_set *bs) { struct bio *b; b = bio_alloc_bioset(gfp_mask, 0, bs); if (!b) return NULL; __bio_clone_fast(b, bio); if (bio_integrity(bio)) { int ret; ret = bio_integrity_clone(b, bio, gfp_mask); if (ret < 0) { bio_put(b); return NULL; } } return b; } EXPORT_SYMBOL(bio_clone_fast); /** * bio_clone_bioset - clone a bio * @bio_src: bio to clone * @gfp_mask: allocation priority * @bs: bio_set to allocate from * * Clone bio. Caller will own the returned bio, but not the actual data it * points to. Reference count of returned bio will be one. */ struct bio *bio_clone_bioset(struct bio *bio_src, gfp_t gfp_mask, struct bio_set *bs) { struct bvec_iter iter; struct bio_vec bv; struct bio *bio; /* * Pre immutable biovecs, __bio_clone() used to just do a memcpy from * bio_src->bi_io_vec to bio->bi_io_vec. * * We can't do that anymore, because: * * - The point of cloning the biovec is to produce a bio with a biovec * the caller can modify: bi_idx and bi_bvec_done should be 0. * * - The original bio could've had more than BIO_MAX_PAGES biovecs; if * we tried to clone the whole thing bio_alloc_bioset() would fail. * But the clone should succeed as long as the number of biovecs we * actually need to allocate is fewer than BIO_MAX_PAGES. * * - Lastly, bi_vcnt should not be looked at or relied upon by code * that does not own the bio - reason being drivers don't use it for * iterating over the biovec anymore, so expecting it to be kept up * to date (i.e. for clones that share the parent biovec) is just * asking for trouble and would force extra work on * __bio_clone_fast() anyways. */ bio = bio_alloc_bioset(gfp_mask, bio_segments(bio_src), bs); if (!bio) return NULL; bio->bi_disk = bio_src->bi_disk; bio->bi_opf = bio_src->bi_opf; bio->bi_write_hint = bio_src->bi_write_hint; bio->bi_iter.bi_sector = bio_src->bi_iter.bi_sector; bio->bi_iter.bi_size = bio_src->bi_iter.bi_size; switch (bio_op(bio)) { case REQ_OP_DISCARD: case REQ_OP_SECURE_ERASE: case REQ_OP_WRITE_ZEROES: break; case REQ_OP_WRITE_SAME: bio->bi_io_vec[bio->bi_vcnt++] = bio_src->bi_io_vec[0]; break; default: bio_for_each_segment(bv, bio_src, iter) bio->bi_io_vec[bio->bi_vcnt++] = bv; break; } if (bio_integrity(bio_src)) { int ret; ret = bio_integrity_clone(bio, bio_src, gfp_mask); if (ret < 0) { bio_put(bio); return NULL; } } bio_clone_blkcg_association(bio, bio_src); return bio; } EXPORT_SYMBOL(bio_clone_bioset); /** * bio_add_pc_page - attempt to add page to bio * @q: the target queue * @bio: destination bio * @page: page to add * @len: vec entry length * @offset: vec entry offset * * Attempt to add a page to the bio_vec maplist. This can fail for a * number of reasons, such as the bio being full or target block device * limitations. The target block device must allow bio's up to PAGE_SIZE, * so it is always possible to add a single page to an empty bio. * * This should only be used by REQ_PC bios. */ int bio_add_pc_page(struct request_queue *q, struct bio *bio, struct page *page, unsigned int len, unsigned int offset) { int retried_segments = 0; struct bio_vec *bvec; /* * cloned bio must not modify vec list */ if (unlikely(bio_flagged(bio, BIO_CLONED))) return 0; if (((bio->bi_iter.bi_size + len) >> 9) > queue_max_hw_sectors(q)) return 0; /* * For filesystems with a blocksize smaller than the pagesize * we will often be called with the same page as last time and * a consecutive offset. Optimize this special case. */ if (bio->bi_vcnt > 0) { struct bio_vec *prev = &bio->bi_io_vec[bio->bi_vcnt - 1]; if (page == prev->bv_page && offset == prev->bv_offset + prev->bv_len) { prev->bv_len += len; bio->bi_iter.bi_size += len; goto done; } /* * If the queue doesn't support SG gaps and adding this * offset would create a gap, disallow it. */ if (bvec_gap_to_prev(q, prev, offset)) return 0; } if (bio->bi_vcnt >= bio->bi_max_vecs) return 0; /* * setup the new entry, we might clear it again later if we * cannot add the page */ bvec = &bio->bi_io_vec[bio->bi_vcnt]; bvec->bv_page = page; bvec->bv_len = len; bvec->bv_offset = offset; bio->bi_vcnt++; bio->bi_phys_segments++; bio->bi_iter.bi_size += len; /* * Perform a recount if the number of segments is greater * than queue_max_segments(q). */ while (bio->bi_phys_segments > queue_max_segments(q)) { if (retried_segments) goto failed; retried_segments = 1; blk_recount_segments(q, bio); } /* If we may be able to merge these biovecs, force a recount */ if (bio->bi_vcnt > 1 && (BIOVEC_PHYS_MERGEABLE(bvec-1, bvec))) bio_clear_flag(bio, BIO_SEG_VALID); done: return len; failed: bvec->bv_page = NULL; bvec->bv_len = 0; bvec->bv_offset = 0; bio->bi_vcnt--; bio->bi_iter.bi_size -= len; blk_recount_segments(q, bio); return 0; } EXPORT_SYMBOL(bio_add_pc_page); /** * bio_add_page - attempt to add page to bio * @bio: destination bio * @page: page to add * @len: vec entry length * @offset: vec entry offset * * Attempt to add a page to the bio_vec maplist. This will only fail * if either bio->bi_vcnt == bio->bi_max_vecs or it's a cloned bio. */ int bio_add_page(struct bio *bio, struct page *page, unsigned int len, unsigned int offset) { struct bio_vec *bv; /* * cloned bio must not modify vec list */ if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED))) return 0; /* * For filesystems with a blocksize smaller than the pagesize * we will often be called with the same page as last time and * a consecutive offset. Optimize this special case. */ if (bio->bi_vcnt > 0) { bv = &bio->bi_io_vec[bio->bi_vcnt - 1]; if (page == bv->bv_page && offset == bv->bv_offset + bv->bv_len) { bv->bv_len += len; goto done; } } if (bio->bi_vcnt >= bio->bi_max_vecs) return 0; bv = &bio->bi_io_vec[bio->bi_vcnt]; bv->bv_page = page; bv->bv_len = len; bv->bv_offset = offset; bio->bi_vcnt++; done: bio->bi_iter.bi_size += len; return len; } EXPORT_SYMBOL(bio_add_page); /** * bio_iov_iter_get_pages - pin user or kernel pages and add them to a bio * @bio: bio to add pages to * @iter: iov iterator describing the region to be mapped * * Pins as many pages from *iter and appends them to @bio's bvec array. The * pages will have to be released using put_page() when done. */ int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter) { unsigned short nr_pages = bio->bi_max_vecs - bio->bi_vcnt; struct bio_vec *bv = bio->bi_io_vec + bio->bi_vcnt; struct page **pages = (struct page **)bv; size_t offset, diff; ssize_t size; size = iov_iter_get_pages(iter, pages, LONG_MAX, nr_pages, &offset); if (unlikely(size <= 0)) return size ? size : -EFAULT; nr_pages = (size + offset + PAGE_SIZE - 1) / PAGE_SIZE; /* * Deep magic below: We need to walk the pinned pages backwards * because we are abusing the space allocated for the bio_vecs * for the page array. Because the bio_vecs are larger than the * page pointers by definition this will always work. But it also * means we can't use bio_add_page, so any changes to it's semantics * need to be reflected here as well. */ bio->bi_iter.bi_size += size; bio->bi_vcnt += nr_pages; diff = (nr_pages * PAGE_SIZE - offset) - size; while (nr_pages--) { bv[nr_pages].bv_page = pages[nr_pages]; bv[nr_pages].bv_len = PAGE_SIZE; bv[nr_pages].bv_offset = 0; } bv[0].bv_offset += offset; bv[0].bv_len -= offset; if (diff) bv[bio->bi_vcnt - 1].bv_len -= diff; iov_iter_advance(iter, size); return 0; } EXPORT_SYMBOL_GPL(bio_iov_iter_get_pages); struct submit_bio_ret { struct completion event; int error; }; static void submit_bio_wait_endio(struct bio *bio) { struct submit_bio_ret *ret = bio->bi_private; ret->error = blk_status_to_errno(bio->bi_status); complete(&ret->event); } /** * submit_bio_wait - submit a bio, and wait until it completes * @bio: The &struct bio which describes the I/O * * Simple wrapper around submit_bio(). Returns 0 on success, or the error from * bio_endio() on failure. * * WARNING: Unlike to how submit_bio() is usually used, this function does not * result in bio reference to be consumed. The caller must drop the reference * on his own. */ int submit_bio_wait(struct bio *bio) { struct submit_bio_ret ret; init_completion(&ret.event); bio->bi_private = &ret; bio->bi_end_io = submit_bio_wait_endio; bio->bi_opf |= REQ_SYNC; submit_bio(bio); wait_for_completion_io(&ret.event); return ret.error; } EXPORT_SYMBOL(submit_bio_wait); /** * bio_advance - increment/complete a bio by some number of bytes * @bio: bio to advance * @bytes: number of bytes to complete * * This updates bi_sector, bi_size and bi_idx; if the number of bytes to * complete doesn't align with a bvec boundary, then bv_len and bv_offset will * be updated on the last bvec as well. * * @bio will then represent the remaining, uncompleted portion of the io. */ void bio_advance(struct bio *bio, unsigned bytes) { if (bio_integrity(bio)) bio_integrity_advance(bio, bytes); bio_advance_iter(bio, &bio->bi_iter, bytes); } EXPORT_SYMBOL(bio_advance); /** * bio_alloc_pages - allocates a single page for each bvec in a bio * @bio: bio to allocate pages for * @gfp_mask: flags for allocation * * Allocates pages up to @bio->bi_vcnt. * * Returns 0 on success, -ENOMEM on failure. On failure, any allocated pages are * freed. */ int bio_alloc_pages(struct bio *bio, gfp_t gfp_mask) { int i; struct bio_vec *bv; bio_for_each_segment_all(bv, bio, i) { bv->bv_page = alloc_page(gfp_mask); if (!bv->bv_page) { while (--bv >= bio->bi_io_vec) __free_page(bv->bv_page); return -ENOMEM; } } return 0; } EXPORT_SYMBOL(bio_alloc_pages); /** * bio_copy_data - copy contents of data buffers from one chain of bios to * another * @src: source bio list * @dst: destination bio list * * If @src and @dst are single bios, bi_next must be NULL - otherwise, treats * @src and @dst as linked lists of bios. * * Stops when it reaches the end of either @src or @dst - that is, copies * min(src->bi_size, dst->bi_size) bytes (or the equivalent for lists of bios). */ void bio_copy_data(struct bio *dst, struct bio *src) { struct bvec_iter src_iter, dst_iter; struct bio_vec src_bv, dst_bv; void *src_p, *dst_p; unsigned bytes; src_iter = src->bi_iter; dst_iter = dst->bi_iter; while (1) { if (!src_iter.bi_size) { src = src->bi_next; if (!src) break; src_iter = src->bi_iter; } if (!dst_iter.bi_size) { dst = dst->bi_next; if (!dst) break; dst_iter = dst->bi_iter; } src_bv = bio_iter_iovec(src, src_iter); dst_bv = bio_iter_iovec(dst, dst_iter); bytes = min(src_bv.bv_len, dst_bv.bv_len); src_p = kmap_atomic(src_bv.bv_page); dst_p = kmap_atomic(dst_bv.bv_page); memcpy(dst_p + dst_bv.bv_offset, src_p + src_bv.bv_offset, bytes); kunmap_atomic(dst_p); kunmap_atomic(src_p); bio_advance_iter(src, &src_iter, bytes); bio_advance_iter(dst, &dst_iter, bytes); } } EXPORT_SYMBOL(bio_copy_data); struct bio_map_data { int is_our_pages; struct iov_iter iter; struct iovec iov[]; }; static struct bio_map_data *bio_alloc_map_data(unsigned int iov_count, gfp_t gfp_mask) { if (iov_count > UIO_MAXIOV) return NULL; return kmalloc(sizeof(struct bio_map_data) + sizeof(struct iovec) * iov_count, gfp_mask); } /** * bio_copy_from_iter - copy all pages from iov_iter to bio * @bio: The &struct bio which describes the I/O as destination * @iter: iov_iter as source * * Copy all pages from iov_iter to bio. * Returns 0 on success, or error on failure. */ static int bio_copy_from_iter(struct bio *bio, struct iov_iter iter) { int i; struct bio_vec *bvec; bio_for_each_segment_all(bvec, bio, i) { ssize_t ret; ret = copy_page_from_iter(bvec->bv_page, bvec->bv_offset, bvec->bv_len, &iter); if (!iov_iter_count(&iter)) break; if (ret < bvec->bv_len) return -EFAULT; } return 0; } /** * bio_copy_to_iter - copy all pages from bio to iov_iter * @bio: The &struct bio which describes the I/O as source * @iter: iov_iter as destination * * Copy all pages from bio to iov_iter. * Returns 0 on success, or error on failure. */ static int bio_copy_to_iter(struct bio *bio, struct iov_iter iter) { int i; struct bio_vec *bvec; bio_for_each_segment_all(bvec, bio, i) { ssize_t ret; ret = copy_page_to_iter(bvec->bv_page, bvec->bv_offset, bvec->bv_len, &iter); if (!iov_iter_count(&iter)) break; if (ret < bvec->bv_len) return -EFAULT; } return 0; } void bio_free_pages(struct bio *bio) { struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) __free_page(bvec->bv_page); } EXPORT_SYMBOL(bio_free_pages); /** * bio_uncopy_user - finish previously mapped bio * @bio: bio being terminated * * Free pages allocated from bio_copy_user_iov() and write back data * to user space in case of a read. */ int bio_uncopy_user(struct bio *bio) { struct bio_map_data *bmd = bio->bi_private; int ret = 0; if (!bio_flagged(bio, BIO_NULL_MAPPED)) { /* * if we're in a workqueue, the request is orphaned, so * don't copy into a random user address space, just free * and return -EINTR so user space doesn't expect any data. */ if (!current->mm) ret = -EINTR; else if (bio_data_dir(bio) == READ) ret = bio_copy_to_iter(bio, bmd->iter); if (bmd->is_our_pages) bio_free_pages(bio); } kfree(bmd); bio_put(bio); return ret; } /** * bio_copy_user_iov - copy user data to bio * @q: destination block queue * @map_data: pointer to the rq_map_data holding pages (if necessary) * @iter: iovec iterator * @gfp_mask: memory allocation flags * * Prepares and returns a bio for indirect user io, bouncing data * to/from kernel pages as necessary. Must be paired with * call bio_uncopy_user() on io completion. */ struct bio *bio_copy_user_iov(struct request_queue *q, struct rq_map_data *map_data, const struct iov_iter *iter, gfp_t gfp_mask) { struct bio_map_data *bmd; struct page *page; struct bio *bio; int i, ret; int nr_pages = 0; unsigned int len = iter->count; unsigned int offset = map_data ? offset_in_page(map_data->offset) : 0; for (i = 0; i < iter->nr_segs; i++) { unsigned long uaddr; unsigned long end; unsigned long start; uaddr = (unsigned long) iter->iov[i].iov_base; end = (uaddr + iter->iov[i].iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT; start = uaddr >> PAGE_SHIFT; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages += end - start; } if (offset) nr_pages++; bmd = bio_alloc_map_data(iter->nr_segs, gfp_mask); if (!bmd) return ERR_PTR(-ENOMEM); /* * We need to do a deep copy of the iov_iter including the iovecs. * The caller provided iov might point to an on-stack or otherwise * shortlived one. */ bmd->is_our_pages = map_data ? 0 : 1; memcpy(bmd->iov, iter->iov, sizeof(struct iovec) * iter->nr_segs); iov_iter_init(&bmd->iter, iter->type, bmd->iov, iter->nr_segs, iter->count); ret = -ENOMEM; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) goto out_bmd; ret = 0; if (map_data) { nr_pages = 1 << map_data->page_order; i = map_data->offset / PAGE_SIZE; } while (len) { unsigned int bytes = PAGE_SIZE; bytes -= offset; if (bytes > len) bytes = len; if (map_data) { if (i == map_data->nr_entries * nr_pages) { ret = -ENOMEM; break; } page = map_data->pages[i / nr_pages]; page += (i % nr_pages); i++; } else { page = alloc_page(q->bounce_gfp | gfp_mask); if (!page) { ret = -ENOMEM; break; } } if (bio_add_pc_page(q, bio, page, bytes, offset) < bytes) break; len -= bytes; offset = 0; } if (ret) goto cleanup; /* * success */ if (((iter->type & WRITE) && (!map_data || !map_data->null_mapped)) || (map_data && map_data->from_user)) { ret = bio_copy_from_iter(bio, *iter); if (ret) goto cleanup; } bio->bi_private = bmd; return bio; cleanup: if (!map_data) bio_free_pages(bio); bio_put(bio); out_bmd: kfree(bmd); return ERR_PTR(ret); } /** * bio_map_user_iov - map user iovec into bio * @q: the struct request_queue for the bio * @iter: iovec iterator * @gfp_mask: memory allocation flags * * Map the user space address into a bio suitable for io to a block * device. Returns an error pointer in case of error. */ struct bio *bio_map_user_iov(struct request_queue *q, const struct iov_iter *iter, gfp_t gfp_mask) { int j; int nr_pages = 0; struct page **pages; struct bio *bio; int cur_page = 0; int ret, offset; struct iov_iter i; struct iovec iov; iov_for_each(iov, i, *iter) { unsigned long uaddr = (unsigned long) iov.iov_base; unsigned long len = iov.iov_len; unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = uaddr >> PAGE_SHIFT; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages += end - start; /* * buffer must be aligned to at least logical block size for now */ if (uaddr & queue_dma_alignment(q)) return ERR_PTR(-EINVAL); } if (!nr_pages) return ERR_PTR(-EINVAL); bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); ret = -ENOMEM; pages = kcalloc(nr_pages, sizeof(struct page *), gfp_mask); if (!pages) goto out; iov_for_each(iov, i, *iter) { unsigned long uaddr = (unsigned long) iov.iov_base; unsigned long len = iov.iov_len; unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = uaddr >> PAGE_SHIFT; const int local_nr_pages = end - start; const int page_limit = cur_page + local_nr_pages; ret = get_user_pages_fast(uaddr, local_nr_pages, (iter->type & WRITE) != WRITE, &pages[cur_page]); if (ret < local_nr_pages) { ret = -EFAULT; goto out_unmap; } offset = offset_in_page(uaddr); for (j = cur_page; j < page_limit; j++) { unsigned int bytes = PAGE_SIZE - offset; if (len <= 0) break; if (bytes > len) bytes = len; /* * sorry... */ if (bio_add_pc_page(q, bio, pages[j], bytes, offset) < bytes) break; len -= bytes; offset = 0; } cur_page = j; /* * release the pages we didn't map into the bio, if any */ while (j < page_limit) put_page(pages[j++]); } kfree(pages); bio_set_flag(bio, BIO_USER_MAPPED); /* * subtle -- if bio_map_user_iov() ended up bouncing a bio, * it would normally disappear when its bi_end_io is run. * however, we need it for the unmap, so grab an extra * reference to it */ bio_get(bio); return bio; out_unmap: for (j = 0; j < nr_pages; j++) { if (!pages[j]) break; put_page(pages[j]); } out: kfree(pages); bio_put(bio); return ERR_PTR(ret); } static void __bio_unmap_user(struct bio *bio) { struct bio_vec *bvec; int i; /* * make sure we dirty pages we wrote to */ bio_for_each_segment_all(bvec, bio, i) { if (bio_data_dir(bio) == READ) set_page_dirty_lock(bvec->bv_page); put_page(bvec->bv_page); } bio_put(bio); } /** * bio_unmap_user - unmap a bio * @bio: the bio being unmapped * * Unmap a bio previously mapped by bio_map_user_iov(). Must be called from * process context. * * bio_unmap_user() may sleep. */ void bio_unmap_user(struct bio *bio) { __bio_unmap_user(bio); bio_put(bio); } static void bio_map_kern_endio(struct bio *bio) { bio_put(bio); } /** * bio_map_kern - map kernel address into bio * @q: the struct request_queue for the bio * @data: pointer to buffer to map * @len: length in bytes * @gfp_mask: allocation flags for bio allocation * * Map the kernel address into a bio suitable for io to a block * device. Returns an error pointer in case of error. */ struct bio *bio_map_kern(struct request_queue *q, void *data, unsigned int len, gfp_t gfp_mask) { unsigned long kaddr = (unsigned long)data; unsigned long end = (kaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = kaddr >> PAGE_SHIFT; const int nr_pages = end - start; int offset, i; struct bio *bio; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); offset = offset_in_page(kaddr); for (i = 0; i < nr_pages; i++) { unsigned int bytes = PAGE_SIZE - offset; if (len <= 0) break; if (bytes > len) bytes = len; if (bio_add_pc_page(q, bio, virt_to_page(data), bytes, offset) < bytes) { /* we don't support partial mappings */ bio_put(bio); return ERR_PTR(-EINVAL); } data += bytes; len -= bytes; offset = 0; } bio->bi_end_io = bio_map_kern_endio; return bio; } EXPORT_SYMBOL(bio_map_kern); static void bio_copy_kern_endio(struct bio *bio) { bio_free_pages(bio); bio_put(bio); } static void bio_copy_kern_endio_read(struct bio *bio) { char *p = bio->bi_private; struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) { memcpy(p, page_address(bvec->bv_page), bvec->bv_len); p += bvec->bv_len; } bio_copy_kern_endio(bio); } /** * bio_copy_kern - copy kernel address into bio * @q: the struct request_queue for the bio * @data: pointer to buffer to copy * @len: length in bytes * @gfp_mask: allocation flags for bio and page allocation * @reading: data direction is READ * * copy the kernel address into a bio suitable for io to a block * device. Returns an error pointer in case of error. */ struct bio *bio_copy_kern(struct request_queue *q, void *data, unsigned int len, gfp_t gfp_mask, int reading) { unsigned long kaddr = (unsigned long)data; unsigned long end = (kaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = kaddr >> PAGE_SHIFT; struct bio *bio; void *p = data; int nr_pages = 0; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages = end - start; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); while (len) { struct page *page; unsigned int bytes = PAGE_SIZE; if (bytes > len) bytes = len; page = alloc_page(q->bounce_gfp | gfp_mask); if (!page) goto cleanup; if (!reading) memcpy(page_address(page), p, bytes); if (bio_add_pc_page(q, bio, page, bytes, 0) < bytes) break; len -= bytes; p += bytes; } if (reading) { bio->bi_end_io = bio_copy_kern_endio_read; bio->bi_private = data; } else { bio->bi_end_io = bio_copy_kern_endio; } return bio; cleanup: bio_free_pages(bio); bio_put(bio); return ERR_PTR(-ENOMEM); } /* * bio_set_pages_dirty() and bio_check_pages_dirty() are support functions * for performing direct-IO in BIOs. * * The problem is that we cannot run set_page_dirty() from interrupt context * because the required locks are not interrupt-safe. So what we can do is to * mark the pages dirty _before_ performing IO. And in interrupt context, * check that the pages are still dirty. If so, fine. If not, redirty them * in process context. * * We special-case compound pages here: normally this means reads into hugetlb * pages. The logic in here doesn't really work right for compound pages * because the VM does not uniformly chase down the head page in all cases. * But dirtiness of compound pages is pretty meaningless anyway: the VM doesn't * handle them at all. So we skip compound pages here at an early stage. * * Note that this code is very hard to test under normal circumstances because * direct-io pins the pages with get_user_pages(). This makes * is_page_cache_freeable return false, and the VM will not clean the pages. * But other code (eg, flusher threads) could clean the pages if they are mapped * pagecache. * * Simply disabling the call to bio_set_pages_dirty() is a good way to test the * deferred bio dirtying paths. */ /* * bio_set_pages_dirty() will mark all the bio's pages as dirty. */ void bio_set_pages_dirty(struct bio *bio) { struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) { struct page *page = bvec->bv_page; if (page && !PageCompound(page)) set_page_dirty_lock(page); } } static void bio_release_pages(struct bio *bio) { struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) { struct page *page = bvec->bv_page; if (page) put_page(page); } } /* * bio_check_pages_dirty() will check that all the BIO's pages are still dirty. * If they are, then fine. If, however, some pages are clean then they must * have been written out during the direct-IO read. So we take another ref on * the BIO and the offending pages and re-dirty the pages in process context. * * It is expected that bio_check_pages_dirty() will wholly own the BIO from * here on. It will run one put_page() against each page and will run one * bio_put() against the BIO. */ static void bio_dirty_fn(struct work_struct *work); static DECLARE_WORK(bio_dirty_work, bio_dirty_fn); static DEFINE_SPINLOCK(bio_dirty_lock); static struct bio *bio_dirty_list; /* * This runs in process context */ static void bio_dirty_fn(struct work_struct *work) { unsigned long flags; struct bio *bio; spin_lock_irqsave(&bio_dirty_lock, flags); bio = bio_dirty_list; bio_dirty_list = NULL; spin_unlock_irqrestore(&bio_dirty_lock, flags); while (bio) { struct bio *next = bio->bi_private; bio_set_pages_dirty(bio); bio_release_pages(bio); bio_put(bio); bio = next; } } void bio_check_pages_dirty(struct bio *bio) { struct bio_vec *bvec; int nr_clean_pages = 0; int i; bio_for_each_segment_all(bvec, bio, i) { struct page *page = bvec->bv_page; if (PageDirty(page) || PageCompound(page)) { put_page(page); bvec->bv_page = NULL; } else { nr_clean_pages++; } } if (nr_clean_pages) { unsigned long flags; spin_lock_irqsave(&bio_dirty_lock, flags); bio->bi_private = bio_dirty_list; bio_dirty_list = bio; spin_unlock_irqrestore(&bio_dirty_lock, flags); schedule_work(&bio_dirty_work); } else { bio_put(bio); } } void generic_start_io_acct(struct request_queue *q, int rw, unsigned long sectors, struct hd_struct *part) { int cpu = part_stat_lock(); part_round_stats(q, cpu, part); part_stat_inc(cpu, part, ios[rw]); part_stat_add(cpu, part, sectors[rw], sectors); part_inc_in_flight(q, part, rw); part_stat_unlock(); } EXPORT_SYMBOL(generic_start_io_acct); void generic_end_io_acct(struct request_queue *q, int rw, struct hd_struct *part, unsigned long start_time) { unsigned long duration = jiffies - start_time; int cpu = part_stat_lock(); part_stat_add(cpu, part, ticks[rw], duration); part_round_stats(q, cpu, part); part_dec_in_flight(q, part, rw); part_stat_unlock(); } EXPORT_SYMBOL(generic_end_io_acct); #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE void bio_flush_dcache_pages(struct bio *bi) { struct bio_vec bvec; struct bvec_iter iter; bio_for_each_segment(bvec, bi, iter) flush_dcache_page(bvec.bv_page); } EXPORT_SYMBOL(bio_flush_dcache_pages); #endif static inline bool bio_remaining_done(struct bio *bio) { /* * If we're not chaining, then ->__bi_remaining is always 1 and * we always end io on the first invocation. */ if (!bio_flagged(bio, BIO_CHAIN)) return true; BUG_ON(atomic_read(&bio->__bi_remaining) <= 0); if (atomic_dec_and_test(&bio->__bi_remaining)) { bio_clear_flag(bio, BIO_CHAIN); return true; } return false; } /** * bio_endio - end I/O on a bio * @bio: bio * * Description: * bio_endio() will end I/O on the whole bio. bio_endio() is the preferred * way to end I/O on a bio. No one should call bi_end_io() directly on a * bio unless they own it and thus know that it has an end_io function. * * bio_endio() can be called several times on a bio that has been chained * using bio_chain(). The ->bi_end_io() function will only be called the * last time. At this point the BLK_TA_COMPLETE tracing event will be * generated if BIO_TRACE_COMPLETION is set. **/ void bio_endio(struct bio *bio) { again: if (!bio_remaining_done(bio)) return; if (!bio_integrity_endio(bio)) return; /* * Need to have a real endio function for chained bios, otherwise * various corner cases will break (like stacking block devices that * save/restore bi_end_io) - however, we want to avoid unbounded * recursion and blowing the stack. Tail call optimization would * handle this, but compiling with frame pointers also disables * gcc's sibling call optimization. */ if (bio->bi_end_io == bio_chain_endio) { bio = __bio_chain_endio(bio); goto again; } if (bio->bi_disk && bio_flagged(bio, BIO_TRACE_COMPLETION)) { trace_block_bio_complete(bio->bi_disk->queue, bio, blk_status_to_errno(bio->bi_status)); bio_clear_flag(bio, BIO_TRACE_COMPLETION); } blk_throtl_bio_endio(bio); /* release cgroup info */ bio_uninit(bio); if (bio->bi_end_io) bio->bi_end_io(bio); } EXPORT_SYMBOL(bio_endio); /** * bio_split - split a bio * @bio: bio to split * @sectors: number of sectors to split from the front of @bio * @gfp: gfp mask * @bs: bio set to allocate from * * Allocates and returns a new bio which represents @sectors from the start of * @bio, and updates @bio to represent the remaining sectors. * * Unless this is a discard request the newly allocated bio will point * to @bio's bi_io_vec; it is the caller's responsibility to ensure that * @bio is not freed before the split. */ struct bio *bio_split(struct bio *bio, int sectors, gfp_t gfp, struct bio_set *bs) { struct bio *split = NULL; BUG_ON(sectors <= 0); BUG_ON(sectors >= bio_sectors(bio)); split = bio_clone_fast(bio, gfp, bs); if (!split) return NULL; split->bi_iter.bi_size = sectors << 9; if (bio_integrity(split)) bio_integrity_trim(split); bio_advance(bio, split->bi_iter.bi_size); if (bio_flagged(bio, BIO_TRACE_COMPLETION)) bio_set_flag(bio, BIO_TRACE_COMPLETION); return split; } EXPORT_SYMBOL(bio_split); /** * bio_trim - trim a bio * @bio: bio to trim * @offset: number of sectors to trim from the front of @bio * @size: size we want to trim @bio to, in sectors */ void bio_trim(struct bio *bio, int offset, int size) { /* 'bio' is a cloned bio which we need to trim to match * the given offset and size. */ size <<= 9; if (offset == 0 && size == bio->bi_iter.bi_size) return; bio_clear_flag(bio, BIO_SEG_VALID); bio_advance(bio, offset << 9); bio->bi_iter.bi_size = size; if (bio_integrity(bio)) bio_integrity_trim(bio); } EXPORT_SYMBOL_GPL(bio_trim); /* * create memory pools for biovec's in a bio_set. * use the global biovec slabs created for general use. */ mempool_t *biovec_create_pool(int pool_entries) { struct biovec_slab *bp = bvec_slabs + BVEC_POOL_MAX; return mempool_create_slab_pool(pool_entries, bp->slab); } void bioset_free(struct bio_set *bs) { if (bs->rescue_workqueue) destroy_workqueue(bs->rescue_workqueue); if (bs->bio_pool) mempool_destroy(bs->bio_pool); if (bs->bvec_pool) mempool_destroy(bs->bvec_pool); bioset_integrity_free(bs); bio_put_slab(bs); kfree(bs); } EXPORT_SYMBOL(bioset_free); /** * bioset_create - Create a bio_set * @pool_size: Number of bio and bio_vecs to cache in the mempool * @front_pad: Number of bytes to allocate in front of the returned bio * @flags: Flags to modify behavior, currently %BIOSET_NEED_BVECS * and %BIOSET_NEED_RESCUER * * Description: * Set up a bio_set to be used with @bio_alloc_bioset. Allows the caller * to ask for a number of bytes to be allocated in front of the bio. * Front pad allocation is useful for embedding the bio inside * another structure, to avoid allocating extra data to go with the bio. * Note that the bio must be embedded at the END of that structure always, * or things will break badly. * If %BIOSET_NEED_BVECS is set in @flags, a separate pool will be allocated * for allocating iovecs. This pool is not needed e.g. for bio_clone_fast(). * If %BIOSET_NEED_RESCUER is set, a workqueue is created which can be used to * dispatch queued requests when the mempool runs out of space. * */ struct bio_set *bioset_create(unsigned int pool_size, unsigned int front_pad, int flags) { unsigned int back_pad = BIO_INLINE_VECS * sizeof(struct bio_vec); struct bio_set *bs; bs = kzalloc(sizeof(*bs), GFP_KERNEL); if (!bs) return NULL; bs->front_pad = front_pad; spin_lock_init(&bs->rescue_lock); bio_list_init(&bs->rescue_list); INIT_WORK(&bs->rescue_work, bio_alloc_rescue); bs->bio_slab = bio_find_or_create_slab(front_pad + back_pad); if (!bs->bio_slab) { kfree(bs); return NULL; } bs->bio_pool = mempool_create_slab_pool(pool_size, bs->bio_slab); if (!bs->bio_pool) goto bad; if (flags & BIOSET_NEED_BVECS) { bs->bvec_pool = biovec_create_pool(pool_size); if (!bs->bvec_pool) goto bad; } if (!(flags & BIOSET_NEED_RESCUER)) return bs; bs->rescue_workqueue = alloc_workqueue("bioset", WQ_MEM_RECLAIM, 0); if (!bs->rescue_workqueue) goto bad; return bs; bad: bioset_free(bs); return NULL; } EXPORT_SYMBOL(bioset_create); #ifdef CONFIG_BLK_CGROUP /** * bio_associate_blkcg - associate a bio with the specified blkcg * @bio: target bio * @blkcg_css: css of the blkcg to associate * * Associate @bio with the blkcg specified by @blkcg_css. Block layer will * treat @bio as if it were issued by a task which belongs to the blkcg. * * This function takes an extra reference of @blkcg_css which will be put * when @bio is released. The caller must own @bio and is responsible for * synchronizing calls to this function. */ int bio_associate_blkcg(struct bio *bio, struct cgroup_subsys_state *blkcg_css) { if (unlikely(bio->bi_css)) return -EBUSY; css_get(blkcg_css); bio->bi_css = blkcg_css; return 0; } EXPORT_SYMBOL_GPL(bio_associate_blkcg); /** * bio_associate_current - associate a bio with %current * @bio: target bio * * Associate @bio with %current if it hasn't been associated yet. Block * layer will treat @bio as if it were issued by %current no matter which * task actually issues it. * * This function takes an extra reference of @task's io_context and blkcg * which will be put when @bio is released. The caller must own @bio, * ensure %current->io_context exists, and is responsible for synchronizing * calls to this function. */ int bio_associate_current(struct bio *bio) { struct io_context *ioc; if (bio->bi_css) return -EBUSY; ioc = current->io_context; if (!ioc) return -ENOENT; get_io_context_active(ioc); bio->bi_ioc = ioc; bio->bi_css = task_get_css(current, io_cgrp_id); return 0; } EXPORT_SYMBOL_GPL(bio_associate_current); /** * bio_disassociate_task - undo bio_associate_current() * @bio: target bio */ void bio_disassociate_task(struct bio *bio) { if (bio->bi_ioc) { put_io_context(bio->bi_ioc); bio->bi_ioc = NULL; } if (bio->bi_css) { css_put(bio->bi_css); bio->bi_css = NULL; } } /** * bio_clone_blkcg_association - clone blkcg association from src to dst bio * @dst: destination bio * @src: source bio */ void bio_clone_blkcg_association(struct bio *dst, struct bio *src) { if (src->bi_css) WARN_ON(bio_associate_blkcg(dst, src->bi_css)); } EXPORT_SYMBOL_GPL(bio_clone_blkcg_association); #endif /* CONFIG_BLK_CGROUP */ static void __init biovec_init_slabs(void) { int i; for (i = 0; i < BVEC_POOL_NR; i++) { int size; struct biovec_slab *bvs = bvec_slabs + i; if (bvs->nr_vecs <= BIO_INLINE_VECS) { bvs->slab = NULL; continue; } size = bvs->nr_vecs * sizeof(struct bio_vec); bvs->slab = kmem_cache_create(bvs->name, size, 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); } } static int __init init_bio(void) { bio_slab_max = 2; bio_slab_nr = 0; bio_slabs = kzalloc(bio_slab_max * sizeof(struct bio_slab), GFP_KERNEL); if (!bio_slabs) panic("bio: can't allocate bios\n"); bio_integrity_init(); biovec_init_slabs(); fs_bio_set = bioset_create(BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS); if (!fs_bio_set) panic("bio: can't allocate bios\n"); if (bioset_integrity_create(fs_bio_set, BIO_POOL_SIZE)) panic("bio: can't create integrity pool\n"); return 0; } subsys_initcall(init_bio);
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2604_0
crossvul-cpp_data_good_2623_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % JJJ PPPP 222 % % J P P 2 2 % % J PPPP 22 % % J J P 2 % % JJ P 22222 % % % % % % Read/Write JPEG-2000 Image Format % % % % Cristy % % Nathan Brown % % June 2001 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/semaphore.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/module.h" #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) #include <openjpeg.h> #endif /* Forward declarations. */ #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) static MagickBooleanType WriteJP2Image(const ImageInfo *,Image *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J 2 K % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJ2K() returns MagickTrue if the image format type, identified by the % magick string, is J2K. % % The format of the IsJ2K method is: % % MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\xff\x4f\xff\x51",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J P 2 % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJP2() returns MagickTrue if the image format type, identified by the % magick string, is JP2. % % The format of the IsJP2 method is: % % MagickBooleanType IsJP2(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsJP2(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\x0d\x0a\x87\x0a",4) == 0) return(MagickTrue); if (length < 12) return(MagickFalse); if (memcmp(magick,"\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a",12) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJP2Image() reads a JPEG 2000 Image file (JP2) or JPEG 2000 % codestream (JPC) image file and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image or set of images. % % JP2 support is originally written by Nathan Brown, nathanbrown@letu.edu. % % The format of the ReadJP2Image method is: % % Image *ReadJP2Image(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) static void JP2ErrorHandler(const char *message,void *client_data) { ExceptionInfo *exception; exception=(ExceptionInfo *) client_data; (void) ThrowMagickException(exception,GetMagickModule(),CoderError, message,"`%s'","OpenJP2"); } static OPJ_SIZE_T JP2ReadHandler(void *buffer,OPJ_SIZE_T length,void *context) { Image *image; ssize_t count; image=(Image *) context; count=ReadBlob(image,(ssize_t) length,(unsigned char *) buffer); if (count == 0) return((OPJ_SIZE_T) -1); return((OPJ_SIZE_T) count); } static OPJ_BOOL JP2SeekHandler(OPJ_OFF_T offset,void *context) { Image *image; image=(Image *) context; return(SeekBlob(image,offset,SEEK_SET) < 0 ? OPJ_FALSE : OPJ_TRUE); } static OPJ_OFF_T JP2SkipHandler(OPJ_OFF_T offset,void *context) { Image *image; image=(Image *) context; return(SeekBlob(image,offset,SEEK_CUR) < 0 ? -1 : offset); } static void JP2WarningHandler(const char *message,void *client_data) { ExceptionInfo *exception; exception=(ExceptionInfo *) client_data; (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'","OpenJP2"); } static OPJ_SIZE_T JP2WriteHandler(void *buffer,OPJ_SIZE_T length,void *context) { Image *image; ssize_t count; image=(Image *) context; count=WriteBlob(image,(ssize_t) length,(unsigned char *) buffer); return((OPJ_SIZE_T) count); } static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) { const char *option; Image *image; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; opj_codestream_index_t *codestream_index = (opj_codestream_index_t *) NULL; opj_dparameters_t parameters; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned char sans[4]; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize JP2 codec. */ if (ReadBlob(image,4,sans) != 4) { image=DestroyImageList(image); return((Image *) NULL); } (void) SeekBlob(image,SEEK_SET,0); if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_decompress(OPJ_CODEC_JPT); else if (IsJ2K(sans,4) != MagickFalse) jp2_codec=opj_create_decompress(OPJ_CODEC_J2K); else jp2_codec=opj_create_decompress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception); opj_set_default_decoder_parameters(&parameters); option=GetImageOption(image_info,"jp2:reduce-factor"); if (option != (const char *) NULL) parameters.cp_reduce=StringToInteger(option); option=GetImageOption(image_info,"jp2:quality-layers"); if (option == (const char *) NULL) option=GetImageOption(image_info,"jp2:layer-number"); if (option != (const char *) NULL) parameters.cp_layer=StringToInteger(option); if (opj_setup_decoder(jp2_codec,&parameters) == 0) { opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToManageJP2Stream"); } jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image)); if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } jp2_status=1; if ((image->columns != 0) && (image->rows != 0)) { /* Extract an area from the image. */ jp2_status=opj_set_decode_area(jp2_codec,jp2_image, (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y, (OPJ_INT32) image->extract_info.x+(ssize_t) image->columns, (OPJ_INT32) image->extract_info.y+(ssize_t) image->rows); if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } } if ((image_info->number_scenes != 0) && (image_info->scene != 0)) jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image, (unsigned int) image_info->scene-1); else if (image->ping == MagickFalse) { jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image); if (jp2_status != 0) jp2_status=opj_end_decompress(jp2_codec,jp2_stream); } if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } opj_stream_destroy(jp2_stream); for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) || (jp2_image->comps[0].dx != jp2_image->comps[i].dx) || (jp2_image->comps[0].dy != jp2_image->comps[i].dy) || (jp2_image->comps[0].prec != jp2_image->comps[i].prec) || (jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd) || ((image->ping == MagickFalse) && (jp2_image->comps[i].data == NULL))) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported") } } /* Convert JP2 image. */ image->columns=(size_t) jp2_image->comps[0].w; image->rows=(size_t) jp2_image->comps[0].h; image->depth=jp2_image->comps[0].prec; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } image->compression=JPEG2000Compression; if (jp2_image->color_space == 2) { SetImageColorspace(image,GRAYColorspace); if (jp2_image->numcomps > 1) image->matte=MagickTrue; } else if (jp2_image->color_space == 3) SetImageColorspace(image,Rec601YCbCrColorspace); if (jp2_image->numcomps > 3) image->matte=MagickTrue; if (jp2_image->icc_profile_buf != (unsigned char *) NULL) { StringInfo *profile; profile=BlobToStringInfo(jp2_image->icc_profile_buf, jp2_image->icc_profile_len); if (profile != (StringInfo *) NULL) SetImageProfile(image,"icc",profile); } if (image->ping != MagickFalse) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); return(GetFirstImageInList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { double pixel, scale; scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1); pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+ (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0)); switch (i) { case 0: { q->red=ClampToQuantum(pixel); q->green=q->red; q->blue=q->red; q->opacity=OpaqueOpacity; break; } case 1: { if (jp2_image->numcomps == 2) { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } q->green=ClampToQuantum(pixel); break; } case 2: { q->blue=ClampToQuantum(pixel); break; } case 3: { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } /* Free resources. */ opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterJP2Image() adds attributes for the JP2 image format to the list of % supported formats. The attributes include the image format tag, a method % method to read and/or write the format, whether the format supports the % saving of more than one frame to the same file or blob, whether the format % supports native in-memory I/O, and a brief description of the format. % % The format of the RegisterJP2Image method is: % % size_t RegisterJP2Image(void) % */ ModuleExport size_t RegisterJP2Image(void) { char version[MaxTextExtent]; MagickInfo *entry; *version='\0'; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) (void) FormatLocaleString(version,MaxTextExtent,"%s",opj_version()); #endif entry=SetMagickInfo("JP2"); entry->description=ConstantString("JPEG-2000 File Format Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJP2; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("J2C"); entry->description=ConstantString("JPEG-2000 Code Stream Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJ2K; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("J2K"); entry->description=ConstantString("JPEG-2000 Code Stream Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJ2K; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPM"); entry->description=ConstantString("JPEG-2000 Code Stream Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJP2; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPT"); entry->description=ConstantString("JPEG-2000 File Format Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJP2; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPC"); entry->description=ConstantString("JPEG-2000 Code Stream Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJP2; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterJP2Image() removes format registrations made by the JP2 module % from the list of supported formats. % % The format of the UnregisterJP2Image method is: % % UnregisterJP2Image(void) % */ ModuleExport void UnregisterJP2Image(void) { (void) UnregisterMagickInfo("JPC"); (void) UnregisterMagickInfo("JPT"); (void) UnregisterMagickInfo("JPM"); (void) UnregisterMagickInfo("JP2"); (void) UnregisterMagickInfo("J2K"); } #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJP2Image() writes an image in the JPEG 2000 image format. % % JP2 support originally written by Nathan Brown, nathanbrown@letu.edu % % The format of the WriteJP2Image method is: % % MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static void CinemaProfileCompliance(const opj_image_t *jp2_image, opj_cparameters_t *parameters) { /* Digital Cinema 4K profile compliant codestream. */ parameters->tile_size_on=OPJ_FALSE; parameters->cp_tdx=1; parameters->cp_tdy=1; parameters->tp_flag='C'; parameters->tp_on=1; parameters->cp_tx0=0; parameters->cp_ty0=0; parameters->image_offset_x0=0; parameters->image_offset_y0=0; parameters->cblockw_init=32; parameters->cblockh_init=32; parameters->csty|=0x01; parameters->prog_order=OPJ_CPRL; parameters->roi_compno=(-1); parameters->subsampling_dx=1; parameters->subsampling_dy=1; parameters->irreversible=1; if ((jp2_image->comps[0].w == 2048) || (jp2_image->comps[0].h == 1080)) { /* Digital Cinema 2K. */ parameters->cp_cinema=OPJ_CINEMA2K_24; parameters->cp_rsiz=OPJ_CINEMA2K; parameters->max_comp_size=1041666; if (parameters->numresolution > 6) parameters->numresolution=6; } if ((jp2_image->comps[0].w == 4096) || (jp2_image->comps[0].h == 2160)) { /* Digital Cinema 4K. */ parameters->cp_cinema=OPJ_CINEMA4K_24; parameters->cp_rsiz=OPJ_CINEMA4K; parameters->max_comp_size=1041666; if (parameters->numresolution < 1) parameters->numresolution=1; if (parameters->numresolution > 7) parameters->numresolution=7; parameters->numpocs=2; parameters->POC[0].tile=1; parameters->POC[0].resno0=0; parameters->POC[0].compno0=0; parameters->POC[0].layno1=1; parameters->POC[0].resno1=parameters->numresolution-1; parameters->POC[0].compno1=3; parameters->POC[0].prg1=OPJ_CPRL; parameters->POC[1].tile=1; parameters->POC[1].resno0=parameters->numresolution-1; parameters->POC[1].compno0=0; parameters->POC[1].layno1=1; parameters->POC[1].resno1=parameters->numresolution; parameters->POC[1].compno1=3; parameters->POC[1].prg1=OPJ_CPRL; } parameters->tcp_numlayers=1; parameters->tcp_rates[0]=((float) (jp2_image->numcomps*jp2_image->comps[0].w* jp2_image->comps[0].h*jp2_image->comps[0].prec))/(parameters->max_comp_size* 8*jp2_image->comps[0].dx*jp2_image->comps[0].dy); parameters->cp_disto_alloc=1; } static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image) { const char *option, *property; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; OPJ_COLOR_SPACE jp2_colorspace; opj_cparameters_t parameters; opj_image_cmptparm_t jp2_info[5]; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned int channels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Initialize JPEG 2000 encoder parameters. */ opj_set_default_encoder_parameters(&parameters); for (i=1; i < 6; i++) if (((size_t) (1 << (i+2)) > image->columns) && ((size_t) (1 << (i+2)) > image->rows)) break; parameters.numresolution=i; option=GetImageOption(image_info,"jp2:number-resolutions"); if (option != (const char *) NULL) parameters.numresolution=StringToInteger(option); parameters.tcp_numlayers=1; parameters.tcp_rates[0]=0; /* lossless */ parameters.cp_disto_alloc=1; if ((image_info->quality != 0) && (image_info->quality != 100)) { parameters.tcp_distoratio[0]=(double) image_info->quality; parameters.cp_fixed_quality=OPJ_TRUE; } if (image_info->extract != (char *) NULL) { RectangleInfo geometry; int flags; /* Set tile size. */ flags=ParseAbsoluteGeometry(image_info->extract,&geometry); parameters.cp_tdx=(int) geometry.width; parameters.cp_tdy=(int) geometry.width; if ((flags & HeightValue) != 0) parameters.cp_tdy=(int) geometry.height; if ((flags & XValue) != 0) parameters.cp_tx0=geometry.x; if ((flags & YValue) != 0) parameters.cp_ty0=geometry.y; parameters.tile_size_on=OPJ_TRUE; } option=GetImageOption(image_info,"jp2:quality"); if (option != (const char *) NULL) { register const char *p; /* Set quality PSNR. */ p=option; for (i=0; sscanf(p,"%f",&parameters.tcp_distoratio[i]) == 1; i++) { if (i >= 100) break; while ((*p != '\0') && (*p != ',')) p++; if (*p == '\0') break; p++; } parameters.tcp_numlayers=i+1; parameters.cp_fixed_quality=OPJ_TRUE; } option=GetImageOption(image_info,"jp2:progression-order"); if (option != (const char *) NULL) { if (LocaleCompare(option,"LRCP") == 0) parameters.prog_order=OPJ_LRCP; if (LocaleCompare(option,"RLCP") == 0) parameters.prog_order=OPJ_RLCP; if (LocaleCompare(option,"RPCL") == 0) parameters.prog_order=OPJ_RPCL; if (LocaleCompare(option,"PCRL") == 0) parameters.prog_order=OPJ_PCRL; if (LocaleCompare(option,"CPRL") == 0) parameters.prog_order=OPJ_CPRL; } option=GetImageOption(image_info,"jp2:rate"); if (option != (const char *) NULL) { register const char *p; /* Set compression rate. */ p=option; for (i=0; sscanf(p,"%f",&parameters.tcp_rates[i]) == 1; i++) { if (i > 100) break; while ((*p != '\0') && (*p != ',')) p++; if (*p == '\0') break; p++; } parameters.tcp_numlayers=i+1; parameters.cp_disto_alloc=OPJ_TRUE; } if (image_info->sampling_factor != (const char *) NULL) (void) sscanf(image_info->sampling_factor,"%d,%d", &parameters.subsampling_dx,&parameters.subsampling_dy); property=GetImageProperty(image,"comment"); if (property != (const char *) NULL) parameters.cp_comment=(char *) property; channels=3; jp2_colorspace=OPJ_CLRSPC_SRGB; if (image->colorspace == YUVColorspace) { jp2_colorspace=OPJ_CLRSPC_SYCC; parameters.subsampling_dx=2; } else { if (IsGrayColorspace(image->colorspace) != MagickFalse) { channels=1; jp2_colorspace=OPJ_CLRSPC_GRAY; } else (void) TransformImageColorspace(image,sRGBColorspace); if (image->matte != MagickFalse) channels++; } parameters.tcp_mct=channels == 3 ? 1 : 0; ResetMagickMemory(jp2_info,0,sizeof(jp2_info)); for (i=0; i < (ssize_t) channels; i++) { jp2_info[i].prec=(unsigned int) image->depth; jp2_info[i].bpp=(unsigned int) image->depth; if ((image->depth == 1) && ((LocaleCompare(image_info->magick,"JPT") == 0) || (LocaleCompare(image_info->magick,"JP2") == 0))) { jp2_info[i].prec++; /* OpenJPEG returns exception for depth @ 1 */ jp2_info[i].bpp++; } jp2_info[i].sgnd=0; jp2_info[i].dx=parameters.subsampling_dx; jp2_info[i].dy=parameters.subsampling_dy; jp2_info[i].w=(unsigned int) image->columns; jp2_info[i].h=(unsigned int) image->rows; } jp2_image=opj_image_create(channels,jp2_info,jp2_colorspace); if (jp2_image == (opj_image_t *) NULL) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); jp2_image->x0=parameters.image_offset_x0; jp2_image->y0=parameters.image_offset_y0; jp2_image->x1=(unsigned int) (2*parameters.image_offset_x0+(image->columns-1)* parameters.subsampling_dx+1); jp2_image->y1=(unsigned int) (2*parameters.image_offset_y0+(image->rows-1)* parameters.subsampling_dx+1); if ((image->depth == 12) && ((image->columns == 2048) || (image->rows == 1080) || (image->columns == 4096) || (image->rows == 2160))) CinemaProfileCompliance(jp2_image,&parameters); if (channels == 4) jp2_image->comps[3].alpha=1; else if ((channels == 2) && (jp2_colorspace == OPJ_CLRSPC_GRAY)) jp2_image->comps[1].alpha=1; /* Convert to JP2 pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *p; ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) channels; i++) { double scale; register int *q; scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange; q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx); switch (i) { case 0: { if (jp2_colorspace == OPJ_CLRSPC_GRAY) { *q=(int) (scale*GetPixelLuma(image,p)); break; } *q=(int) (scale*p->red); break; } case 1: { if (jp2_colorspace == OPJ_CLRSPC_GRAY) { *q=(int) (scale*(QuantumRange-p->opacity)); break; } *q=(int) (scale*p->green); break; } case 2: { *q=(int) (scale*p->blue); break; } case 3: { *q=(int) (scale*(QuantumRange-p->opacity)); break; } } } p++; } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_compress(OPJ_CODEC_JPT); else if (LocaleCompare(image_info->magick,"J2K") == 0) jp2_codec=opj_create_compress(OPJ_CODEC_J2K); else jp2_codec=opj_create_compress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,&image->exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,&image->exception); opj_setup_encoder(jp2_codec,&parameters,jp2_image); jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); if (jp2_stream == (opj_stream_t *) NULL) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream); if (jp2_status == 0) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); if ((opj_encode(jp2_codec,jp2_stream) == 0) || (opj_end_compress(jp2_codec,jp2_stream) == 0)) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); } /* Free resources. */ opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); (void) CloseBlob(image); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-772/c/good_2623_1
crossvul-cpp_data_good_1168_2
/* LodePNG version 20140823 Copyright (c) 2005-2014 Lode Vandevenne This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* Copyright (c) 2015 Armin Novak * Modifications fixing various errors. */ #include "lodepng.h" #include <winpr/wtypes.h> #include <stdio.h> #include <stdlib.h> #define VERSION_STRING "20140823" #if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/ #pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/ #pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/ #endif /*_MSC_VER */ /* This source file is built up in the following large parts. The code sections with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way. -Tools for C and common code for PNG and Zlib -C Code for Zlib (huffman, deflate, ...) -C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...) -The C++ wrapper around all of the above */ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ /* // Tools for C, and common code for PNG and Zlib. // */ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ /* Often in case of an error a value is assigned to a variable and then it breaks out of a loop (to go to the cleanup phase of a function). This macro does that. It makes the error handling code shorter and more readable. Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83); */ #define CERROR_BREAK(errorvar, code)\ {\ errorvar = code;\ break;\ } /*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/ #define ERROR_BREAK(code) CERROR_BREAK(error, code) /*Set error var to the error code, and return it.*/ #define CERROR_RETURN_ERROR(errorvar, code)\ {\ errorvar = code;\ return code;\ } /*Try the code, if it returns error, also return the error.*/ #define CERROR_TRY_RETURN(call)\ {\ unsigned error = call;\ if(error) return error;\ } /* About uivector, ucvector and string: -All of them wrap dynamic arrays or text strings in a similar way. -LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version. -The string tools are made to avoid problems with compilers that declare things like strncat as deprecated. -They're not used in the interface, only internally in this file as static functions. -As with many other structs in this file, the init and cleanup functions serve as ctor and dtor. */ #ifdef LODEPNG_COMPILE_ZLIB /*dynamic vector of unsigned ints*/ typedef struct uivector { unsigned* data; size_t size; /*size in number of unsigned longs*/ size_t allocsize; /*allocated size in bytes*/ } uivector; static void uivector_cleanup(void* p) { ((uivector*)p)->size = ((uivector*)p)->allocsize = 0; free(((uivector*)p)->data); ((uivector*)p)->data = NULL; } /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned uivector_reserve(uivector* p, size_t allocsize) { if(allocsize > p->allocsize) { size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); void* data = realloc(p->data, newsize); if(data) { memset(&((char*)data)[p->allocsize], 0, newsize - p->allocsize); p->allocsize = newsize; p->data = (unsigned*)data; } else { uivector_cleanup(p); return 0; /*error: not enough memory*/ } } return 1; } /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned uivector_resize(uivector* p, size_t size) { if(!uivector_reserve(p, size * sizeof(unsigned))) return 0; p->size = size; return 1; /*success*/ } /*resize and give all new elements the value*/ static unsigned uivector_resizev(uivector* p, size_t size, unsigned value) { size_t oldsize = p->size, i; if(!uivector_resize(p, size)) return 0; for(i = oldsize; i < size; i++) p->data[i] = value; return 1; } static void uivector_init(uivector* p) { p->data = NULL; p->size = p->allocsize = 0; } #ifdef LODEPNG_COMPILE_ENCODER /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned uivector_push_back(uivector* p, unsigned c) { if(!uivector_resize(p, p->size + 1)) return 0; p->data[p->size - 1] = c; return 1; } /*copy q to p, returns 1 if success, 0 if failure ==> nothing done*/ static unsigned uivector_copy(uivector* p, const uivector* q) { size_t i; if(!uivector_resize(p, q->size)) return 0; for(i = 0; i < q->size; i++) p->data[i] = q->data[i]; return 1; } #endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ZLIB*/ /* /////////////////////////////////////////////////////////////////////////// */ /*dynamic vector of unsigned chars*/ typedef struct ucvector { unsigned char* data; size_t size; /*used size*/ size_t allocsize; /*allocated size*/ } ucvector; static void ucvector_cleanup(void* p) { ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0; free(((ucvector*)p)->data); ((ucvector*)p)->data = NULL; } /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned ucvector_reserve(ucvector* p, size_t allocsize) { if(allocsize > p->allocsize) { size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); void* data = realloc(p->data, newsize); if(data) { p->allocsize = newsize; p->data = (unsigned char*)data; } else { ucvector_cleanup(p); return 0; /*error: not enough memory*/ } } return 1; } /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned ucvector_resize(ucvector* p, size_t size) { if(!ucvector_reserve(p, size * sizeof(unsigned char))) return 0; p->size = size; return 1; /*success*/ } #ifdef LODEPNG_COMPILE_PNG static void ucvector_init(ucvector* p) { p->data = NULL; p->size = p->allocsize = 0; } #ifdef LODEPNG_COMPILE_DECODER /*resize and give all new elements the value*/ static unsigned ucvector_resizev(ucvector* p, size_t size, unsigned char value) { size_t oldsize = p->size, i; if(!ucvector_resize(p, size)) return 0; for(i = oldsize; i < size; i++) p->data[i] = value; return 1; } #endif /*LODEPNG_COMPILE_DECODER*/ #endif /*LODEPNG_COMPILE_PNG*/ #ifdef LODEPNG_COMPILE_ZLIB /*you can both convert from vector to buffer&size and vica versa. If you use init_buffer to take over a buffer and size, it is not needed to use cleanup*/ static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size) { p->data = buffer; p->allocsize = p->size = size; } #endif /*LODEPNG_COMPILE_ZLIB*/ #if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER) /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned ucvector_push_back(ucvector* p, unsigned char c) { if(!ucvector_resize(p, p->size + 1)) return 0; p->data[p->size - 1] = c; return 1; } #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_PNG #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*free the above pair again*/ static void string_cleanup(char** out) { free(*out); *out = NULL; } /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned string_resize(char** out, size_t size) { char* data = (char*)realloc(*out, size + 1); if(data) { data[size] = 0; /*null termination char*/ *out = data; } else string_cleanup(out); return data != 0; } /*init a {char*, size_t} pair for use as string*/ static void string_init(char** out) { *out = NULL; string_resize(out, 0); } static void string_set(char** out, const char* in) { size_t insize = strlen(in), i = 0; if(string_resize(out, insize)) { for(i = 0; i < insize; i++) { (*out)[i] = in[i]; } } } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ #endif /*LODEPNG_COMPILE_PNG*/ /* ////////////////////////////////////////////////////////////////////////// */ unsigned lodepng_read32bitInt(const unsigned char* buffer) { return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); } #if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER) /*buffer must have at least 4 allocated bytes available*/ static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) { buffer[0] = (unsigned char)((value >> 24) & 0xff); buffer[1] = (unsigned char)((value >> 16) & 0xff); buffer[2] = (unsigned char)((value >> 8) & 0xff); buffer[3] = (unsigned char)((value ) & 0xff); } #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ #ifdef LODEPNG_COMPILE_ENCODER static int lodepng_add32bitInt(ucvector* buffer, unsigned value) { if (!ucvector_resize(buffer, buffer->size + 4)) return 0; lodepng_set32bitInt(&buffer->data[buffer->size - 4], value); return 1; } #endif /*LODEPNG_COMPILE_ENCODER*/ /* ////////////////////////////////////////////////////////////////////////// */ /* / File IO / */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_DISK unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) { FILE* file; INT64 size; /*provide some proper output values if error will happen*/ *out = 0; *outsize = 0; file = fopen(filename, "rb"); if(!file) return 78; /*get filesize:*/ _fseeki64(file , 0 , SEEK_END); size = _ftelli64(file); rewind(file); /*read contents of the file into the vector*/ *outsize = 0; *out = (unsigned char*)malloc((size_t)size); if(size && (*out)) (*outsize) = fread(*out, 1, (size_t)size, file); fclose(file); if (size < 0) return 91; if (*outsize != (size_t)size) return 91; if(!(*out) && size) return 83; /*the above malloc failed*/ return 0; } /*write given buffer to the file, overwriting the file, it doesn't append to it.*/ unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) { FILE* file; int ret = 0; file = fopen(filename, "wb" ); if(!file) return 79; if (fwrite((char*)buffer , 1 , buffersize, file) != buffersize) ret = 91; fclose(file); return ret; } #endif /*LODEPNG_COMPILE_DISK*/ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ /* // End of common code and tools. Begin of Zlib related code. // */ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_ZLIB #ifdef LODEPNG_COMPILE_ENCODER /*TODO: this ignores potential out of memory errors*/ static int addBitToStream(size_t* bitpointer, ucvector* bitstream, unsigned char bit) { /*add a new byte at the end*/ if(((*bitpointer) & 7) == 0) { if (!ucvector_push_back(bitstream, (unsigned char)0)) return 83; } /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/ (bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7)); (*bitpointer)++; return 0; } static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) { size_t i; for(i = 0; i < nbits; i++) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1)); } static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) { size_t i; for(i = 0; i < nbits; i++) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1)); } #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_DECODER #define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1) static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream) { unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream)); (*bitpointer)++; return result; } static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) { unsigned result = 0, i; for(i = 0; i < nbits; i++) { result += ((unsigned)READBIT(*bitpointer, bitstream)) << i; (*bitpointer)++; } return result; } #endif /*LODEPNG_COMPILE_DECODER*/ /* ////////////////////////////////////////////////////////////////////////// */ /* / Deflate - Huffman / */ /* ////////////////////////////////////////////////////////////////////////// */ #define FIRST_LENGTH_CODE_INDEX 257 #define LAST_LENGTH_CODE_INDEX 285 /*256 literals, the end code, some length codes, and 2 unused codes*/ #define NUM_DEFLATE_CODE_SYMBOLS 288 /*the distance codes have their own symbols, 30 used, 2 unused*/ #define NUM_DISTANCE_SYMBOLS 32 /*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/ #define NUM_CODE_LENGTH_CODES 19 /*the base lengths represented by codes 257-285*/ static const unsigned LENGTHBASE[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; /*the extra bits used by codes 257-285 (added to base length)*/ static const unsigned LENGTHEXTRA[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; /*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/ static const unsigned DISTANCEBASE[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; /*the extra bits of backwards distances (added to base)*/ static const unsigned DISTANCEEXTRA[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; /*the order in which "code length alphabet code lengths" are stored, out of this the huffman tree of the dynamic huffman tree lengths is generated*/ static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; /* ////////////////////////////////////////////////////////////////////////// */ /* Huffman tree struct, containing multiple representations of the tree */ typedef struct HuffmanTree { unsigned* tree2d; unsigned* tree1d; unsigned* lengths; /*the lengths of the codes of the 1d-tree*/ unsigned maxbitlen; /*maximum number of bits a single code can get*/ unsigned numcodes; /*number of symbols in the alphabet = number of codes*/ } HuffmanTree; /*function used for debug purposes to draw the tree in ascii art with C++*/ /* static void HuffmanTree_draw(HuffmanTree* tree) { std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl; for(size_t i = 0; i < tree->tree1d.size; i++) { if(tree->lengths.data[i]) std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl; } std::cout << std::endl; }*/ static void HuffmanTree_init(HuffmanTree* tree) { tree->tree2d = 0; tree->tree1d = 0; tree->lengths = 0; tree->maxbitlen = 0; tree->numcodes = 0; } static void HuffmanTree_cleanup(HuffmanTree* tree) { free(tree->tree2d); free(tree->tree1d); free(tree->lengths); } /*the tree representation used by the decoder. return value is error*/ static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) { unsigned nodefilled = 0; /*up to which node it is filled*/ unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/ unsigned n, i; tree->tree2d = (unsigned*)calloc(tree->numcodes * 2, sizeof(unsigned)); if(!tree->tree2d) return 83; /*alloc fail*/ /* convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means uninited, a value >= numcodes is an address to another bit, a value < numcodes is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as many columns as codes - 1. A good huffmann tree has N * 2 - 1 nodes, of which N - 1 are internal nodes. Here, the internal nodes are stored (what their 0 and 1 option point to). There is only memory for such good tree currently, if there are more nodes (due to too long length codes), error 55 will happen */ for(n = 0; n < tree->numcodes * 2; n++) { tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/ } for(n = 0; n < tree->numcodes; n++) /*the codes*/ { for(i = 0; i < tree->lengths[n]; i++) /*the bits for this code*/ { unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1); if(treepos > tree->numcodes - 2) return 55; /*oversubscribed, see comment in lodepng_error_text*/ if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/ { if(i + 1 == tree->lengths[n]) /*last bit*/ { tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/ treepos = 0; } else { /*put address of the next step in here, first that address has to be found of course (it's just nodefilled + 1)...*/ nodefilled++; /*addresses encoded with numcodes added to it*/ tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes; treepos = nodefilled; } } else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes; } } for(n = 0; n < tree->numcodes * 2; n++) { if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/ } return 0; } /* Second step for the ...makeFromLengths and ...makeFromFrequencies functions. numcodes, lengths and maxbitlen must already be filled in correctly. return value is error. */ static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) { uivector blcount; uivector nextcode; unsigned bits, n, error = 0; uivector_init(&blcount); uivector_init(&nextcode); tree->tree1d = (unsigned*)calloc(tree->numcodes, sizeof(unsigned)); if(!tree->tree1d) error = 83; /*alloc fail*/ if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0) || !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0)) error = 83; /*alloc fail*/ if(!error) { /*step 1: count number of instances of each code length*/ for(bits = 0; bits < tree->numcodes; bits++) blcount.data[tree->lengths[bits]]++; /*step 2: generate the nextcode values*/ for(bits = 1; bits <= tree->maxbitlen; bits++) { nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1; } /*step 3: generate all the codes*/ for(n = 0; n < tree->numcodes; n++) { if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++; } } uivector_cleanup(&blcount); uivector_cleanup(&nextcode); if(!error) return HuffmanTree_make2DTree(tree); else return error; } /* given the code lengths (as stored in the PNG file), generate the tree as defined by Deflate. maxbitlen is the maximum bits that a code in the tree can have. return value is error. */ static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen, size_t numcodes, unsigned maxbitlen) { unsigned i; tree->lengths = (unsigned*)calloc(numcodes, sizeof(unsigned)); if(!tree->lengths) return 83; /*alloc fail*/ for(i = 0; i < numcodes; i++) tree->lengths[i] = bitlen[i]; tree->numcodes = (unsigned)numcodes; /*number of symbols*/ tree->maxbitlen = maxbitlen; return HuffmanTree_makeFromLengths2(tree); } #ifdef LODEPNG_COMPILE_ENCODER /* A coin, this is the terminology used for the package-merge algorithm and the coin collector's problem. This is used to generate the huffman tree. A coin can be multiple coins (when they're merged) */ typedef struct Coin { uivector symbols; float weight; /*the sum of all weights in this coin*/ } Coin; static void coin_init(Coin* c) { uivector_init(&c->symbols); } /*argument c is void* so that this dtor can be given as function pointer to the vector resize function*/ static void coin_cleanup(void* c) { uivector_cleanup(&((Coin*)c)->symbols); } static void coin_copy(Coin* c1, const Coin* c2) { c1->weight = c2->weight; uivector_copy(&c1->symbols, &c2->symbols); } static void add_coins(Coin* c1, const Coin* c2) { size_t i; for(i = 0; i < c2->symbols.size; i++) uivector_push_back(&c1->symbols, c2->symbols.data[i]); c1->weight += c2->weight; } static void init_coins(Coin* coins, size_t num) { size_t i; for(i = 0; i < num; i++) coin_init(&coins[i]); } static void cleanup_coins(Coin* coins, size_t num) { size_t i; for(i = 0; i < num; i++) coin_cleanup(&coins[i]); } static int coin_compare(const void* a, const void* b) { float wa = ((const Coin*)a)->weight; float wb = ((const Coin*)b)->weight; return wa > wb ? 1 : wa < wb ? -1 : 0; } static unsigned append_symbol_coins(Coin* coins, const unsigned* frequencies, unsigned numcodes, size_t sum) { unsigned i; unsigned j = 0; /*index of present symbols*/ for(i = 0; i < numcodes; i++) { if(frequencies[i] != 0) /*only include symbols that are present*/ { coins[j].weight = frequencies[i] / (float)sum; uivector_push_back(&coins[j].symbols, i); j++; } } return 0; } unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, size_t numcodes, unsigned maxbitlen) { unsigned i, j; size_t sum = 0, numpresent = 0; unsigned error = 0; Coin* coins; /*the coins of the currently calculated row*/ Coin* prev_row; /*the previous row of coins*/ size_t numcoins; size_t coinmem; if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/ for(i = 0; i < numcodes; i++) { if(frequencies[i] > 0) { numpresent++; sum += frequencies[i]; } } for(i = 0; i < numcodes; i++) lengths[i] = 0; /*ensure at least two present symbols. There should be at least one symbol according to RFC 1951 section 3.2.7. To decoders incorrectly require two. To make these work as well ensure there are at least two symbols. The Package-Merge code below also doesn't work correctly if there's only one symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/ if(numpresent == 0) { lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/ } else if(numpresent == 1) { for(i = 0; i < numcodes; i++) { if(frequencies[i]) { lengths[i] = 1; lengths[i == 0 ? 1 : 0] = 1; break; } } } else { /*Package-Merge algorithm represented by coin collector's problem For every symbol, maxbitlen coins will be created*/ coinmem = numpresent * 2; /*max amount of coins needed with the current algo*/ coins = (Coin*)calloc(sizeof(Coin), coinmem); prev_row = (Coin*)calloc(sizeof(Coin), coinmem); if(!coins || !prev_row) { free(coins); free(prev_row); return 83; /*alloc fail*/ } init_coins(coins, coinmem); init_coins(prev_row, coinmem); /*first row, lowest denominator*/ error = append_symbol_coins(coins, frequencies, numcodes, sum); numcoins = numpresent; qsort(coins, numcoins, sizeof(Coin), coin_compare); if(!error) { unsigned numprev = 0; for(j = 1; j <= maxbitlen && !error; j++) /*each of the remaining rows*/ { unsigned tempnum; Coin* tempcoins; /*swap prev_row and coins, and their amounts*/ tempcoins = prev_row; prev_row = coins; coins = tempcoins; tempnum = numprev; numprev = numcoins; numcoins = tempnum; cleanup_coins(coins, numcoins); init_coins(coins, numcoins); numcoins = 0; /*fill in the merged coins of the previous row*/ for(i = 0; i + 1 < numprev; i += 2) { /*merge prev_row[i] and prev_row[i + 1] into new coin*/ Coin* coin = &coins[numcoins++]; coin_copy(coin, &prev_row[i]); add_coins(coin, &prev_row[i + 1]); } /*fill in all the original symbols again*/ if(j < maxbitlen) { error = append_symbol_coins(coins + numcoins, frequencies, numcodes, sum); numcoins += numpresent; } qsort(coins, numcoins, sizeof(Coin), coin_compare); } } if(!error) { /*calculate the lenghts of each symbol, as the amount of times a coin of each symbol is used*/ for(i = 0; i < numpresent - 1; i++) { Coin* coin = &coins[i]; for(j = 0; j < coin->symbols.size; j++) lengths[coin->symbols.data[j]]++; } } cleanup_coins(coins, coinmem); free(coins); cleanup_coins(prev_row, coinmem); free(prev_row); } return error; } /*Create the Huffman tree given the symbol frequencies*/ static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, size_t mincodes, size_t numcodes, unsigned maxbitlen) { unsigned* lengths; unsigned error = 0; while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/ tree->maxbitlen = maxbitlen; tree->numcodes = (unsigned)numcodes; /*number of symbols*/ lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned)); if (!lengths) free(tree->lengths); tree->lengths = lengths; if(!tree->lengths) return 83; /*alloc fail*/ /*initialize all lengths to 0*/ memset(tree->lengths, 0, numcodes * sizeof(unsigned)); error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); if(!error) error = HuffmanTree_makeFromLengths2(tree); return error; } static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index) { return tree->tree1d[index]; } static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index) { return tree->lengths[index]; } #endif /*LODEPNG_COMPILE_ENCODER*/ /*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/ static unsigned generateFixedLitLenTree(HuffmanTree* tree) { unsigned i, error = 0; unsigned* bitlen = (unsigned*)calloc(NUM_DEFLATE_CODE_SYMBOLS, sizeof(unsigned)); if(!bitlen) return 83; /*alloc fail*/ /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/ for(i = 0; i <= 143; i++) bitlen[i] = 8; for(i = 144; i <= 255; i++) bitlen[i] = 9; for(i = 256; i <= 279; i++) bitlen[i] = 7; for(i = 280; i <= 287; i++) bitlen[i] = 8; error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15); free(bitlen); return error; } /*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/ static unsigned generateFixedDistanceTree(HuffmanTree* tree) { unsigned i, error = 0; unsigned* bitlen = (unsigned*)malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); if(!bitlen) return 83; /*alloc fail*/ /*there are 32 distance codes, but 30-31 are unused*/ for(i = 0; i < NUM_DISTANCE_SYMBOLS; i++) bitlen[i] = 5; error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15); free(bitlen); return error; } #ifdef LODEPNG_COMPILE_DECODER /* returns the code, or (unsigned)(-1) if error happened inbitlength is the length of the complete buffer, in bits (so its byte length times 8) */ static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp, const HuffmanTree* codetree, size_t inbitlength) { unsigned treepos = 0, ct; if (!codetree || !codetree->tree2d) return 0; for(;;) { if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/ /* decode the symbol from the tree. The "readBitFromStream" code is inlined in the expression below because this is the biggest bottleneck while decoding */ ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)]; (*bp)++; if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/ else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/ if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/ } } #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_DECODER /* ////////////////////////////////////////////////////////////////////////// */ /* / Inflator (Decompressor) / */ /* ////////////////////////////////////////////////////////////////////////// */ /*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/ static int getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) { int rc; rc = generateFixedLitLenTree(tree_ll); if (rc) return rc; return generateFixedDistanceTree(tree_d); } /*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/ static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, const unsigned char* in, size_t* bp, size_t inlength) { /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/ unsigned error = 0; unsigned n, HLIT, HDIST, HCLEN, i; size_t inbitlength = inlength * 8; /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/ unsigned* bitlen_ll = 0; /*lit,len code lengths*/ unsigned* bitlen_d = 0; /*dist code lengths*/ /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/ unsigned* bitlen_cl = 0; HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/ if((*bp) >> 3 >= inlength - 2) return 49; /*error: the bit pointer is or will go past the memory*/ /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/ HLIT = readBitsFromStream(bp, in, 5) + 257; /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/ HDIST = readBitsFromStream(bp, in, 5) + 1; /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/ HCLEN = readBitsFromStream(bp, in, 4) + 4; HuffmanTree_init(&tree_cl); while(!error) { /*read the code length codes out of 3 * (amount of code length codes) bits*/ bitlen_cl = (unsigned*)malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned)); if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/); for(i = 0; i < NUM_CODE_LENGTH_CODES; i++) { if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3); else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/ } error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7); if(error) break; /*now we can use this tree to read the lengths for the tree that this function will return*/ bitlen_ll = (unsigned*)malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); bitlen_d = (unsigned*)malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/); for(i = 0; i < NUM_DEFLATE_CODE_SYMBOLS; i++) bitlen_ll[i] = 0; for(i = 0; i < NUM_DISTANCE_SYMBOLS; i++) bitlen_d[i] = 0; /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/ i = 0; while(i < HLIT + HDIST) { unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength); if(code <= 15) /*a length code*/ { if(i < HLIT) bitlen_ll[i] = code; else bitlen_d[i - HLIT] = code; i++; } else if(code == 16) /*repeat previous*/ { unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/ unsigned value; /*set value to the previous code*/ if(*bp >= inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ if (i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/ replength += readBitsFromStream(bp, in, 2); if(i < HLIT + 1) value = bitlen_ll[i - 1]; else value = bitlen_d[i - HLIT - 1]; /*repeat this value in the next lengths*/ for(n = 0; n < replength; n++) { if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/ if(i < HLIT) bitlen_ll[i] = value; else bitlen_d[i - HLIT] = value; i++; } } else if(code == 17) /*repeat "0" 3-10 times*/ { unsigned replength = 3; /*read in the bits that indicate repeat length*/ if(*bp >= inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ replength += readBitsFromStream(bp, in, 3); /*repeat this value in the next lengths*/ for(n = 0; n < replength; n++) { if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/ if(i < HLIT) bitlen_ll[i] = 0; else bitlen_d[i - HLIT] = 0; i++; } } else if(code == 18) /*repeat "0" 11-138 times*/ { unsigned replength = 11; /*read in the bits that indicate repeat length*/ if(*bp >= inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ replength += readBitsFromStream(bp, in, 7); /*repeat this value in the next lengths*/ for(n = 0; n < replength; n++) { if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/ if(i < HLIT) bitlen_ll[i] = 0; else bitlen_d[i - HLIT] = 0; i++; } } else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ { if(code == (unsigned)(-1)) { /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol (10=no endcode, 11=wrong jump outside of tree)*/ error = (*bp) > inbitlength ? 10 : 11; } else error = 16; /*unexisting code, this can never happen*/ break; } } if(error) break; if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/ /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/ error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15); if(error) break; error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15); break; /*end of error-while*/ } free(bitlen_cl); free(bitlen_ll); free(bitlen_d); HuffmanTree_cleanup(&tree_cl); return error; } /*inflate a block with dynamic of fixed Huffman tree*/ static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength, unsigned btype) { unsigned error = 0; HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/ HuffmanTree tree_d; /*the huffman tree for distance codes*/ size_t inbitlength = inlength * 8; HuffmanTree_init(&tree_ll); HuffmanTree_init(&tree_d); if(btype == 1) { error = getTreeInflateFixed(&tree_ll, &tree_d); if (error) { HuffmanTree_cleanup(&tree_ll); HuffmanTree_cleanup(&tree_d); return error; } } else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength); while(!error) /*decode all symbols until end reached, breaks at end code*/ { /*code_ll is literal, length or end code*/ unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength); if(code_ll <= 255) /*literal symbol*/ { /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/ if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/); out->data[*pos] = (unsigned char)code_ll; (*pos)++; } else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ { unsigned code_d, distance; unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/ size_t start, forward, backward, length; /*part 1: get length base*/ length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX]; /*part 2: get extra bits and add the value of that to length*/ numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX]; if(*bp >= inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ length += readBitsFromStream(bp, in, numextrabits_l); /*part 3: get distance code*/ code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength); if(code_d > 29) { if(code_ll == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ { /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol (10=no endcode, 11=wrong jump outside of tree)*/ error = (*bp) > inlength * 8 ? 10 : 11; } else error = 18; /*error: invalid distance code (30-31 are never used)*/ break; } distance = DISTANCEBASE[code_d]; /*part 4: get extra bits from distance*/ numextrabits_d = DISTANCEEXTRA[code_d]; if(*bp >= inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ distance += readBitsFromStream(bp, in, numextrabits_d); /*part 5: fill in all the out[n] values based on the length and dist*/ start = (*pos); if(distance > start) ERROR_BREAK(52); /*too long backward distance*/ backward = start - distance; if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/); for(forward = 0; forward < length; forward++) { out->data[(*pos)] = out->data[backward]; (*pos)++; backward++; if(backward >= start) backward = start - distance; } } else if(code_ll == 256) { break; /*end code, break the loop*/ } else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ { /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol (10=no endcode, 11=wrong jump outside of tree)*/ error = (*bp) > inlength * 8 ? 10 : 11; break; } } HuffmanTree_cleanup(&tree_ll); HuffmanTree_cleanup(&tree_d); return error; } static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength) { /*go to first boundary of byte*/ size_t p; unsigned LEN, NLEN, n, error = 0; while(((*bp) & 0x7) != 0) (*bp)++; p = (*bp) / 8; /*byte position*/ /*read LEN (2 bytes) and NLEN (2 bytes)*/ if(p >= inlength - 4) return 52; /*error, bit pointer will jump past memory*/ LEN = in[p] + 256u * in[p + 1]; p += 2; NLEN = in[p] + 256u * in[p + 1]; p += 2; /*check if 16-bit NLEN is really the one's complement of LEN*/ if(LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/ if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/ /*read the literal data: LEN bytes are now stored in the out buffer*/ if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/ for(n = 0; n < LEN; n++) out->data[(*pos)++] = in[p++]; (*bp) = p * 8; return error; } static unsigned lodepng_inflatev(ucvector* out, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/ size_t bp = 0; unsigned BFINAL = 0; size_t pos = 0; /*byte position in the out buffer*/ unsigned error = 0; (void)settings; while(!BFINAL) { unsigned BTYPE; if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/ BFINAL = readBitFromStream(&bp, in); BTYPE = 1u * readBitFromStream(&bp, in); BTYPE += 2u * readBitFromStream(&bp, in); if(BTYPE == 3) return 20; /*error: invalid BTYPE*/ else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/ else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/ if(error) return error; } return error; } unsigned lodepng_inflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { unsigned error; ucvector v; ucvector_init_buffer(&v, *out, *outsize); error = lodepng_inflatev(&v, in, insize, settings); *out = v.data; *outsize = v.size; return error; } static unsigned inflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { if(settings->custom_inflate) { return settings->custom_inflate(out, outsize, in, insize, settings); } else { return lodepng_inflate(out, outsize, in, insize, settings); } } #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* ////////////////////////////////////////////////////////////////////////// */ /* / Deflator (Compressor) / */ /* ////////////////////////////////////////////////////////////////////////// */ static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258; /*bitlen is the size in bits of the code*/ static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen) { addBitsToStreamReversed(bp, compressed, code, bitlen); } /*search the index in the array, that has the largest value smaller than or equal to the given value, given array must be sorted (if no value is smaller, it returns the size of the given array)*/ static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) { /*linear search implementation*/ /*for(size_t i = 1; i < array_size; i++) if(array[i] > value) return i - 1; return array_size - 1;*/ /*binary search implementation (not that much faster) (precondition: array_size > 0)*/ size_t left = 1; size_t right = array_size - 1; while(left <= right) { size_t mid = (left + right) / 2; if(array[mid] <= value) left = mid + 1; /*the value to find is more to the right*/ else if(array[mid - 1] > value) right = mid - 1; /*the value to find is more to the left*/ else return mid - 1; } return array_size - 1; } static void addLengthDistance(uivector* values, size_t length, size_t distance) { /*values in encoded vector are those used by deflate: 0-255: literal bytes 256: end 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits) 286-287: invalid*/ unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length); unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]); unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance); unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]); uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX); uivector_push_back(values, extra_length); uivector_push_back(values, dist_code); uivector_push_back(values, extra_distance); } /*3 bytes of data get encoded into two bytes. The hash cannot use more than 3 bytes as input because 3 is the minimum match length for deflate*/ static const unsigned HASH_NUM_VALUES = 65536; static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/ typedef struct Hash { int* head; /*hash value to head circular pos - can be outdated if went around window*/ /*circular pos to prev circular pos*/ unsigned short* chain; int* val; /*circular pos to hash value*/ /*TODO: do this not only for zeros but for any repeated byte. However for PNG it's always going to be the zeros that dominate, so not important for PNG*/ int* headz; /*similar to head, but for chainz*/ unsigned short* chainz; /*those with same amount of zeros*/ unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/ } Hash; static unsigned hash_init(Hash* hash, unsigned windowsize) { unsigned i; hash->head = (int*)calloc(sizeof(int), HASH_NUM_VALUES); hash->val = (int*)calloc(sizeof(int), windowsize); hash->chain = (unsigned short*)calloc(sizeof(unsigned short), windowsize); hash->zeros = (unsigned short*)calloc(sizeof(unsigned short), windowsize); hash->headz = (int*)calloc(sizeof(int), (MAX_SUPPORTED_DEFLATE_LENGTH + 1)); hash->chainz = (unsigned short*)calloc(sizeof(unsigned short), windowsize); if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros) { return 83; /*alloc fail*/ } /*initialize hash table*/ for(i = 0; i < HASH_NUM_VALUES; i++) hash->head[i] = -1; for(i = 0; i < windowsize; i++) hash->val[i] = -1; for(i = 0; i < windowsize; i++) hash->chain[i] = i; /*same value as index indicates uninitialized*/ for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; i++) hash->headz[i] = -1; for(i = 0; i < windowsize; i++) hash->chainz[i] = i; /*same value as index indicates uninitialized*/ return 0; } static void hash_cleanup(Hash* hash) { free(hash->head); free(hash->val); free(hash->chain); free(hash->zeros); free(hash->headz); free(hash->chainz); } static unsigned getHash(const unsigned char* data, size_t size, size_t pos) { unsigned result = 0; if (pos + 2 < size) { /*A simple shift and xor hash is used. Since the data of PNGs is dominated by zeroes due to the filters, a better hash does not have a significant effect on speed in traversing the chain, and causes more time spend on calculating the hash.*/ result ^= (unsigned)(data[pos + 0] << 0u); result ^= (unsigned)(data[pos + 1] << 4u); result ^= (unsigned)(data[pos + 2] << 8u); } else { size_t amount, i; if(pos >= size) return 0; amount = size - pos; for(i = 0; i < amount; i++) result ^= (unsigned)(data[pos + i] << (i * 8u)); } return result & HASH_BIT_MASK; } static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) { const unsigned char* start = data + pos; const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH; if(end > data + size) end = data + size; data = start; while (data != end && *data == 0) data++; /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/ return (unsigned)(data - start); } /*wpos = pos & (windowsize - 1)*/ static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) { hash->val[wpos] = (int)hashval; if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval]; hash->head[hashval] = wpos; hash->zeros[wpos] = numzeros; if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros]; hash->headz[numzeros] = wpos; } /* LZ77-encode the data. Return value is error code. The input are raw bytes, the output is in the form of unsigned integers with codes representing for example literal bytes, or length/distance pairs. It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a sliding window (of windowsize) is used, and all past bytes in that window can be used as the "dictionary". A brute force search through all possible distances would be slow, and this hash technique is one out of several ways to speed this up. */ static unsigned encodeLZ77(uivector* out, Hash* hash, const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize, unsigned minmatch, unsigned nicematch, unsigned lazymatching) { size_t pos; unsigned i, error = 0; /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/ unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8; unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64; unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/ unsigned numzeros = 0; unsigned offset; /*the offset represents the distance in LZ77 terminology*/ unsigned length; unsigned lazy = 0; unsigned lazylength = 0, lazyoffset = 0; unsigned hashval; unsigned current_offset, current_length; unsigned prev_offset; const unsigned char *lastptr, *foreptr, *backptr; unsigned hashpos; if(windowsize <= 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/ if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/ if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH; for(pos = inpos; pos < insize; pos++) { size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/ unsigned chainlength = 0; hashval = getHash(in, insize, pos); if(usezeros && hashval == 0) { if (numzeros == 0) numzeros = countZeros(in, insize, pos); else if (pos + numzeros > insize || in[pos + numzeros - 1] != 0) numzeros--; } else { numzeros = 0; } updateHashChain(hash, wpos, hashval, numzeros); /*the length and offset found for the current position*/ length = 0; offset = 0; hashpos = hash->chain[wpos]; lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH]; /*search for the longest string*/ prev_offset = 0; for(;;) { if(chainlength++ >= maxchainlength) break; current_offset = hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize; if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/ prev_offset = current_offset; if(current_offset > 0) { /*test the next characters*/ foreptr = &in[pos]; backptr = &in[pos - current_offset]; /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/ if(numzeros >= 3) { unsigned skip = hash->zeros[hashpos]; if(skip > numzeros) skip = numzeros; backptr += skip; foreptr += skip; } while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ { ++backptr; ++foreptr; } current_length = (unsigned)(foreptr - &in[pos]); if(current_length > length) { length = current_length; /*the longest length*/ offset = current_offset; /*the offset that is related to this longest length*/ /*jump out once a length of max length is found (speed gain). This also jumps out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/ if(current_length >= nicematch) break; } } if(hashpos == hash->chain[hashpos]) break; if(numzeros >= 3 && length > numzeros) { hashpos = hash->chainz[hashpos]; if(hash->zeros[hashpos] != numzeros) break; } else { hashpos = hash->chain[hashpos]; /*outdated hash value, happens if particular value was not encountered in whole last window*/ if(hash->val[hashpos] != (int)hashval) break; } } if(lazymatching) { if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) { lazy = 1; lazylength = length; lazyoffset = offset; continue; /*try the next byte*/ } if(lazy) { lazy = 0; if(pos == 0) ERROR_BREAK(81); if(length > lazylength + 1) { /*push the previous character as literal*/ if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/); } else { length = lazylength; offset = lazyoffset; hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/ hash->headz[numzeros] = -1; /*idem*/ pos--; } } } if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/); /*encode it as length/distance pair or literal value*/ if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ { if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); } else if(length < minmatch || (length == 3 && offset > 4096)) { /*compensate for the fact that longer offsets have more extra bits, a length of only 3 may be not worth it then*/ if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); } else { addLengthDistance(out, length, offset); for(i = 1; i < length; i++) { pos++; wpos = pos & (windowsize - 1); hashval = getHash(in, insize, pos); if(usezeros && hashval == 0) { if (numzeros == 0) numzeros = countZeros(in, insize, pos); else if (pos + numzeros > insize || in[pos + numzeros - 1] != 0) numzeros--; } else { numzeros = 0; } updateHashChain(hash, wpos, hashval, numzeros); } } } /*end of the loop through each character of input*/ return error; } /* /////////////////////////////////////////////////////////////////////////// */ static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) { /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte, 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/ size_t i, j, numdeflateblocks = (datasize + 65534) / 65535; unsigned datapos = 0; for(i = 0; i < numdeflateblocks; i++) { unsigned BFINAL, BTYPE, LEN, NLEN; unsigned char firstbyte; BFINAL = (i == numdeflateblocks - 1); BTYPE = 0; firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1)); if (!ucvector_push_back(out, firstbyte)) return 83; LEN = 65535; if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos; NLEN = 65535 - LEN; if (!ucvector_push_back(out, (unsigned char)(LEN % 256))) return 83; if (!ucvector_push_back(out, (unsigned char)(LEN / 256))) return 83; if (!ucvector_push_back(out, (unsigned char)(NLEN % 256))) return 83; if (!ucvector_push_back(out, (unsigned char)(NLEN / 256))) return 83; /*Decompressed data*/ for(j = 0; j < 65535 && datapos < datasize; j++) { if (!ucvector_push_back(out, data[datapos++])) return 83; } } return 0; } /* write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees. tree_ll: the tree for lit and len codes. tree_d: the tree for distance codes. */ static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded, const HuffmanTree* tree_ll, const HuffmanTree* tree_d) { size_t i = 0; for(i = 0; i < lz77_encoded->size; i++) { unsigned val = lz77_encoded->data[i]; addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val)); if(val > 256) /*for a length code, 3 more things have to be added*/ { unsigned length_index = val - FIRST_LENGTH_CODE_INDEX; unsigned n_length_extra_bits = LENGTHEXTRA[length_index]; unsigned length_extra_bits = lz77_encoded->data[++i]; unsigned distance_code = lz77_encoded->data[++i]; unsigned distance_index = distance_code; unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index]; unsigned distance_extra_bits = lz77_encoded->data[++i]; addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits); addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code), HuffmanTree_getLength(tree_d, distance_code)); addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits); } } } /*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/ static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, const unsigned char* data, size_t datapos, size_t dataend, const LodePNGCompressSettings* settings, unsigned final) { unsigned error = 0; /* A block is compressed as follows: The PNG data is lz77 encoded, resulting in literal bytes and length/distance pairs. This is then huffman compressed with two huffman trees. One huffman tree is used for the lit and len values ("ll"), another huffman tree is used for the dist values ("d"). These two trees are stored using their code lengths, and to compress even more these code lengths are also run-length encoded and huffman compressed. This gives a huffman tree of code lengths "cl". The code lenghts used to describe this third tree are the code length code lengths ("clcl"). */ /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/ uivector lz77_encoded; HuffmanTree tree_ll; /*tree for lit,len values*/ HuffmanTree tree_d; /*tree for distance codes*/ HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/ uivector frequencies_ll; /*frequency of lit,len codes*/ uivector frequencies_d; /*frequency of dist codes*/ uivector frequencies_cl; /*frequency of code length codes*/ uivector bitlen_lld; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/ uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/ /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl (these are written as is in the file, it would be crazy to compress these using yet another huffman tree that needs to be represented by yet another set of code lengths)*/ uivector bitlen_cl; size_t datasize = dataend - datapos; /* Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies: bitlen_lld is to tree_cl what data is to tree_ll and tree_d. bitlen_lld_e is to bitlen_lld what lz77_encoded is to data. bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded. */ unsigned BFINAL = final; size_t numcodes_ll, numcodes_d, i; unsigned HLIT, HDIST, HCLEN; uivector_init(&lz77_encoded); HuffmanTree_init(&tree_ll); HuffmanTree_init(&tree_d); HuffmanTree_init(&tree_cl); uivector_init(&frequencies_ll); uivector_init(&frequencies_d); uivector_init(&frequencies_cl); uivector_init(&bitlen_lld); uivector_init(&bitlen_lld_e); uivector_init(&bitlen_cl); /*This while loop never loops due to a break at the end, it is here to allow breaking out of it to the cleanup phase on error conditions.*/ while(!error) { if(settings->use_lz77) { error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, settings->minmatch, settings->nicematch, settings->lazymatching); if(error) break; } else { if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/); if (!lz77_encoded.data) ERROR_BREAK(83 /* alloc fail */); for(i = datapos; i < dataend; i++) lz77_encoded.data[i] = data[i]; /*no LZ77, but still will be Huffman compressed*/ } if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/); if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/); /*Count the frequencies of lit, len and dist codes*/ for(i = 0; i < lz77_encoded.size; i++) { unsigned symbol; if (!lz77_encoded.data) ERROR_BREAK(83 /* alloc fail */); symbol = lz77_encoded.data[i]; frequencies_ll.data[symbol]++; if(symbol > 256) { unsigned dist = lz77_encoded.data[i + 2]; frequencies_d.data[dist]++; i += 3; } } frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/ /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/ error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15); if(error) break; /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/ error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15); if(error) break; numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286; numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30; /*store the code lengths of both generated trees in bitlen_lld*/ for(i = 0; i < numcodes_ll; i++) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i)); for(i = 0; i < numcodes_d; i++) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i)); /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times), 17 (3-10 zeroes), 18 (11-138 zeroes)*/ for(i = 0; i < (unsigned)bitlen_lld.size; i++) { unsigned j = 0; /*amount of repititions*/ while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) j++; if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/ { j++; /*include the first zero*/ if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ { uivector_push_back(&bitlen_lld_e, 17); uivector_push_back(&bitlen_lld_e, j - 3); } else /*repeat code 18 supports max 138 zeroes*/ { if(j > 138) j = 138; uivector_push_back(&bitlen_lld_e, 18); uivector_push_back(&bitlen_lld_e, j - 11); } i += (j - 1); } else if(j >= 3) /*repeat code for value other than zero*/ { size_t k; unsigned num = j / 6, rest = j % 6; uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); for(k = 0; k < num; k++) { uivector_push_back(&bitlen_lld_e, 16); uivector_push_back(&bitlen_lld_e, 6 - 3); } if(rest >= 3) { uivector_push_back(&bitlen_lld_e, 16); uivector_push_back(&bitlen_lld_e, rest - 3); } else j -= rest; i += j; } else /*too short to benefit from repeat code*/ { uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); } } /*generate tree_cl, the huffmantree of huffmantrees*/ if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/); for(i = 0; i < bitlen_lld_e.size; i++) { frequencies_cl.data[bitlen_lld_e.data[i]]++; /*after a repeat code come the bits that specify the number of repetitions, those don't need to be in the frequencies_cl calculation*/ if(bitlen_lld_e.data[i] >= 16) i++; } error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data, frequencies_cl.size, frequencies_cl.size, 7); if(error) break; if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/); for(i = 0; i < tree_cl.numcodes && bitlen_cl.data; i++) { /*lenghts of code length tree is in the order as specified by deflate*/ bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]); } while(bitlen_cl.data && bitlen_cl.size > 4 && bitlen_cl.data[bitlen_cl.size - 1] == 0) { /*remove zeros at the end, but minimum size must be 4*/ if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/); } if(error || !bitlen_cl.data) break; /* Write everything into the output After the BFINAL and BTYPE, the dynamic block consists out of the following: - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN - (HCLEN+4)*3 bits code lengths of code length alphabet - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length alphabet, + possible repetition codes 16, 17, 18) - HDIST + 1 code lengths of distance alphabet (encoded using the code length alphabet, + possible repetition codes 16, 17, 18) - compressed data - 256 (end code) */ /*Write block type*/ addBitToStream(bp, out, BFINAL); addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/ addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/ /*write the HLIT, HDIST and HCLEN values*/ HLIT = (unsigned)(numcodes_ll - 257); HDIST = (unsigned)(numcodes_d - 1); HCLEN = 0; if (bitlen_cl.size > 4) HCLEN = (unsigned)bitlen_cl.size - 4; /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/ while(HCLEN > 0 && !bitlen_cl.data[HCLEN + 4 - 1]) HCLEN--; addBitsToStream(bp, out, HLIT, 5); addBitsToStream(bp, out, HDIST, 5); addBitsToStream(bp, out, HCLEN, 4); /*write the code lenghts of the code length alphabet*/ if (bitlen_cl.size > 4) { for(i = 0; i < HCLEN + 4; i++) addBitsToStream(bp, out, bitlen_cl.data[i], 3); } /*write the lenghts of the lit/len AND the dist alphabet*/ for(i = 0; i < bitlen_lld_e.size; i++) { addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]), HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i])); /*extra bits of repeat codes*/ if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2); else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3); else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7); } /*write the compressed data symbols*/ writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); /*error: the length of the end code 256 must be larger than 0*/ if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64); /*write the end code*/ addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); break; /*end of error-while*/ } /*cleanup*/ uivector_cleanup(&lz77_encoded); HuffmanTree_cleanup(&tree_ll); HuffmanTree_cleanup(&tree_d); HuffmanTree_cleanup(&tree_cl); uivector_cleanup(&frequencies_ll); uivector_cleanup(&frequencies_d); uivector_cleanup(&frequencies_cl); uivector_cleanup(&bitlen_lld_e); uivector_cleanup(&bitlen_lld); uivector_cleanup(&bitlen_cl); return error; } static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash, const unsigned char* data, size_t datapos, size_t dataend, const LodePNGCompressSettings* settings, unsigned final) { HuffmanTree tree_ll; /*tree for literal values and length codes*/ HuffmanTree tree_d; /*tree for distance codes*/ unsigned BFINAL = final; unsigned error = 0; size_t i; HuffmanTree_init(&tree_ll); HuffmanTree_init(&tree_d); error = generateFixedLitLenTree(&tree_ll); if (error) return error; error = generateFixedDistanceTree(&tree_d); if (error) { HuffmanTree_cleanup(&tree_ll); return error; } addBitToStream(bp, out, BFINAL); addBitToStream(bp, out, 1); /*first bit of BTYPE*/ addBitToStream(bp, out, 0); /*second bit of BTYPE*/ if(settings->use_lz77) /*LZ77 encoded*/ { uivector lz77_encoded; uivector_init(&lz77_encoded); error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, settings->minmatch, settings->nicematch, settings->lazymatching); if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); uivector_cleanup(&lz77_encoded); } else /*no LZ77, but still will be Huffman compressed*/ { for(i = datapos; i < dataend; i++) { addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i])); } } /*add END code*/ if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); /*cleanup*/ HuffmanTree_cleanup(&tree_ll); HuffmanTree_cleanup(&tree_d); return error; } static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings) { unsigned error = 0; size_t i, blocksize, numdeflateblocks; size_t bp = 0; /*the bit pointer*/ Hash hash; if(settings->btype > 2) return 61; else if(settings->btype == 0) return deflateNoCompression(out, in, insize); else if(settings->btype == 1) blocksize = insize; else /*if(settings->btype == 2)*/ { blocksize = insize / 8 + 8; if(blocksize < 65535) blocksize = 65535; } numdeflateblocks = (insize + blocksize - 1) / blocksize; if(numdeflateblocks == 0) numdeflateblocks = 1; error = hash_init(&hash, settings->windowsize); if(error) goto fail; for(i = 0; i < numdeflateblocks && !error; i++) { unsigned final = (i == numdeflateblocks - 1); size_t start = i * blocksize; size_t end = start + blocksize; if(end > insize) end = insize; if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final); else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final); } fail: hash_cleanup(&hash); return error; } unsigned lodepng_deflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings) { unsigned error; ucvector v; ucvector_init_buffer(&v, *out, *outsize); error = lodepng_deflatev(&v, in, insize, settings); *out = v.data; *outsize = v.size; return error; } static unsigned deflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings) { if(settings->custom_deflate) { return settings->custom_deflate(out, outsize, in, insize, settings); } else { return lodepng_deflate(out, outsize, in, insize, settings); } } #endif /*LODEPNG_COMPILE_DECODER*/ /* ////////////////////////////////////////////////////////////////////////// */ /* / Adler32 */ /* ////////////////////////////////////////////////////////////////////////// */ static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) { unsigned s1 = adler & 0xffff; unsigned s2 = (adler >> 16) & 0xffff; while(len > 0) { /*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/ unsigned amount = len > 5550 ? 5550 : len; len -= amount; while(amount > 0) { s1 += (*data++); s2 += s1; amount--; } s1 %= 65521; s2 %= 65521; } return (s2 << 16) | s1; } /*Return the adler32 of the bytes data[0..len-1]*/ static unsigned adler32(const unsigned char* data, unsigned len) { return update_adler32(1L, data, len); } /* ////////////////////////////////////////////////////////////////////////// */ /* / Zlib / */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_DECODER unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { unsigned error = 0; unsigned CM, CINFO, FDICT; if(insize < 2) return 53; /*error, size of zlib data too small*/ /*read information from zlib header*/ if((in[0] * 256 + in[1]) % 31 != 0) { /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/ return 24; } CM = in[0] & 15; CINFO = (in[0] >> 4) & 15; /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/ FDICT = (in[1] >> 5) & 1; /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/ if(CM != 8 || CINFO > 7) { /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/ return 25; } if(FDICT != 0) { /*error: the specification of PNG says about the zlib stream: "The additional flags shall not specify a preset dictionary."*/ return 26; } error = inflate(out, outsize, in + 2, insize - 2, settings); if(error) return error; if(!settings->ignore_adler32) { unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]); unsigned checksum = adler32(*out, (unsigned)(*outsize)); if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/ } return 0; /*no error*/ } static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { if(settings->custom_zlib) { return settings->custom_zlib(out, outsize, in, insize, settings); } else { return lodepng_zlib_decompress(out, outsize, in, insize, settings); } } #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings) { /*initially, *out must be NULL and outsize 0, if you just give some random *out that's pointing to a non allocated buffer, this'll crash*/ ucvector outv; size_t i; unsigned error; unsigned char* deflatedata = 0; size_t deflatesize = 0; unsigned ADLER32; /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/ unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/ unsigned FLEVEL = 0; unsigned FDICT = 0; unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64; unsigned FCHECK = 31 - CMFFLG % 31; CMFFLG += FCHECK; /*ucvector-controlled version of the output buffer, for dynamic array*/ ucvector_init_buffer(&outv, *out, *outsize); if (!ucvector_push_back(&outv, (unsigned char)(CMFFLG / 256))) return 83; if (!ucvector_push_back(&outv, (unsigned char)(CMFFLG % 256))) return 83; error = deflate(&deflatedata, &deflatesize, in, insize, settings); if(!error) { ADLER32 = adler32(in, (unsigned)insize); for(i = 0; i < deflatesize; i++) { if (!ucvector_push_back(&outv, deflatedata[i])) return 83; } free(deflatedata); error = !lodepng_add32bitInt(&outv, ADLER32); } if (!error) { *out = outv.data; *outsize = outv.size; } else { *out = NULL; *outsize = 0; ucvector_cleanup(&outv); } return error; } /* compress using the default or custom zlib function */ static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings) { if(settings->custom_zlib) { return settings->custom_zlib(out, outsize, in, insize, settings); } else { return lodepng_zlib_compress(out, outsize, in, insize, settings); } } #endif /*LODEPNG_COMPILE_ENCODER*/ #else /*no LODEPNG_COMPILE_ZLIB*/ #ifdef LODEPNG_COMPILE_DECODER static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { if (!settings->custom_zlib) return 87; /*no custom zlib function provided */ return settings->custom_zlib(out, outsize, in, insize, settings); } #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings) { if (!settings->custom_zlib) return 87; /*no custom zlib function provided */ return settings->custom_zlib(out, outsize, in, insize, settings); } #endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ZLIB*/ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_ENCODER /*this is a good tradeoff between speed and compression ratio*/ #define DEFAULT_WINDOWSIZE 2048 void lodepng_compress_settings_init(LodePNGCompressSettings* settings) { /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/ settings->btype = 2; settings->use_lz77 = 1; settings->windowsize = DEFAULT_WINDOWSIZE; settings->minmatch = 3; settings->nicematch = 128; settings->lazymatching = 1; settings->custom_zlib = 0; settings->custom_deflate = 0; settings->custom_context = 0; } const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0}; #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_DECODER void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) { settings->ignore_adler32 = 0; settings->custom_zlib = 0; settings->custom_inflate = 0; settings->custom_context = 0; } const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0}; #endif /*LODEPNG_COMPILE_DECODER*/ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ /* // End of Zlib related code. Begin of PNG related code. // */ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_PNG /* ////////////////////////////////////////////////////////////////////////// */ /* / CRC32 / */ /* ////////////////////////////////////////////////////////////////////////// */ /* CRC polynomial: 0xedb88320 */ static unsigned lodepng_crc32_table[256] = { 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u, 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u, 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u, 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u, 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u, 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u, 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u, 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u, 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u, 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u, 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u, 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u, 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u, 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u, 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u, 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u, 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u, 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u, 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u, 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u, 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u, 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u, 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u, 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u, 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u, 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u, 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u, 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u, 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u, 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u, 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u, 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u }; /*Return the CRC of the bytes buf[0..len-1].*/ unsigned lodepng_crc32(const unsigned char* buf, size_t len) { unsigned c = 0xffffffffL; size_t n; for(n = 0; n < len; n++) { c = lodepng_crc32_table[(c ^ buf[n]) & 0xff] ^ (c >> 8); } return c ^ 0xffffffffL; } /* ////////////////////////////////////////////////////////////////////////// */ /* / Reading and writing single bits and bytes from/to stream for LodePNG / */ /* ////////////////////////////////////////////////////////////////////////// */ static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) { unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1); (*bitpointer)++; return result; } static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) { unsigned result = 0; size_t i; for(i = nbits - 1; i < nbits; i--) { result += (unsigned)readBitFromReversedStream(bitpointer, bitstream) << i; } return result; } #ifdef LODEPNG_COMPILE_DECODER static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) { /*the current bit in bitstream must be 0 for this to work*/ if(bit) { /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/ bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7))); } (*bitpointer)++; } #endif /*LODEPNG_COMPILE_DECODER*/ static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) { /*the current bit in bitstream may be 0 or 1 for this to work*/ if(bit == 0) { size_t pos = (*bitpointer) >> 3; bitstream[pos] &= (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7)))); } else { size_t pos = (*bitpointer) >> 3; bitstream[pos] |= (1 << (7 - ((*bitpointer) & 0x7))); } (*bitpointer)++; } /* ////////////////////////////////////////////////////////////////////////// */ /* / PNG chunks / */ /* ////////////////////////////////////////////////////////////////////////// */ unsigned lodepng_chunk_length(const unsigned char* chunk) { return lodepng_read32bitInt(&chunk[0]); } void lodepng_chunk_type(char type[5], const unsigned char* chunk) { unsigned i; for(i = 0; i < 4; i++) type[i] = (char)chunk[4 + i]; type[4] = 0; /*null termination char*/ } unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) { if(strlen(type) != 4) return 0; return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]); } unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) { return((chunk[4] & 32) != 0); } unsigned char lodepng_chunk_private(const unsigned char* chunk) { return((chunk[6] & 32) != 0); } unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) { return((chunk[7] & 32) != 0); } unsigned char* lodepng_chunk_data(unsigned char* chunk) { return &chunk[8]; } const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) { return &chunk[8]; } unsigned lodepng_chunk_check_crc(const unsigned char* chunk) { unsigned length = lodepng_chunk_length(chunk); unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]); /*the CRC is taken of the data and the 4 chunk type letters, not the length*/ unsigned checksum = lodepng_crc32(&chunk[4], length + 4); if(CRC != checksum) return 1; else return 0; } void lodepng_chunk_generate_crc(unsigned char* chunk) { unsigned length = lodepng_chunk_length(chunk); unsigned CRC = lodepng_crc32(&chunk[4], length + 4); lodepng_set32bitInt(chunk + 8 + length, CRC); } unsigned char* lodepng_chunk_next(unsigned char* chunk) { unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; return &chunk[total_chunk_length]; } const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk) { unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; return &chunk[total_chunk_length]; } unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk) { unsigned i; unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; unsigned char *chunk_start, *new_buffer; size_t new_length = (*outlength) + total_chunk_length; if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/ new_buffer = (unsigned char*)realloc(*out, new_length); if(!new_buffer) return 83; /*alloc fail*/ (*out) = new_buffer; (*outlength) = new_length; chunk_start = &(*out)[new_length - total_chunk_length]; for(i = 0; i < total_chunk_length; i++) chunk_start[i] = chunk[i]; return 0; } unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, const char* type, const unsigned char* data) { unsigned i; unsigned char *chunk, *new_buffer; size_t new_length = (*outlength) + length + 12; if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/ new_buffer = (unsigned char*)realloc(*out, new_length); if(!new_buffer) return 83; /*alloc fail*/ (*out) = new_buffer; (*outlength) = new_length; chunk = &(*out)[(*outlength) - length - 12]; /*1: length*/ lodepng_set32bitInt(chunk, (unsigned)length); /*2: chunk name (4 letters)*/ chunk[4] = (unsigned char)type[0]; chunk[5] = (unsigned char)type[1]; chunk[6] = (unsigned char)type[2]; chunk[7] = (unsigned char)type[3]; /*3: the data*/ for(i = 0; i < length; i++) chunk[8 + i] = data[i]; /*4: CRC (of the chunkname characters and the data)*/ lodepng_chunk_generate_crc(chunk); return 0; } /* ////////////////////////////////////////////////////////////////////////// */ /* / Color types and such / */ /* ////////////////////////////////////////////////////////////////////////// */ /*return type is a LodePNG error code*/ static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/ { switch(colortype) { case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/ case 2: if(!( bd == 8 || bd == 16)) return 37; break; /*RGB*/ case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; /*palette*/ case 4: if(!( bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/ case 6: if(!( bd == 8 || bd == 16)) return 37; break; /*RGBA*/ default: return 31; } return 0; /*allowed color type / bits combination*/ } static unsigned getNumColorChannels(LodePNGColorType colortype) { switch(colortype) { case 0: return 1; /*grey*/ case 2: return 3; /*RGB*/ case 3: return 1; /*palette*/ case 4: return 2; /*grey + alpha*/ case 6: return 4; /*RGBA*/ } return 0; /*unexisting color type*/ } static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) { /*bits per pixel is amount of channels * bits per channel*/ return getNumColorChannels(colortype) * bitdepth; } /* ////////////////////////////////////////////////////////////////////////// */ void lodepng_color_mode_init(LodePNGColorMode* info) { info->key_defined = 0; info->key_r = info->key_g = info->key_b = 0; info->colortype = LCT_RGBA; info->bitdepth = 8; info->palette = 0; info->palettesize = 0; } void lodepng_color_mode_cleanup(LodePNGColorMode* info) { lodepng_palette_clear(info); } unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) { size_t i; lodepng_color_mode_cleanup(dest); *dest = *source; if(source->palette) { dest->palette = (unsigned char*)malloc(1024); if(!dest->palette && source->palettesize) return 83; /*alloc fail*/ for(i = 0; i < source->palettesize * 4; i++) dest->palette[i] = source->palette[i]; } return 0; } static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) { size_t i; if(a->colortype != b->colortype) return 0; if(a->bitdepth != b->bitdepth) return 0; if(a->key_defined != b->key_defined) return 0; if(a->key_defined) { if(a->key_r != b->key_r) return 0; if(a->key_g != b->key_g) return 0; if(a->key_b != b->key_b) return 0; } if(a->palettesize != b->palettesize) return 0; for(i = 0; i < a->palettesize * 4; i++) { if(a->palette[i] != b->palette[i]) return 0; } return 1; } void lodepng_palette_clear(LodePNGColorMode* info) { free(info->palette); info->palette = 0; info->palettesize = 0; } unsigned lodepng_palette_add(LodePNGColorMode* info, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { unsigned char* data; /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with the max of 256 colors, it'll have the exact alloc size*/ if(!info->palette) /*allocate palette if empty*/ { /*room for 256 colors with 4 bytes each*/ data = (unsigned char*)realloc(info->palette, 1024); if(!data) return 83; /*alloc fail*/ else info->palette = data; } info->palette[4 * info->palettesize + 0] = r; info->palette[4 * info->palettesize + 1] = g; info->palette[4 * info->palettesize + 2] = b; info->palette[4 * info->palettesize + 3] = a; info->palettesize++; return 0; } unsigned lodepng_get_bpp(const LodePNGColorMode* info) { /*calculate bits per pixel out of colortype and bitdepth*/ return lodepng_get_bpp_lct(info->colortype, info->bitdepth); } unsigned lodepng_get_channels(const LodePNGColorMode* info) { return getNumColorChannels(info->colortype); } unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) { return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA; } unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) { return (info->colortype & 4) != 0; /*4 or 6*/ } unsigned lodepng_is_palette_type(const LodePNGColorMode* info) { return info->colortype == LCT_PALETTE; } unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) { size_t i; for(i = 0; i < info->palettesize; i++) { if(info->palette[i * 4 + 3] < 255) return 1; } return 0; } unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) { return info->key_defined || lodepng_is_alpha_type(info) || lodepng_has_palette_alpha(info); } size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) { return (w * h * lodepng_get_bpp(color) + 7) / 8; } size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { return (w * h * lodepng_get_bpp_lct(colortype, bitdepth) + 7) / 8; } #ifdef LODEPNG_COMPILE_PNG #ifdef LODEPNG_COMPILE_DECODER /*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer*/ static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color) { return h * ((w * lodepng_get_bpp(color) + 7) / 8); } #endif /*LODEPNG_COMPILE_DECODER*/ #endif /*LODEPNG_COMPILE_PNG*/ #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS static void LodePNGUnknownChunks_init(LodePNGInfo* info) { unsigned i; for(i = 0; i < 3; i++) info->unknown_chunks_data[i] = 0; for(i = 0; i < 3; i++) info->unknown_chunks_size[i] = 0; } static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) { unsigned i; for(i = 0; i < 3; i++) free(info->unknown_chunks_data[i]); } static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) { unsigned i; LodePNGUnknownChunks_cleanup(dest); for(i = 0; i < 3; i++) { size_t j; dest->unknown_chunks_size[i] = src->unknown_chunks_size[i]; dest->unknown_chunks_data[i] = (unsigned char*)malloc(src->unknown_chunks_size[i]); if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/ for(j = 0; j < src->unknown_chunks_size[i]; j++) { dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j]; } } return 0; } /******************************************************************************/ static void LodePNGText_init(LodePNGInfo* info) { info->text_num = 0; info->text_keys = NULL; info->text_strings = NULL; } static void LodePNGText_cleanup(LodePNGInfo* info) { size_t i; for(i = 0; i < info->text_num; i++) { string_cleanup(&info->text_keys[i]); string_cleanup(&info->text_strings[i]); } free(info->text_keys); free(info->text_strings); } static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) { size_t i = 0; dest->text_keys = 0; dest->text_strings = 0; dest->text_num = 0; for(i = 0; i < source->text_num; i++) { CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i])); } return 0; } void lodepng_clear_text(LodePNGInfo* info) { LodePNGText_cleanup(info); } unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) { char** new_keys = (char**)(realloc(info->text_keys, sizeof(char*) * (info->text_num + 1))); char** new_strings = (char**)(realloc(info->text_strings, sizeof(char*) * (info->text_num + 1))); if(!new_keys || !new_strings) { free(new_keys); free(new_strings); return 83; /*alloc fail*/ } info->text_num++; info->text_keys = new_keys; info->text_strings = new_strings; string_init(&info->text_keys[info->text_num - 1]); string_set(&info->text_keys[info->text_num - 1], key); string_init(&info->text_strings[info->text_num - 1]); string_set(&info->text_strings[info->text_num - 1], str); return 0; } /******************************************************************************/ static void LodePNGIText_init(LodePNGInfo* info) { info->itext_num = 0; info->itext_keys = NULL; info->itext_langtags = NULL; info->itext_transkeys = NULL; info->itext_strings = NULL; } static void LodePNGIText_cleanup(LodePNGInfo* info) { size_t i; for(i = 0; i < info->itext_num; i++) { string_cleanup(&info->itext_keys[i]); string_cleanup(&info->itext_langtags[i]); string_cleanup(&info->itext_transkeys[i]); string_cleanup(&info->itext_strings[i]); } free(info->itext_keys); free(info->itext_langtags); free(info->itext_transkeys); free(info->itext_strings); } static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) { size_t i = 0; dest->itext_keys = 0; dest->itext_langtags = 0; dest->itext_transkeys = 0; dest->itext_strings = 0; dest->itext_num = 0; for(i = 0; i < source->itext_num; i++) { CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i], source->itext_transkeys[i], source->itext_strings[i])); } return 0; } void lodepng_clear_itext(LodePNGInfo* info) { LodePNGIText_cleanup(info); } unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, const char* transkey, const char* str) { char** new_keys = (char**)(realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1))); char** new_langtags = (char**)(realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1))); char** new_transkeys = (char**)(realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1))); char** new_strings = (char**)(realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1))); if(!new_keys || !new_langtags || !new_transkeys || !new_strings) { free(new_keys); free(new_langtags); free(new_transkeys); free(new_strings); return 83; /*alloc fail*/ } info->itext_num++; info->itext_keys = new_keys; info->itext_langtags = new_langtags; info->itext_transkeys = new_transkeys; info->itext_strings = new_strings; string_init(&info->itext_keys[info->itext_num - 1]); string_set(&info->itext_keys[info->itext_num - 1], key); string_init(&info->itext_langtags[info->itext_num - 1]); string_set(&info->itext_langtags[info->itext_num - 1], langtag); string_init(&info->itext_transkeys[info->itext_num - 1]); string_set(&info->itext_transkeys[info->itext_num - 1], transkey); string_init(&info->itext_strings[info->itext_num - 1]); string_set(&info->itext_strings[info->itext_num - 1], str); return 0; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ void lodepng_info_init(LodePNGInfo* info) { lodepng_color_mode_init(&info->color); info->interlace_method = 0; info->compression_method = 0; info->filter_method = 0; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS info->background_defined = 0; info->background_r = info->background_g = info->background_b = 0; LodePNGText_init(info); LodePNGIText_init(info); info->time_defined = 0; info->phys_defined = 0; LodePNGUnknownChunks_init(info); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } void lodepng_info_cleanup(LodePNGInfo* info) { lodepng_color_mode_cleanup(&info->color); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS LodePNGText_cleanup(info); LodePNGIText_cleanup(info); LodePNGUnknownChunks_cleanup(info); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) { lodepng_info_cleanup(dest); *dest = *source; lodepng_color_mode_init(&dest->color); CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color)); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS CERROR_TRY_RETURN(LodePNGText_copy(dest, source)); CERROR_TRY_RETURN(LodePNGIText_copy(dest, source)); LodePNGUnknownChunks_init(dest); CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source)); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ return 0; } void lodepng_info_swap(LodePNGInfo* a, LodePNGInfo* b) { LodePNGInfo temp = *a; *a = *b; *b = temp; } /* ////////////////////////////////////////////////////////////////////////// */ /*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/ static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) { unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/ /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/ unsigned p = index & m; in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/ in = in << (bits * (m - p)); if(p == 0) out[index * bits / 8] = in; else out[index * bits / 8] |= in; } typedef struct ColorTree ColorTree; /* One node of a color tree This is the data structure used to count the number of unique colors and to get a palette index for a color. It's like an octree, but because the alpha channel is used too, each node has 16 instead of 8 children. */ struct ColorTree { ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/ int index; /*the payload. Only has a meaningful value if this is in the last level*/ }; static void color_tree_init(ColorTree* tree) { int i; for(i = 0; i < 16; i++) tree->children[i] = 0; tree->index = -1; } static void color_tree_cleanup(ColorTree* tree) { int i; for(i = 0; i < 16; i++) { if(tree->children[i]) { color_tree_cleanup(tree->children[i]); free(tree->children[i]); } } } /*returns -1 if color not present, its index otherwise*/ static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { int bit = 0; for(bit = 0; bit < 8; bit++) { int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); if(!tree->children[i]) return -1; else tree = tree->children[i]; } return tree ? tree->index : -1; } #ifdef LODEPNG_COMPILE_ENCODER static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { return color_tree_get(tree, r, g, b, a) >= 0; } #endif /*LODEPNG_COMPILE_ENCODER*/ /*color is not allowed to already exist. Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/ static void color_tree_add(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) { int bit; for(bit = 0; bit < 8; bit++) { int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); if(!tree->children[i]) { tree->children[i] = (ColorTree*)malloc(sizeof(ColorTree)); color_tree_init(tree->children[i]); } tree = tree->children[i]; } tree->index = (int)index; } /*put a pixel, given its RGBA color, into image of any color type*/ static unsigned rgba8ToPixel(unsigned char* out, size_t i, const LodePNGColorMode* mode, ColorTree* tree /*for palette*/, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { if(mode->colortype == LCT_GREY) { unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/; if(mode->bitdepth == 8) out[i] = grey; else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey; else { /*take the most significant bits of grey*/ grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1); addColorBits(out, i, mode->bitdepth, grey); } } else if(mode->colortype == LCT_RGB) { if(mode->bitdepth == 8) { out[i * 3 + 0] = r; out[i * 3 + 1] = g; out[i * 3 + 2] = b; } else { out[i * 6 + 0] = out[i * 6 + 1] = r; out[i * 6 + 2] = out[i * 6 + 3] = g; out[i * 6 + 4] = out[i * 6 + 5] = b; } } else if(mode->colortype == LCT_PALETTE) { int index = color_tree_get(tree, r, g, b, a); if(index < 0) return 82; /*color not in palette*/ if(mode->bitdepth == 8) out[i] = index; else addColorBits(out, i, mode->bitdepth, (unsigned)index); } else if(mode->colortype == LCT_GREY_ALPHA) { unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/; if(mode->bitdepth == 8) { out[i * 2 + 0] = grey; out[i * 2 + 1] = a; } else if(mode->bitdepth == 16) { out[i * 4 + 0] = out[i * 4 + 1] = grey; out[i * 4 + 2] = out[i * 4 + 3] = a; } } else if(mode->colortype == LCT_RGBA) { if(mode->bitdepth == 8) { out[i * 4 + 0] = r; out[i * 4 + 1] = g; out[i * 4 + 2] = b; out[i * 4 + 3] = a; } else { out[i * 8 + 0] = out[i * 8 + 1] = r; out[i * 8 + 2] = out[i * 8 + 3] = g; out[i * 8 + 4] = out[i * 8 + 5] = b; out[i * 8 + 6] = out[i * 8 + 7] = a; } } return 0; /*no error*/ } /*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/ static void rgba16ToPixel(unsigned char* out, size_t i, const LodePNGColorMode* mode, unsigned short r, unsigned short g, unsigned short b, unsigned short a) { if(mode->colortype == LCT_GREY) { unsigned short grey = r; /*((unsigned)r + g + b) / 3*/; out[i * 2 + 0] = (grey >> 8) & 255; out[i * 2 + 1] = grey & 255; } else if(mode->colortype == LCT_RGB) { out[i * 6 + 0] = (r >> 8) & 255; out[i * 6 + 1] = r & 255; out[i * 6 + 2] = (g >> 8) & 255; out[i * 6 + 3] = g & 255; out[i * 6 + 4] = (b >> 8) & 255; out[i * 6 + 5] = b & 255; } else if(mode->colortype == LCT_GREY_ALPHA) { unsigned short grey = r; /*((unsigned)r + g + b) / 3*/; out[i * 4 + 0] = (grey >> 8) & 255; out[i * 4 + 1] = grey & 255; out[i * 4 + 2] = (a >> 8) & 255; out[i * 4 + 3] = a & 255; } else if(mode->colortype == LCT_RGBA) { out[i * 8 + 0] = (r >> 8) & 255; out[i * 8 + 1] = r & 255; out[i * 8 + 2] = (g >> 8) & 255; out[i * 8 + 3] = g & 255; out[i * 8 + 4] = (b >> 8) & 255; out[i * 8 + 5] = b & 255; out[i * 8 + 6] = (a >> 8) & 255; out[i * 8 + 7] = a & 255; } } /*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/ static void getPixelColorRGBA8(unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a, const unsigned char* in, size_t i, const LodePNGColorMode* mode) { if(mode->colortype == LCT_GREY) { if(mode->bitdepth == 8) { *r = *g = *b = in[i]; if(mode->key_defined && *r == mode->key_r) *a = 0; else *a = 255; } else if(mode->bitdepth == 16) { *r = *g = *b = in[i * 2 + 0]; if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; else *a = 255; } else { unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ size_t j = i * mode->bitdepth; unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); *r = *g = *b = (value * 255) / highest; if(mode->key_defined && value == mode->key_r) *a = 0; else *a = 255; } } else if(mode->colortype == LCT_RGB) { if(mode->bitdepth == 8) { *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2]; if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0; else *a = 255; } else { *r = in[i * 6 + 0]; *g = in[i * 6 + 2]; *b = in[i * 6 + 4]; if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; else *a = 255; } } else if(mode->colortype == LCT_PALETTE) { unsigned index; if(mode->bitdepth == 8) index = in[i]; else { size_t j = i * mode->bitdepth; index = readBitsFromReversedStream(&j, in, mode->bitdepth); } if(index >= mode->palettesize) { /*This is an error according to the PNG spec, but common PNG decoders make it black instead. Done here too, slightly faster due to no error handling needed.*/ *r = *g = *b = 0; *a = 255; } else { *r = mode->palette[index * 4 + 0]; *g = mode->palette[index * 4 + 1]; *b = mode->palette[index * 4 + 2]; *a = mode->palette[index * 4 + 3]; } } else if(mode->colortype == LCT_GREY_ALPHA) { if(mode->bitdepth == 8) { *r = *g = *b = in[i * 2 + 0]; *a = in[i * 2 + 1]; } else { *r = *g = *b = in[i * 4 + 0]; *a = in[i * 4 + 2]; } } else if(mode->colortype == LCT_RGBA) { if(mode->bitdepth == 8) { *r = in[i * 4 + 0]; *g = in[i * 4 + 1]; *b = in[i * 4 + 2]; *a = in[i * 4 + 3]; } else { *r = in[i * 8 + 0]; *g = in[i * 8 + 2]; *b = in[i * 8 + 4]; *a = in[i * 8 + 6]; } } } /*Similar to getPixelColorRGBA8, but with all the for loops inside of the color mode test cases, optimized to convert the colors much faster, when converting to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with enough memory, if has_alpha is true the output is RGBA. mode has the color mode of the input buffer.*/ static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels, unsigned has_alpha, const unsigned char* in, const LodePNGColorMode* mode) { unsigned num_channels = has_alpha ? 4 : 3; size_t i; if(mode->colortype == LCT_GREY) { if(mode->bitdepth == 8) { for(i = 0; i < numpixels; i++, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i]; if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255; } } else if(mode->bitdepth == 16) { for(i = 0; i < numpixels; i++, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i * 2]; if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255; } } else { unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ size_t j = 0; for(i = 0; i < numpixels; i++, buffer += num_channels) { unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest; if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255; } } } else if(mode->colortype == LCT_RGB) { if(mode->bitdepth == 8) { for(i = 0; i < numpixels; i++, buffer += num_channels) { buffer[0] = in[i * 3 + 0]; buffer[1] = in[i * 3 + 1]; buffer[2] = in[i * 3 + 2]; if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r && buffer[1]== mode->key_g && buffer[2] == mode->key_b ? 0 : 255; } } else { for(i = 0; i < numpixels; i++, buffer += num_channels) { buffer[0] = in[i * 6 + 0]; buffer[1] = in[i * 6 + 2]; buffer[2] = in[i * 6 + 4]; if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255; } } } else if(mode->colortype == LCT_PALETTE) { unsigned index; size_t j = 0; for(i = 0; i < numpixels; i++, buffer += num_channels) { if(mode->bitdepth == 8) index = in[i]; else index = readBitsFromReversedStream(&j, in, mode->bitdepth); if(index >= mode->palettesize) { /*This is an error according to the PNG spec, but most PNG decoders make it black instead. Done here too, slightly faster due to no error handling needed.*/ buffer[0] = buffer[1] = buffer[2] = 0; if(has_alpha) buffer[3] = 255; } else { buffer[0] = mode->palette[index * 4 + 0]; buffer[1] = mode->palette[index * 4 + 1]; buffer[2] = mode->palette[index * 4 + 2]; if(has_alpha) buffer[3] = mode->palette[index * 4 + 3]; } } } else if(mode->colortype == LCT_GREY_ALPHA) { if(mode->bitdepth == 8) { for(i = 0; i < numpixels; i++, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0]; if(has_alpha) buffer[3] = in[i * 2 + 1]; } } else { for(i = 0; i < numpixels; i++, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; if(has_alpha) buffer[3] = in[i * 4 + 2]; } } } else if(mode->colortype == LCT_RGBA) { if(mode->bitdepth == 8) { for(i = 0; i < numpixels; i++, buffer += num_channels) { buffer[0] = in[i * 4 + 0]; buffer[1] = in[i * 4 + 1]; buffer[2] = in[i * 4 + 2]; if(has_alpha) buffer[3] = in[i * 4 + 3]; } } else { for(i = 0; i < numpixels; i++, buffer += num_channels) { buffer[0] = in[i * 8 + 0]; buffer[1] = in[i * 8 + 2]; buffer[2] = in[i * 8 + 4]; if(has_alpha) buffer[3] = in[i * 8 + 6]; } } } } /*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with given color type, but the given color type must be 16-bit itself.*/ static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a, const unsigned char* in, size_t i, const LodePNGColorMode* mode) { if(mode->colortype == LCT_GREY) { *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1]; if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; else *a = 65535; } else if(mode->colortype == LCT_RGB) { *r = 256 * in[i * 6 + 0] + in[i * 6 + 1]; *g = 256 * in[i * 6 + 2] + in[i * 6 + 3]; *b = 256 * in[i * 6 + 4] + in[i * 6 + 5]; if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; else *a = 65535; } else if(mode->colortype == LCT_GREY_ALPHA) { *r = *g = *b = 256 * in[i * 4 + 0] + in[i * 4 + 1]; *a = 256 * in[i * 4 + 2] + in[i * 4 + 3]; } else if(mode->colortype == LCT_RGBA) { *r = 256 * in[i * 8 + 0] + in[i * 8 + 1]; *g = 256 * in[i * 8 + 2] + in[i * 8 + 3]; *b = 256 * in[i * 8 + 4] + in[i * 8 + 5]; *a = 256 * in[i * 8 + 6] + in[i * 8 + 7]; } } unsigned lodepng_convert(unsigned char* out, const unsigned char* in, LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, unsigned w, unsigned h) { size_t i; ColorTree tree; size_t numpixels = w * h; if(lodepng_color_mode_equal(mode_out, mode_in)) { size_t numbytes = lodepng_get_raw_size(w, h, mode_in); for(i = 0; i < numbytes; i++) out[i] = in[i]; return 0; } if(mode_out->colortype == LCT_PALETTE) { size_t palsize = 1u << mode_out->bitdepth; if(mode_out->palettesize < palsize) palsize = mode_out->palettesize; color_tree_init(&tree); for(i = 0; i < palsize; i++) { unsigned char* p = &mode_out->palette[i * 4]; color_tree_add(&tree, p[0], p[1], p[2], p[3], i); } } if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) { for(i = 0; i < numpixels; i++) { unsigned short r = 0, g = 0, b = 0, a = 0; getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); rgba16ToPixel(out, i, mode_out, r, g, b, a); } } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) { getPixelColorsRGBA8(out, numpixels, 1, in, mode_in); } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) { getPixelColorsRGBA8(out, numpixels, 0, in, mode_in); } else { unsigned char r = 0, g = 0, b = 0, a = 0; for(i = 0; i < numpixels; i++) { getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a); } } if(mode_out->colortype == LCT_PALETTE) { color_tree_cleanup(&tree); } return 0; /*no error (this function currently never has one, but maybe OOM detection added later.)*/ } #ifdef LODEPNG_COMPILE_ENCODER void lodepng_color_profile_init(LodePNGColorProfile* profile) { profile->colored = 0; profile->key = 0; profile->alpha = 0; profile->key_r = profile->key_g = profile->key_b = 0; profile->numcolors = 0; profile->bits = 1; } /*function used for debug purposes with C++*/ /*void printColorProfile(LodePNGColorProfile* p) { std::cout << "colored: " << (int)p->colored << ", "; std::cout << "key: " << (int)p->key << ", "; std::cout << "key_r: " << (int)p->key_r << ", "; std::cout << "key_g: " << (int)p->key_g << ", "; std::cout << "key_b: " << (int)p->key_b << ", "; std::cout << "alpha: " << (int)p->alpha << ", "; std::cout << "numcolors: " << (int)p->numcolors << ", "; std::cout << "bits: " << (int)p->bits << std::endl; }*/ /*Returns how many bits needed to represent given value (max 8 bit)*/ unsigned getValueRequiredBits(unsigned char value) { if(value == 0 || value == 255) return 1; /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/ if(value % 17 == 0) return value % 85 == 0 ? 2 : 4; return 8; } /*profile must already have been inited with mode. It's ok to set some parameters of profile to done already.*/ unsigned get_color_profile(LodePNGColorProfile* profile, const unsigned char* in, unsigned w, unsigned h, const LodePNGColorMode* mode) { unsigned error = 0; size_t i; ColorTree tree; size_t numpixels = w * h; unsigned colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0; unsigned alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1; unsigned numcolors_done = 0; unsigned bpp = lodepng_get_bpp(mode); unsigned bits_done = bpp == 1 ? 1 : 0; unsigned maxnumcolors = 257; unsigned sixteen = 0; if(bpp <= 8) maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256)); color_tree_init(&tree); /*Check if the 16-bit input is truly 16-bit*/ if(mode->bitdepth == 16) { unsigned short r, g, b, a; for(i = 0; i < numpixels; i++) { getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); if(r % 257u != 0 || g % 257u != 0 || b % 257u != 0 || a % 257u != 0) /*first and second byte differ*/ { sixteen = 1; break; } } } if(sixteen) { unsigned short r = 0, g = 0, b = 0, a = 0; profile->bits = 16; bits_done = numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/ for(i = 0; i < numpixels; i++) { getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); if(!colored_done && (r != g || r != b)) { profile->colored = 1; colored_done = 1; } if(!alpha_done) { unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); if(a != 65535 && (a != 0 || (profile->key && !matchkey))) { profile->alpha = 1; alpha_done = 1; if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } else if(a == 0 && !profile->alpha && !profile->key) { profile->key = 1; profile->key_r = r; profile->key_g = g; profile->key_b = b; } else if(a == 65535 && profile->key && matchkey) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; alpha_done = 1; } } if(alpha_done && numcolors_done && colored_done && bits_done) break; } } else /* < 16-bit */ { for(i = 0; i < numpixels; i++) { unsigned char r = 0, g = 0, b = 0, a = 0; getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode); if(!bits_done && profile->bits < 8) { /*only r is checked, < 8 bits is only relevant for greyscale*/ unsigned bits = getValueRequiredBits(r); if(bits > profile->bits) profile->bits = bits; } bits_done = (profile->bits >= bpp); if(!colored_done && (r != g || r != b)) { profile->colored = 1; colored_done = 1; if(profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/ } if(!alpha_done) { unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); if(a != 255 && (a != 0 || (profile->key && !matchkey))) { profile->alpha = 1; alpha_done = 1; if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } else if(a == 0 && !profile->alpha && !profile->key) { profile->key = 1; profile->key_r = r; profile->key_g = g; profile->key_b = b; } else if(a == 255 && profile->key && matchkey) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; alpha_done = 1; if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } } if(!numcolors_done) { if(!color_tree_has(&tree, r, g, b, a)) { color_tree_add(&tree, r, g, b, a, profile->numcolors); if(profile->numcolors < 256) { unsigned char* p = profile->palette; unsigned n = profile->numcolors; p[n * 4 + 0] = r; p[n * 4 + 1] = g; p[n * 4 + 2] = b; p[n * 4 + 3] = a; } profile->numcolors++; numcolors_done = profile->numcolors >= maxnumcolors; } } if(alpha_done && numcolors_done && colored_done && bits_done) break; } /*make the profile's key always 16-bit for consistency - repeat each byte twice*/ profile->key_r *= 257; profile->key_g *= 257; profile->key_b *= 257; } color_tree_cleanup(&tree); return error; } /*Automatically chooses color type that gives smallest amount of bits in the output image, e.g. grey if there are only greyscale pixels, palette if there are less than 256 colors, ... Updates values of mode with a potentially smaller color model. mode_out should contain the user chosen color model, but will be overwritten with the new chosen one.*/ unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, const unsigned char* image, unsigned w, unsigned h, const LodePNGColorMode* mode_in) { LodePNGColorProfile prof; unsigned error = 0; unsigned i, n, palettebits, grey_ok, palette_ok; lodepng_color_profile_init(&prof); error = get_color_profile(&prof, image, w, h, mode_in); if(error) return error; mode_out->key_defined = 0; if(prof.key && w * h <= 16) prof.alpha = 1; /*too few pixels to justify tRNS chunk overhead*/ grey_ok = !prof.colored && !prof.alpha; /*grey without alpha, with potentially low bits*/ n = prof.numcolors; palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8)); palette_ok = n <= 256 && (n * 2 < w * h) && prof.bits <= 8; if(w * h < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ if(grey_ok && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/ if(palette_ok) { unsigned char* p = prof.palette; lodepng_palette_clear(mode_out); /*remove potential earlier palette*/ for(i = 0; i < prof.numcolors; i++) { error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]); if(error) break; } mode_out->colortype = LCT_PALETTE; mode_out->bitdepth = palettebits; if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize && mode_in->bitdepth == mode_out->bitdepth) { /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/ lodepng_color_mode_cleanup(mode_out); lodepng_color_mode_copy(mode_out, mode_in); } } else /*8-bit or 16-bit per channel*/ { mode_out->bitdepth = prof.bits; mode_out->colortype = prof.alpha ? (prof.colored ? LCT_RGBA : LCT_GREY_ALPHA) : (prof.colored ? LCT_RGB : LCT_GREY); if(prof.key && !prof.alpha) { unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/ mode_out->key_r = prof.key_r & mask; mode_out->key_g = prof.key_g & mask; mode_out->key_b = prof.key_b & mask; mode_out->key_defined = 1; } } return error; } #endif /* #ifdef LODEPNG_COMPILE_ENCODER */ /* Paeth predicter, used by PNG filter type 4 The parameters are of type short, but should come from unsigned chars, the shorts are only needed to make the paeth calculation correct. */ static unsigned char paethPredictor(short a, short b, short c) { short pa = abs(b - c); short pb = abs(a - c); short pc = abs(a + b - c - c); if(pc < pa && pc < pb) return (unsigned char)c; else if(pb < pa) return (unsigned char)b; else return (unsigned char)a; } /*shared values used by multiple Adam7 related functions*/ static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/ static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/ static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/ static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/ /* Outputs various dimensions and positions in the image related to the Adam7 reduced images. passw: output containing the width of the 7 passes passh: output containing the height of the 7 passes filter_passstart: output containing the index of the start and end of each reduced image with filter bytes padded_passstart output containing the index of the start and end of each reduced image when without filter bytes but with padded scanlines passstart: output containing the index of the start and end of each reduced image without padding between scanlines, but still padding between the images w, h: width and height of non-interlaced image bpp: bits per pixel "padded" is only relevant if bpp is less than 8 and a scanline or image does not end at a full byte */ static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8], size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) { /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/ unsigned i; /*calculate width and height in pixels of each pass*/ for(i = 0; i < 7; i++) { passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i]; passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i]; if(passw[i] == 0) passh[i] = 0; if(passh[i] == 0) passw[i] = 0; } filter_passstart[0] = padded_passstart[0] = passstart[0] = 0; for(i = 0; i < 7; i++) { /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/ filter_passstart[i + 1] = filter_passstart[i] + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0); /*bits padded if needed to fill full byte at end of each scanline*/ padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8); /*only padded at end of reduced image*/ passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8; } } #ifdef LODEPNG_COMPILE_DECODER /* ////////////////////////////////////////////////////////////////////////// */ /* / PNG Decoder / */ /* ////////////////////////////////////////////////////////////////////////// */ /*read the information from the header and store it in the LodePNGInfo. return value is error*/ unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize) { LodePNGInfo* info = &state->info_png; if(insize == 0 || in == 0) { CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/ } if(insize < 29) { CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/ } /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/ lodepng_info_cleanup(info); lodepng_info_init(info); if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) { CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/ } if(in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R') { CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/ } /*read the values given in the header*/ *w = lodepng_read32bitInt(&in[16]); *h = lodepng_read32bitInt(&in[20]); info->color.bitdepth = in[24]; info->color.colortype = (LodePNGColorType)in[25]; info->compression_method = in[26]; info->filter_method = in[27]; info->interlace_method = in[28]; if(!state->decoder.ignore_crc) { unsigned CRC = lodepng_read32bitInt(&in[29]); unsigned checksum = lodepng_crc32(&in[12], 17); if(CRC != checksum) { CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/ } } /*error: only compression method 0 is allowed in the specification*/ if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32); /*error: only filter method 0 is allowed in the specification*/ if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33); /*error: only interlace methods 0 and 1 exist in the specification*/ if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34); state->error = checkColorValidity(info->color.colortype, info->color.bitdepth); return state->error; } static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon, size_t bytewidth, unsigned char filterType, size_t length) { /* For PNG filter method 0 unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte, the filter works byte per byte (bytewidth = 1) precon is the previous unfiltered scanline, recon the result, scanline the current one the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead recon and scanline MAY be the same memory address! precon must be disjoint. */ size_t i; switch(filterType) { case 0: for(i = 0; i < length; i++) recon[i] = scanline[i]; break; case 1: for(i = 0; i < bytewidth; i++) recon[i] = scanline[i]; for(i = bytewidth; i < length; i++) recon[i] = scanline[i] + recon[i - bytewidth]; break; case 2: if(precon) { for(i = 0; i < length; i++) recon[i] = scanline[i] + precon[i]; } else { for(i = 0; i < length; i++) recon[i] = scanline[i]; } break; case 3: if(precon) { for(i = 0; i < bytewidth; i++) recon[i] = scanline[i] + precon[i] / 2; for(i = bytewidth; i < length; i++) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) / 2); } else { for(i = 0; i < bytewidth; i++) recon[i] = scanline[i]; for(i = bytewidth; i < length; i++) recon[i] = scanline[i] + recon[i - bytewidth] / 2; } break; case 4: if(precon) { for(i = 0; i < bytewidth; i++) { recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/ } for(i = bytewidth; i < length; i++) { recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth])); } } else { for(i = 0; i < bytewidth; i++) { recon[i] = scanline[i]; } for(i = bytewidth; i < length; i++) { /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/ recon[i] = (scanline[i] + recon[i - bytewidth]); } } break; default: return 36; /*error: unexisting filter type given*/ } return 0; } static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { /* For PNG filter method 0 this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times) out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes) */ unsigned y; unsigned char* prevline = 0; /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ size_t bytewidth = (bpp + 7) / 8; size_t linebytes = (w * bpp + 7) / 8; for(y = 0; y < h; y++) { size_t outindex = linebytes * y; size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ unsigned char filterType = in[inindex]; CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes)); prevline = &out[outindex]; } return 0; } /* in: Adam7 interlaced image, with no padding bits between scanlines, but between reduced images so that each reduced image starts at a byte. out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h bpp: bits per pixel out has the following size in bits: w * h * bpp. in is possibly bigger due to padding bits between reduced images. out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation (because that's likely a little bit faster) NOTE: comments about padding bits are only relevant if bpp < 8 */ static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; unsigned i; Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); if(bpp >= 8) { for(i = 0; i < 7; i++) { unsigned x, y, b; size_t bytewidth = bpp / 8; for(y = 0; y < passh[i]; y++) for(x = 0; x < passw[i]; x++) { size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth; size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; for(b = 0; b < bytewidth; b++) { out[pixeloutstart + b] = in[pixelinstart + b]; } } } } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ { for(i = 0; i < 7; i++) { unsigned x, y, b; unsigned ilinebits = bpp * passw[i]; unsigned olinebits = bpp * w; size_t obp, ibp; /*bit pointers (for out and in buffer)*/ for(y = 0; y < passh[i]; y++) for(x = 0; x < passw[i]; x++) { ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp); obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; for(b = 0; b < bpp; b++) { unsigned char bit = readBitFromReversedStream(&ibp, in); /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/ setBitOfReversedStream0(&obp, out, bit); } } } } } static void removePaddingBits(unsigned char* out, const unsigned char* in, size_t olinebits, size_t ilinebits, unsigned h) { /* After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers for the Adam7 code, the color convert code and the output to the user. in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7 only useful if (ilinebits - olinebits) is a value in the range 1..7 */ unsigned y; size_t diff = ilinebits - olinebits; size_t ibp = 0, obp = 0; /*input and output bit pointers*/ for(y = 0; y < h; y++) { size_t x; for(x = 0; x < olinebits; x++) { unsigned char bit = readBitFromReversedStream(&ibp, in); setBitOfReversedStream(&obp, out, bit); } ibp += diff; } } /*out must be buffer big enough to contain full image, and in must contain the full decompressed data from the IDAT chunks (with filter index bytes and possible padding bits) return value is error*/ static unsigned postProcessScanlines(unsigned char* out, unsigned char* in, unsigned w, unsigned h, const LodePNGInfo* info_png) { /* This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype. Steps: *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8) *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace NOTE: the in buffer will be overwritten with intermediate data! */ unsigned bpp = lodepng_get_bpp(&info_png->color); if(bpp == 0) return 31; /*error: invalid colortype*/ if(info_png->interlace_method == 0) { if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) { CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp)); removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h); } /*we can immediatly filter into the out buffer, no other steps needed*/ else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp)); } else /*interlace_method is 1 (Adam7)*/ { unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; unsigned i; Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); for(i = 0; i < 7; i++) { CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp)); /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline, move bytes instead of bits or move not at all*/ if(bpp < 8) { /*remove padding bits in scanlines; after this there still may be padding bits between the different reduced images: each reduced image still starts nicely at a byte*/ removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp, ((passw[i] * bpp + 7) / 8) * 8, passh[i]); } } Adam7_deinterlace(out, in, w, h, bpp); } return 0; } static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) { unsigned pos = 0, i; free(color->palette); color->palettesize = chunkLength / 3; color->palette = (unsigned char*)malloc(4 * color->palettesize); if(!color->palette && color->palettesize) { color->palettesize = 0; return 83; /*alloc fail*/ } if(color->palettesize > 256) return 38; /*error: palette too big*/ for(i = 0; i < color->palettesize; i++) { color->palette[4 * i + 0] = data[pos++]; /*R*/ color->palette[4 * i + 1] = data[pos++]; /*G*/ color->palette[4 * i + 2] = data[pos++]; /*B*/ color->palette[4 * i + 3] = 255; /*alpha*/ } return 0; /* OK */ } static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) { unsigned i; if(color->colortype == LCT_PALETTE) { /*error: more alpha values given than there are palette entries*/ if(chunkLength > color->palettesize) return 38; for(i = 0; i < chunkLength; i++) color->palette[4 * i + 3] = data[i]; } else if(color->colortype == LCT_GREY) { /*error: this chunk must be 2 bytes for greyscale image*/ if(chunkLength != 2) return 30; color->key_defined = 1; color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1]; } else if(color->colortype == LCT_RGB) { /*error: this chunk must be 6 bytes for RGB image*/ if(chunkLength != 6) return 41; color->key_defined = 1; color->key_r = 256u * data[0] + data[1]; color->key_g = 256u * data[2] + data[3]; color->key_b = 256u * data[4] + data[5]; } else return 42; /*error: tRNS chunk not allowed for other color models*/ return 0; /* OK */ } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*background color chunk (bKGD)*/ static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if(info->color.colortype == LCT_PALETTE) { /*error: this chunk must be 1 byte for indexed color image*/ if(chunkLength != 1) return 43; info->background_defined = 1; info->background_r = info->background_g = info->background_b = data[0]; } else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) { /*error: this chunk must be 2 bytes for greyscale image*/ if(chunkLength != 2) return 44; info->background_defined = 1; info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1]; } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) { /*error: this chunk must be 6 bytes for greyscale image*/ if(chunkLength != 6) return 45; info->background_defined = 1; info->background_r = 256u * data[0] + data[1]; info->background_g = 256u * data[2] + data[3]; info->background_b = 256u * data[4] + data[5]; } return 0; /* OK */ } /*text chunk (tEXt)*/ static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { unsigned error = 0; char *key = 0, *str = 0; unsigned i; while(!error) /*not really a while loop, only used to break on error*/ { unsigned length, string2_begin; length = 0; while(length < chunkLength && data[length] != 0) length++; /*even though it's not allowed by the standard, no error is thrown if there's no null termination char, if the text is empty*/ if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ key = (char*)malloc(length + 1); if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ key[length] = 0; for(i = 0; i < length; i++) key[i] = (char)data[i]; string2_begin = length + 1; /*skip keyword null terminator*/ length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin; str = (char*)malloc(length + 1); if(!str) CERROR_BREAK(error, 83); /*alloc fail*/ str[length] = 0; for(i = 0; i < length; i++) str[i] = (char)data[string2_begin + i]; error = lodepng_add_text(info, key, str); break; } free(key); free(str); return error; } /*compressed text chunk (zTXt)*/ static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, const unsigned char* data, size_t chunkLength) { unsigned error = 0; unsigned i; unsigned length, string2_begin; char *key = 0; ucvector decoded; ucvector_init(&decoded); while(!error) /*not really a while loop, only used to break on error*/ { for(length = 0; length < chunkLength && data[length] != 0; length++) ; if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ key = (char*)malloc(length + 1); if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ key[length] = 0; for(i = 0; i < length; i++) key[i] = (char)data[i]; if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ string2_begin = length + 2; if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ length = chunkLength - string2_begin; /*will fail if zlib error, e.g. if length is too small*/ error = zlib_decompress(&decoded.data, &decoded.size, (unsigned char*)(&data[string2_begin]), length, zlibsettings); if(error) break; if (!ucvector_push_back(&decoded, 0)) ERROR_BREAK(83); error = lodepng_add_text(info, key, (char*)decoded.data); break; } free(key); ucvector_cleanup(&decoded); return error; } /*international text chunk (iTXt)*/ static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, const unsigned char* data, size_t chunkLength) { unsigned error = 0; unsigned i; unsigned length, begin, compressed; char *key = 0, *langtag = 0, *transkey = 0; ucvector decoded; ucvector_init(&decoded); while(!error) /*not really a while loop, only used to break on error*/ { /*Quick check if the chunk length isn't too small. Even without check it'd still fail with other error checks below if it's too short. This just gives a different error code.*/ if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/ /*read the key*/ for(length = 0; length < chunkLength && data[length] != 0; length++) ; if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/ if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ key = (char*)malloc(length + 1); if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ key[length] = 0; for(i = 0; i < length; i++) key[i] = (char)data[i]; /*read the compression method*/ compressed = data[length + 1]; if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ /*even though it's not allowed by the standard, no error is thrown if there's no null termination char, if the text is empty for the next 3 texts*/ /*read the langtag*/ begin = length + 3; length = 0; for(i = begin; i < chunkLength && data[i] != 0; i++) length++; langtag = (char*)malloc(length + 1); if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/ langtag[length] = 0; for(i = 0; i < length; i++) langtag[i] = (char)data[begin + i]; /*read the transkey*/ begin += length + 1; length = 0; for(i = begin; i < chunkLength && data[i] != 0; i++) length++; transkey = (char*)malloc(length + 1); if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/ transkey[length] = 0; for(i = 0; i < length; i++) transkey[i] = (char)data[begin + i]; /*read the actual text*/ begin += length + 1; length = chunkLength < begin ? 0 : chunkLength - begin; if(compressed) { /*will fail if zlib error, e.g. if length is too small*/ error = zlib_decompress(&decoded.data, &decoded.size, (unsigned char*)(&data[begin]), length, zlibsettings); if(error) break; if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size; if (!ucvector_push_back(&decoded, 0)) CERROR_BREAK(error, 83 /*alloc fail*/); } else { if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/); decoded.data[length] = 0; for(i = 0; i < length; i++) decoded.data[i] = data[begin + i]; } error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data); break; } free(key); free(langtag); free(transkey); ucvector_cleanup(&decoded); return error; } static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if(chunkLength != 7) return 73; /*invalid tIME chunk size*/ info->time_defined = 1; info->time.year = 256u * data[0] + data[1]; info->time.month = data[2]; info->time.day = data[3]; info->time.hour = data[4]; info->time.minute = data[5]; info->time.second = data[6]; return 0; /* OK */ } static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/ info->phys_defined = 1; info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7]; info->phys_unit = data[8]; return 0; /* OK */ } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize) { unsigned char IEND = 0; const unsigned char* chunk; size_t i; ucvector idat; /*the data from idat chunks*/ ucvector scanlines; size_t predict; /*for unknown chunk order*/ unsigned unknown = 0; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*provide some proper output values if error will happen*/ *out = 0; state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/ if(state->error) return; ucvector_init(&idat); chunk = &in[33]; /*first byte of the first chunk after the header*/ /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. IDAT data is put at the start of the in buffer*/ while(!IEND && !state->error) { unsigned chunkLength; const unsigned char* data; /*the data in the chunk*/ /*error: size of the in buffer too small to contain next chunk*/ if((size_t)((chunk - in) + 12) > insize || chunk < in) CERROR_BREAK(state->error, 30); /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/ chunkLength = lodepng_chunk_length(chunk); /*error: chunk length larger than the max PNG chunk size*/ if(chunkLength > 2147483647) CERROR_BREAK(state->error, 63); if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) { CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/ } data = lodepng_chunk_data_const(chunk); /*IDAT chunk, containing compressed image data*/ if(lodepng_chunk_type_equals(chunk, "IDAT")) { size_t oldsize = idat.size; if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/); for(i = 0; i < chunkLength; i++) idat.data[oldsize + i] = data[i]; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS critical_pos = 3; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } /*IEND chunk*/ else if(lodepng_chunk_type_equals(chunk, "IEND")) { IEND = 1; } /*palette chunk (PLTE)*/ else if(lodepng_chunk_type_equals(chunk, "PLTE")) { state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength); if(state->error) break; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS critical_pos = 2; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } /*palette transparency chunk (tRNS)*/ else if(lodepng_chunk_type_equals(chunk, "tRNS")) { state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength); if(state->error) break; } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*background color chunk (bKGD)*/ else if(lodepng_chunk_type_equals(chunk, "bKGD")) { state->error = readChunk_bKGD(&state->info_png, data, chunkLength); if(state->error) break; } /*text chunk (tEXt)*/ else if(lodepng_chunk_type_equals(chunk, "tEXt")) { if(state->decoder.read_text_chunks) { state->error = readChunk_tEXt(&state->info_png, data, chunkLength); if(state->error) break; } } /*compressed text chunk (zTXt)*/ else if(lodepng_chunk_type_equals(chunk, "zTXt")) { if(state->decoder.read_text_chunks) { state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); if(state->error) break; } } /*international text chunk (iTXt)*/ else if(lodepng_chunk_type_equals(chunk, "iTXt")) { if(state->decoder.read_text_chunks) { state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); if(state->error) break; } } else if(lodepng_chunk_type_equals(chunk, "tIME")) { state->error = readChunk_tIME(&state->info_png, data, chunkLength); if(state->error) break; } else if(lodepng_chunk_type_equals(chunk, "pHYs")) { state->error = readChunk_pHYs(&state->info_png, data, chunkLength); if(state->error) break; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ else /*it's not an implemented chunk type, so ignore it: skip over the data*/ { /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/ if(!lodepng_chunk_ancillary(chunk)) CERROR_BREAK(state->error, 69); unknown = 1; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS if(state->decoder.remember_unknown_chunks) { state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1], &state->info_png.unknown_chunks_size[critical_pos - 1], chunk); if(state->error) break; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ { if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/ } if(!IEND) chunk = lodepng_chunk_next_const(chunk); } ucvector_init(&scanlines); /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation. The prediction is currently not correct for interlaced PNG images.*/ predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color) + *h; if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/ if(!state->error) { state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data, idat.size, &state->decoder.zlibsettings); } ucvector_cleanup(&idat); if(!state->error) { ucvector outv; ucvector_init(&outv); if(!ucvector_resizev(&outv, lodepng_get_raw_size(*w, *h, &state->info_png.color), 0)) state->error = 83; /*alloc fail*/ if(!state->error) state->error = postProcessScanlines(outv.data, scanlines.data, *w, *h, &state->info_png); *out = outv.data; } ucvector_cleanup(&scanlines); } unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize) { *out = 0; decodeGeneric(out, w, h, state, in, insize); if(state->error) return state->error; if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) { /*same color type, no copying or converting of data needed*/ /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype the raw image has to the end user*/ if(!state->decoder.color_convert) { state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color); if(state->error) return state->error; } } else { /*color conversion needed; sort of copy of the data*/ unsigned char* data = *out; size_t outsize; /*TODO: check if this works according to the statement in the documentation: "The converter can convert from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/ if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA) && !(state->info_raw.bitdepth == 8)) { return 56; /*unsupported color mode conversion*/ } outsize = lodepng_get_raw_size(*w, *h, &state->info_raw); *out = (unsigned char*)calloc(outsize, sizeof(unsigned char)); if(!(*out)) { state->error = 83; /*alloc fail*/ } else state->error = lodepng_convert(*out, data, &state->info_raw, &state->info_png.color, *w, *h); free(data); } return state->error; } unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize, LodePNGColorType colortype, unsigned bitdepth) { unsigned error; LodePNGState state; lodepng_state_init(&state); state.info_raw.colortype = colortype; state.info_raw.bitdepth = bitdepth; error = lodepng_decode(out, w, h, &state, in, insize); lodepng_state_cleanup(&state); return error; } unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) { return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8); } unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) { return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8); } #ifdef LODEPNG_COMPILE_DISK unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename, LodePNGColorType colortype, unsigned bitdepth) { unsigned char* buffer; size_t buffersize; unsigned error; error = lodepng_load_file(&buffer, &buffersize, filename); if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth); free(buffer); return error; } unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) { return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8); } unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) { return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8); } #endif /*LODEPNG_COMPILE_DISK*/ void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) { settings->color_convert = 1; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS settings->read_text_chunks = 1; settings->remember_unknown_chunks = 0; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ settings->ignore_crc = 0; lodepng_decompress_settings_init(&settings->zlibsettings); } #endif /*LODEPNG_COMPILE_DECODER*/ #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) void lodepng_state_init(LodePNGState* state) { #ifdef LODEPNG_COMPILE_DECODER lodepng_decoder_settings_init(&state->decoder); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER lodepng_encoder_settings_init(&state->encoder); #endif /*LODEPNG_COMPILE_ENCODER*/ lodepng_color_mode_init(&state->info_raw); lodepng_info_init(&state->info_png); state->error = 1; } void lodepng_state_cleanup(LodePNGState* state) { lodepng_color_mode_cleanup(&state->info_raw); lodepng_info_cleanup(&state->info_png); } void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) { lodepng_state_cleanup(dest); *dest = *source; lodepng_color_mode_init(&dest->info_raw); lodepng_info_init(&dest->info_png); dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return; dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return; } #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ #ifdef LODEPNG_COMPILE_ENCODER /* ////////////////////////////////////////////////////////////////////////// */ /* / PNG Encoder / */ /* ////////////////////////////////////////////////////////////////////////// */ /*chunkName must be string of 4 characters*/ static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length) { CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data)); out->allocsize = out->size; /*fix the allocsize again*/ return 0; } static unsigned writeSignature(ucvector* out) { /*8 bytes PNG signature, aka the magic bytes*/ if (!ucvector_push_back(out, 137)) return 83; if (!ucvector_push_back(out, 80)) return 83; if (!ucvector_push_back(out, 78)) return 83; if (!ucvector_push_back(out, 71)) return 83; if (!ucvector_push_back(out, 13)) return 83; if (!ucvector_push_back(out, 10)) return 83; if (!ucvector_push_back(out, 26)) return 83; if (!ucvector_push_back(out, 10)) return 83; return 0; } static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) { unsigned error = 0; ucvector header; ucvector_init(&header); if (!lodepng_add32bitInt(&header, w)) /*width*/ return 1; if (!lodepng_add32bitInt(&header, h)) /*height*/ return 1; ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/ ucvector_push_back(&header, (unsigned char)colortype); /*color type*/ ucvector_push_back(&header, 0); /*compression method*/ ucvector_push_back(&header, 0); /*filter method*/ ucvector_push_back(&header, interlace_method); /*interlace method*/ error = addChunk(out, "IHDR", header.data, header.size); ucvector_cleanup(&header); return error; } static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) { unsigned error = 0; size_t i; ucvector PLTE; ucvector_init(&PLTE); for(i = 0; i < info->palettesize * 4; i++) { /*add all channels except alpha channel*/ if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]); } error = addChunk(out, "PLTE", PLTE.data, PLTE.size); ucvector_cleanup(&PLTE); return error; } static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) { unsigned error = 0; size_t i; ucvector tRNS; ucvector_init(&tRNS); if(info->colortype == LCT_PALETTE) { size_t amount = info->palettesize; /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/ for(i = info->palettesize; i > 0; i--) { if(info->palette[4 * (i - 1) + 3] == 255) amount--; else break; } /*add only alpha channel*/ for(i = 0; i < amount; i++) ucvector_push_back(&tRNS, info->palette[4 * i + 3]); } else if(info->colortype == LCT_GREY) { if(info->key_defined) { ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256)); ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256)); } } else if(info->colortype == LCT_RGB) { if(info->key_defined) { ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256)); ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256)); ucvector_push_back(&tRNS, (unsigned char)(info->key_g / 256)); ucvector_push_back(&tRNS, (unsigned char)(info->key_g % 256)); ucvector_push_back(&tRNS, (unsigned char)(info->key_b / 256)); ucvector_push_back(&tRNS, (unsigned char)(info->key_b % 256)); } } error = addChunk(out, "tRNS", tRNS.data, tRNS.size); ucvector_cleanup(&tRNS); return error; } static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize, LodePNGCompressSettings* zlibsettings) { ucvector zlibdata; unsigned error = 0; /*compress with the Zlib compressor*/ ucvector_init(&zlibdata); error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings); if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size); ucvector_cleanup(&zlibdata); return error; } static unsigned addChunk_IEND(ucvector* out) { unsigned error = 0; error = addChunk(out, "IEND", 0, 0); return error; } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) { unsigned error = 0; size_t i; ucvector text; ucvector_init(&text); for(i = 0; keyword[i] != 0; i++) ucvector_push_back(&text, (unsigned char)keyword[i]); if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ ucvector_push_back(&text, 0); /*0 termination char*/ for(i = 0; textstring[i] != 0; i++) ucvector_push_back(&text, (unsigned char)textstring[i]); error = addChunk(out, "tEXt", text.data, text.size); ucvector_cleanup(&text); return error; } static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring, LodePNGCompressSettings* zlibsettings) { unsigned error = 0; ucvector data, compressed; size_t i, textsize = strlen(textstring); ucvector_init(&data); ucvector_init(&compressed); for(i = 0; keyword[i] != 0; i++) ucvector_push_back(&data, (unsigned char)keyword[i]); if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ ucvector_push_back(&data, 0); /*0 termination char*/ ucvector_push_back(&data, 0); /*compression method: 0*/ error = zlib_compress(&compressed.data, &compressed.size, (unsigned char*)textstring, textsize, zlibsettings); if(!error) { for(i = 0; i < compressed.size; i++) ucvector_push_back(&data, compressed.data[i]); error = addChunk(out, "zTXt", data.data, data.size); } ucvector_cleanup(&compressed); ucvector_cleanup(&data); return error; } static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag, const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) { unsigned error = 0; ucvector data; size_t i, textsize = strlen(textstring); ucvector_init(&data); for(i = 0; keyword[i] != 0; i++) ucvector_push_back(&data, (unsigned char)keyword[i]); if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ ucvector_push_back(&data, 0); /*null termination char*/ ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/ ucvector_push_back(&data, 0); /*compression method*/ for(i = 0; langtag[i] != 0; i++) ucvector_push_back(&data, (unsigned char)langtag[i]); ucvector_push_back(&data, 0); /*null termination char*/ for(i = 0; transkey[i] != 0; i++) ucvector_push_back(&data, (unsigned char)transkey[i]); ucvector_push_back(&data, 0); /*null termination char*/ if(compressed) { ucvector compressed_data; ucvector_init(&compressed_data); error = zlib_compress(&compressed_data.data, &compressed_data.size, (unsigned char*)textstring, textsize, zlibsettings); if(!error) { for(i = 0; i < compressed_data.size; i++) ucvector_push_back(&data, compressed_data.data[i]); } ucvector_cleanup(&compressed_data); } else /*not compressed*/ { for(i = 0; textstring[i] != 0; i++) ucvector_push_back(&data, (unsigned char)textstring[i]); } if(!error) error = addChunk(out, "iTXt", data.data, data.size); ucvector_cleanup(&data); return error; } static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) { unsigned error = 0; ucvector bKGD; ucvector_init(&bKGD); if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) { ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256)); ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) { ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256)); ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); ucvector_push_back(&bKGD, (unsigned char)(info->background_g / 256)); ucvector_push_back(&bKGD, (unsigned char)(info->background_g % 256)); ucvector_push_back(&bKGD, (unsigned char)(info->background_b / 256)); ucvector_push_back(&bKGD, (unsigned char)(info->background_b % 256)); } else if(info->color.colortype == LCT_PALETTE) { ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); /*palette index*/ } error = addChunk(out, "bKGD", bKGD.data, bKGD.size); ucvector_cleanup(&bKGD); return error; } static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) { unsigned error = 0; unsigned char* data = (unsigned char*)malloc(7); if(!data) return 83; /*alloc fail*/ data[0] = (unsigned char)(time->year / 256); data[1] = (unsigned char)(time->year % 256); data[2] = (unsigned char)time->month; data[3] = (unsigned char)time->day; data[4] = (unsigned char)time->hour; data[5] = (unsigned char)time->minute; data[6] = (unsigned char)time->second; error = addChunk(out, "tIME", data, 7); free(data); return error; } static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) { unsigned error = 0; ucvector data; ucvector_init(&data); if (!lodepng_add32bitInt(&data, info->phys_x)) return 1; if (!lodepng_add32bitInt(&data, info->phys_y)) return 1; if (!ucvector_push_back(&data, info->phys_unit)) return 1; error = addChunk(out, "pHYs", data.data, data.size); ucvector_cleanup(&data); return error; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline, size_t length, size_t bytewidth, unsigned char filterType) { size_t i; switch(filterType) { case 0: /*None*/ for(i = 0; i < length; i++) out[i] = scanline[i]; break; case 1: /*Sub*/ for(i = 0; i < bytewidth; i++) out[i] = scanline[i]; for(i = bytewidth; i < length; i++) out[i] = scanline[i] - scanline[i - bytewidth]; break; case 2: /*Up*/ if(prevline) { for(i = 0; i < length; i++) out[i] = scanline[i] - prevline[i]; } else { for(i = 0; i < length; i++) out[i] = scanline[i]; } break; case 3: /*Average*/ if(prevline) { for(i = 0; i < bytewidth; i++) out[i] = scanline[i] - prevline[i] / 2; for(i = bytewidth; i < length; i++) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) / 2); } else { for(i = 0; i < bytewidth; i++) out[i] = scanline[i]; for(i = bytewidth; i < length; i++) out[i] = scanline[i] - scanline[i - bytewidth] / 2; } break; case 4: /*Paeth*/ if(prevline) { /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/ for(i = 0; i < bytewidth; i++) out[i] = (scanline[i] - prevline[i]); for(i = bytewidth; i < length; i++) { out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth])); } } else { for(i = 0; i < bytewidth; i++) out[i] = scanline[i]; /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/ for(i = bytewidth; i < length; i++) out[i] = (scanline[i] - scanline[i - bytewidth]); } break; default: return; /*unexisting filter type given*/ } } /* log2 approximation. A slight bit faster than std::log. */ static float flog2(float f) { float result = 0; while(f > 32) { result += 4; f /= 16; } while(f > 2) { result++; f /= 2; } return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f); } static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, const LodePNGColorMode* info, const LodePNGEncoderSettings* settings) { /* For PNG filter method 0 out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are the scanlines with 1 extra byte per scanline */ unsigned bpp = lodepng_get_bpp(info); /*the width of a scanline in bytes, not including the filter type*/ size_t linebytes = (w * bpp + 7) / 8; /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ size_t bytewidth = (bpp + 7) / 8; const unsigned char* prevline = 0; unsigned x, y; unsigned error = 0; LodePNGFilterStrategy strategy = settings->filter_strategy; /* There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard: * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e. use fixed filtering, with the filter None). * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply all five filters and select the filter that produces the smallest sum of absolute values per row. This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true. If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed, but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum heuristic is used. */ if(settings->filter_palette_zero && (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO; if(bpp == 0) return 31; /*error: invalid color type*/ if(strategy == LFS_ZERO) { for(y = 0; y < h; y++) { size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ size_t inindex = linebytes * y; out[outindex] = 0; /*filter type byte*/ filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0); prevline = &in[inindex]; } } else if(strategy == LFS_MINSUM) { /*adaptive filtering*/ size_t sum[5]; ucvector attempt[5]; /*five filtering attempts, one for each filter type*/ size_t smallest = 0; unsigned char type, i, bestType = 0; for(type = 0; type < 5; type++) { ucvector_init(&attempt[type]); if(!ucvector_resize(&attempt[type], linebytes)) { for(i=0; i<type; i++) ucvector_cleanup(&attempt[i]); return 83; /*alloc fail*/ } } if(!error) { for(y = 0; y < h; y++) { /*try the 5 filter types*/ for(type = 0; type < 5; type++) { filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type); /*calculate the sum of the result*/ sum[type] = 0; if(type == 0) { for(x = 0; x < linebytes; x++) sum[type] += (unsigned char)(attempt[type].data[x]); } else { for(x = 0; x < linebytes; x++) { /*For differences, each byte should be treated as signed, values above 127 are negative (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there. This means filtertype 0 is almost never chosen, but that is justified.*/ unsigned char s = attempt[type].data[x]; sum[type] += s < 128 ? s : (255U - s); } } /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ if(type == 0 || sum[type] < smallest) { bestType = type; smallest = sum[type]; } } prevline = &in[y * linebytes]; /*now fill the out values*/ out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ for(x = 0; x < linebytes; x++) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x]; } } for(type = 0; type < 5; type++) ucvector_cleanup(&attempt[type]); } else if(strategy == LFS_ENTROPY) { float sum[5]; ucvector attempt[5]; /*five filtering attempts, one for each filter type*/ float smallest = 0; unsigned type, i, bestType = 0; unsigned count[256]; for(type = 0; type < 5; type++) { ucvector_init(&attempt[type]); if(!ucvector_resize(&attempt[type], linebytes)) { for(i=0; i<type; i++) ucvector_cleanup(&attempt[i]); return 83; /*alloc fail*/ } } for(y = 0; y < h; y++) { /*try the 5 filter types*/ for(type = 0; type < 5; type++) { filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type); for(x = 0; x < 256; x++) count[x] = 0; for(x = 0; x < linebytes; x++) count[attempt[type].data[x]]++; count[type]++; /*the filter type itself is part of the scanline*/ sum[type] = 0; for(x = 0; x < 256; x++) { float p = count[x] / (float)(linebytes + 1); sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p; } /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ if(type == 0 || sum[type] < smallest) { bestType = type; smallest = sum[type]; } } prevline = &in[y * linebytes]; /*now fill the out values*/ out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ for(x = 0; x < linebytes; x++) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x]; } for(type = 0; type < 5; type++) ucvector_cleanup(&attempt[type]); } else if(strategy == LFS_PREDEFINED) { for(y = 0; y < h; y++) { size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ size_t inindex = linebytes * y; unsigned char type = settings->predefined_filters[y]; out[outindex] = type; /*filter type byte*/ filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); prevline = &in[inindex]; } } else if(strategy == LFS_BRUTE_FORCE) { /*brute force filter chooser. deflate the scanline after every filter attempt to see which one deflates best. This is very slow and gives only slightly smaller, sometimes even larger, result*/ size_t size[5]; ucvector attempt[5]; /*five filtering attempts, one for each filter type*/ size_t smallest = 0; unsigned type = 0, bestType = 0; unsigned char* dummy; LodePNGCompressSettings zlibsettings = settings->zlibsettings; /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose, to simulate the true case where the tree is the same for the whole image. Sometimes it gives better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare cases better compression. It does make this a bit less slow, so it's worth doing this.*/ zlibsettings.btype = 1; /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG images only, so disable it*/ zlibsettings.custom_zlib = 0; zlibsettings.custom_deflate = 0; for(type = 0; type < 5; type++) { ucvector_init(&attempt[type]); ucvector_resize(&attempt[type], linebytes); /*todo: give error if resize failed*/ } for(y = 0; y < h; y++) /*try the 5 filter types*/ { for(type = 0; type < 5; type++) { unsigned testsize = attempt[type].size; /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/ filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type); size[type] = 0; dummy = 0; zlib_compress(&dummy, &size[type], attempt[type].data, testsize, &zlibsettings); free(dummy); /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/ if(type == 0 || size[type] < smallest) { bestType = type; smallest = size[type]; } } prevline = &in[y * linebytes]; out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ for(x = 0; x < linebytes; x++) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x]; } for(type = 0; type < 5; type++) ucvector_cleanup(&attempt[type]); } else return 88; /* unknown filter strategy */ return error; } static void addPaddingBits(unsigned char* out, const unsigned char* in, size_t olinebits, size_t ilinebits, unsigned h) { /*The opposite of the removePaddingBits function olinebits must be >= ilinebits*/ unsigned y; size_t diff = olinebits - ilinebits; size_t obp = 0, ibp = 0; /*bit pointers*/ for(y = 0; y < h; y++) { size_t x; for(x = 0; x < ilinebits; x++) { unsigned char bit = readBitFromReversedStream(&ibp, in); setBitOfReversedStream(&obp, out, bit); } /*obp += diff; --> no, fill in some value in the padding bits too, to avoid "Use of uninitialised value of size ###" warning from valgrind*/ for(x = 0; x < diff; x++) setBitOfReversedStream(&obp, out, 0); } } /* in: non-interlaced image with size w*h out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with no padding bits between scanlines, but between reduced images so that each reduced image starts at a byte. bpp: bits per pixel there are no padding bits, not between scanlines, not between reduced images in has the following size in bits: w * h * bpp. out is possibly bigger due to padding bits between reduced images NOTE: comments about padding bits are only relevant if bpp < 8 */ static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; unsigned i; Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); if(bpp >= 8) { for(i = 0; i < 7; i++) { unsigned x, y, b; size_t bytewidth = bpp / 8; for(y = 0; y < passh[i]; y++) for(x = 0; x < passw[i]; x++) { size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth; for(b = 0; b < bytewidth; b++) { out[pixeloutstart + b] = in[pixelinstart + b]; } } } } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ { for(i = 0; i < 7; i++) { unsigned x, y, b; unsigned ilinebits = bpp * passw[i]; unsigned olinebits = bpp * w; size_t obp, ibp; /*bit pointers (for out and in buffer)*/ for(y = 0; y < passh[i]; y++) for(x = 0; x < passw[i]; x++) { ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; obp = (8 * passstart[i]) + (y * ilinebits + x * bpp); for(b = 0; b < bpp; b++) { unsigned char bit = readBitFromReversedStream(&ibp, in); setBitOfReversedStream(&obp, out, bit); } } } } } /*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image. return value is error**/ static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in, unsigned w, unsigned h, const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) { /* This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps: *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter */ unsigned bpp = lodepng_get_bpp(&info_png->color); unsigned error = 0; if(info_png->interlace_method == 0) { *outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/ *out = (unsigned char*)calloc(*outsize, 1); if(!(*out) && (*outsize)) error = 83; /*alloc fail*/ if(!error) { /*non multiple of 8 bits per scanline, padding bits needed per scanline*/ if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) { unsigned char* padded = (unsigned char*)calloc(h * ((w * bpp + 7) / 8), 1); if(!padded) error = 83; /*alloc fail*/ if(!error) { addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h); error = filter(*out, padded, w, h, &info_png->color, settings); } free(padded); } else { /*we can immediatly filter into the out buffer, no other steps needed*/ error = filter(*out, in, w, h, &info_png->color, settings); } } } else /*interlace_method is 1 (Adam7)*/ { unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; unsigned char* adam7; Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/ *out = (unsigned char*)calloc(*outsize, 1); if(!(*out)) error = 83; /*alloc fail*/ adam7 = (unsigned char*)calloc(passstart[7], sizeof(unsigned char)); if(!adam7 && passstart[7]) error = 83; /*alloc fail*/ if(!error) { unsigned i; Adam7_interlace(adam7, in, w, h, bpp); for(i = 0; i < 7; i++) { if(bpp < 8) { unsigned char* padded = (unsigned char*)calloc(padded_passstart[i + 1] - padded_passstart[i], sizeof(unsigned char)); if(!padded) ERROR_BREAK(83); /*alloc fail*/ addPaddingBits(padded, &adam7[passstart[i]], ((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]); error = filter(&(*out)[filter_passstart[i]], padded, passw[i], passh[i], &info_png->color, settings); free(padded); } else { error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]], passw[i], passh[i], &info_png->color, settings); } if(error) break; } } free(adam7); } return error; } /* palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA... returns 0 if the palette is opaque, returns 1 if the palette has a single color with alpha 0 ==> color key returns 2 if the palette is semi-translucent. */ static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize) { size_t i; unsigned key = 0; unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/ for(i = 0; i < palettesize; i++) { if(!key && palette[4 * i + 3] == 0) { r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2]; key = 1; i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/ } else if(palette[4 * i + 3] != 255) return 2; /*when key, no opaque RGB may have key's RGB*/ else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2; } return key; } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) { unsigned char* inchunk = data; while((size_t)(inchunk - data) < datasize) { CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk)); out->allocsize = out->size; /*fix the allocsize again*/ inchunk = lodepng_chunk_next(inchunk); } return 0; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ unsigned lodepng_encode(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h, LodePNGState* state) { LodePNGInfo info; ucvector outv; unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/ size_t datasize = 0; /*provide some proper output values if error will happen*/ *out = 0; *outsize = 0; state->error = 0; lodepng_info_init(&info); lodepng_info_copy(&info, &state->info_png); if((info.color.colortype == LCT_PALETTE || state->encoder.force_palette) && (info.color.palettesize == 0 || info.color.palettesize > 256)) { state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/ goto fail; } if(state->encoder.auto_convert) { state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw); } if(state->error) goto fail; if(state->encoder.zlibsettings.btype > 2) { state->error = 61; /*error: unexisting btype*/ goto fail; } if(state->info_png.interlace_method > 1) { state->error = 71; /*error: unexisting interlace mode*/ goto fail; } state->error = checkColorValidity(info.color.colortype, info.color.bitdepth); if(state->error) goto fail; /*error: unexisting color type given*/ state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth); if(state->error) goto fail; /*error: unexisting color type given*/ if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) { unsigned char* converted; size_t size = (w * h * lodepng_get_bpp(&info.color) + 7) / 8; converted = (unsigned char*)calloc(size, 1); if(!converted && size) state->error = 83; /*alloc fail*/ if(!state->error) { state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h); } if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); free(converted); } else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); ucvector_init(&outv); while(!state->error) /*while only executed once, to break on error*/ { #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS size_t i; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*write signature and chunks*/ writeSignature(&outv); /*IHDR*/ addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*unknown chunks between IHDR and PLTE*/ if(info.unknown_chunks_data[0]) { state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]); if(state->error) break; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*PLTE*/ if(info.color.colortype == LCT_PALETTE) { addChunk_PLTE(&outv, &info.color); } if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) { addChunk_PLTE(&outv, &info.color); } /*tRNS*/ if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0) { addChunk_tRNS(&outv, &info.color); } if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined) { addChunk_tRNS(&outv, &info.color); } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*bKGD (must come between PLTE and the IDAt chunks*/ if(info.background_defined) addChunk_bKGD(&outv, &info); /*pHYs (must come before the IDAT chunks)*/ if(info.phys_defined) addChunk_pHYs(&outv, &info); /*unknown chunks between PLTE and IDAT*/ if(info.unknown_chunks_data[1]) { state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]); if(state->error) break; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*IDAT (multiple IDAT chunks must be consecutive)*/ state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings); if(state->error) break; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*tIME*/ if(info.time_defined) addChunk_tIME(&outv, &info.time); /*tEXt and/or zTXt*/ for(i = 0; i < info.text_num; i++) { if(strlen(info.text_keys[i]) > 79) { state->error = 66; /*text chunk too large*/ break; } if(strlen(info.text_keys[i]) < 1) { state->error = 67; /*text chunk too small*/ break; } if(state->encoder.text_compression) { addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings); } else { addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]); } } /*LodePNG version id in text chunk*/ if(state->encoder.add_id) { unsigned alread_added_id_text = 0; for(i = 0; i < info.text_num; i++) { if(!strcmp(info.text_keys[i], "LodePNG")) { alread_added_id_text = 1; break; } } if(alread_added_id_text == 0) { addChunk_tEXt(&outv, "LodePNG", VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/ } } /*iTXt*/ for(i = 0; i < info.itext_num; i++) { if(strlen(info.itext_keys[i]) > 79) { state->error = 66; /*text chunk too large*/ break; } if(strlen(info.itext_keys[i]) < 1) { state->error = 67; /*text chunk too small*/ break; } addChunk_iTXt(&outv, state->encoder.text_compression, info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i], &state->encoder.zlibsettings); } /*unknown chunks between IDAT and IEND*/ if(info.unknown_chunks_data[2]) { state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]); if(state->error) break; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ addChunk_IEND(&outv); break; /*this isn't really a while loop; no error happened so break out now!*/ } /*instead of cleaning the vector up, give it to the output*/ *out = outv.data; *outsize = outv.size; fail: lodepng_info_cleanup(&info); free(data); return state->error; } unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { unsigned error; LodePNGState state; lodepng_state_init(&state); state.info_raw.colortype = colortype; state.info_raw.bitdepth = bitdepth; state.info_png.color.colortype = colortype; state.info_png.color.bitdepth = bitdepth; lodepng_encode(out, outsize, image, w, h, &state); error = state.error; lodepng_state_cleanup(&state); return error; } unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) { return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8); } unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) { return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8); } #ifdef LODEPNG_COMPILE_DISK unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { unsigned char* buffer = NULL; size_t buffersize = 0; unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth); if(!error) error = lodepng_save_file(buffer, buffersize, filename); free(buffer); return error; } unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) { return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8); } unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) { return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8); } #endif /*LODEPNG_COMPILE_DISK*/ void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) { lodepng_compress_settings_init(&settings->zlibsettings); settings->filter_palette_zero = 1; settings->filter_strategy = LFS_MINSUM; settings->auto_convert = 1; settings->force_palette = 0; settings->predefined_filters = 0; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS settings->add_id = 0; settings->text_compression = 1; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } #endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_PNG*/ #ifdef LODEPNG_COMPILE_ERROR_TEXT /* This returns the description of a numerical error code in English. This is also the documentation of all the error codes. */ const char* lodepng_error_text(unsigned code) { switch(code) { case 0: return "no error, everything went ok"; case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/ case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/ case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/ case 13: return "problem while processing dynamic deflate block"; case 14: return "problem while processing dynamic deflate block"; case 15: return "problem while processing dynamic deflate block"; case 16: return "unexisting code while processing dynamic deflate block"; case 17: return "end of out buffer memory reached while inflating"; case 18: return "invalid distance code while inflating"; case 19: return "end of out buffer memory reached while inflating"; case 20: return "invalid deflate block BTYPE encountered while decoding"; case 21: return "NLEN is not ones complement of LEN in a deflate block"; /*end of out buffer memory reached while inflating: This can happen if the inflated deflate data is longer than the amount of bytes required to fill up all the pixels of the image, given the color depth and image dimensions. Something that doesn't happen in a normal, well encoded, PNG image.*/ case 22: return "end of out buffer memory reached while inflating"; case 23: return "end of in buffer memory reached while inflating"; case 24: return "invalid FCHECK in zlib header"; case 25: return "invalid compression method in zlib header"; case 26: return "FDICT encountered in zlib header while it's not used for PNG"; case 27: return "PNG file is smaller than a PNG header"; /*Checks the magic file header, the first 8 bytes of the PNG file*/ case 28: return "incorrect PNG signature, it's no PNG or corrupted"; case 29: return "first chunk is not the header chunk"; case 30: return "chunk length too large, chunk broken off at end of file"; case 31: return "illegal PNG color type or bpp"; case 32: return "illegal PNG compression method"; case 33: return "illegal PNG filter method"; case 34: return "illegal PNG interlace method"; case 35: return "chunk length of a chunk is too large or the chunk too small"; case 36: return "illegal PNG filter type encountered"; case 37: return "illegal bit depth for this color type given"; case 38: return "the palette is too big"; /*more than 256 colors*/ case 39: return "more palette alpha values given in tRNS chunk than there are colors in the palette"; case 40: return "tRNS chunk has wrong size for greyscale image"; case 41: return "tRNS chunk has wrong size for RGB image"; case 42: return "tRNS chunk appeared while it was not allowed for this color type"; case 43: return "bKGD chunk has wrong size for palette image"; case 44: return "bKGD chunk has wrong size for greyscale image"; case 45: return "bKGD chunk has wrong size for RGB image"; /*the input data is empty, maybe a PNG file doesn't exist or is in the wrong path*/ case 48: return "empty input or file doesn't exist"; case 49: return "jumped past memory while generating dynamic huffman tree"; case 50: return "jumped past memory while generating dynamic huffman tree"; case 51: return "jumped past memory while inflating huffman block"; case 52: return "jumped past memory while inflating"; case 53: return "size of zlib data too small"; case 54: return "repeat symbol in tree while there was no value symbol yet"; /*jumped past tree while generating huffman tree, this could be when the tree will have more leaves than symbols after generating it out of the given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/ case 55: return "jumped past tree while generating huffman tree"; case 56: return "given output image colortype or bitdepth not supported for color conversion"; case 57: return "invalid CRC encountered (checking CRC can be disabled)"; case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)"; case 59: return "requested color conversion not supported"; case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)"; case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)"; /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/ case 62: return "conversion from color to greyscale not supported"; case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/ /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/ case 64: return "the length of the END symbol 256 in the Huffman tree is 0"; case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes"; case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte"; case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors"; case 69: return "unknown chunk type with 'critical' flag encountered by the decoder"; case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)"; case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)"; case 73: return "invalid tIME chunk size"; case 74: return "invalid pHYs chunk size"; /*length could be wrong, or data chopped off*/ case 75: return "no null termination char found while decoding text chunk"; case 76: return "iTXt chunk too short to contain required bytes"; case 77: return "integer overflow in buffer size"; case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/ case 79: return "failed to open file for writing"; case 80: return "tried creating a tree of 0 symbols"; case 81: return "lazy matching at pos 0 is impossible"; case 82: return "color conversion to palette requested while a color isn't in palette"; case 83: return "memory allocation failed"; case 84: return "given image too small to contain all pixels to be encoded"; case 86: return "impossible offset in lz77 encoding (internal bug)"; case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined"; case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy"; case 89: return "text chunk keyword too short or long: must have size 1-79"; /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/ case 90: return "windowsize must be a power of two"; case 91: return "fwrite failed"; } return "unknown error code"; } #endif /*LODEPNG_COMPILE_ERROR_TEXT*/
./CrossVul/dataset_final_sorted/CWE-772/c/good_1168_2
crossvul-cpp_data_good_1161_0
/* * IPv6 over IPv4 tunnel device - Simple Internet Transition (SIT) * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Changes: * Roger Venning <r.venning@telstra.com>: 6to4 support * Nate Thompson <nate@thebog.net>: 6to4 support * Fred Templin <fred.l.templin@boeing.com>: isatap support */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/capability.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/in6.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/icmp.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/init.h> #include <linux/netfilter_ipv4.h> #include <linux/if_ether.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/protocol.h> #include <net/transp_v6.h> #include <net/ip6_fib.h> #include <net/ip6_route.h> #include <net/ndisc.h> #include <net/addrconf.h> #include <net/ip.h> #include <net/udp.h> #include <net/icmp.h> #include <net/ip_tunnels.h> #include <net/inet_ecn.h> #include <net/xfrm.h> #include <net/dsfield.h> #include <net/net_namespace.h> #include <net/netns/generic.h> /* This version of net/ipv6/sit.c is cloned of net/ipv4/ip_gre.c For comments look at net/ipv4/ip_gre.c --ANK */ #define IP6_SIT_HASH_SIZE 16 #define HASH(addr) (((__force u32)addr^((__force u32)addr>>4))&0xF) static bool log_ecn_error = true; module_param(log_ecn_error, bool, 0644); MODULE_PARM_DESC(log_ecn_error, "Log packets received with corrupted ECN"); static int ipip6_tunnel_init(struct net_device *dev); static void ipip6_tunnel_setup(struct net_device *dev); static void ipip6_dev_free(struct net_device *dev); static bool check_6rd(struct ip_tunnel *tunnel, const struct in6_addr *v6dst, __be32 *v4dst); static struct rtnl_link_ops sit_link_ops __read_mostly; static unsigned int sit_net_id __read_mostly; struct sit_net { struct ip_tunnel __rcu *tunnels_r_l[IP6_SIT_HASH_SIZE]; struct ip_tunnel __rcu *tunnels_r[IP6_SIT_HASH_SIZE]; struct ip_tunnel __rcu *tunnels_l[IP6_SIT_HASH_SIZE]; struct ip_tunnel __rcu *tunnels_wc[1]; struct ip_tunnel __rcu **tunnels[4]; struct net_device *fb_tunnel_dev; }; /* * Must be invoked with rcu_read_lock */ static struct ip_tunnel *ipip6_tunnel_lookup(struct net *net, struct net_device *dev, __be32 remote, __be32 local, int sifindex) { unsigned int h0 = HASH(remote); unsigned int h1 = HASH(local); struct ip_tunnel *t; struct sit_net *sitn = net_generic(net, sit_net_id); int ifindex = dev ? dev->ifindex : 0; for_each_ip_tunnel_rcu(t, sitn->tunnels_r_l[h0 ^ h1]) { if (local == t->parms.iph.saddr && remote == t->parms.iph.daddr && (!dev || !t->parms.link || ifindex == t->parms.link || sifindex == t->parms.link) && (t->dev->flags & IFF_UP)) return t; } for_each_ip_tunnel_rcu(t, sitn->tunnels_r[h0]) { if (remote == t->parms.iph.daddr && (!dev || !t->parms.link || ifindex == t->parms.link || sifindex == t->parms.link) && (t->dev->flags & IFF_UP)) return t; } for_each_ip_tunnel_rcu(t, sitn->tunnels_l[h1]) { if (local == t->parms.iph.saddr && (!dev || !t->parms.link || ifindex == t->parms.link || sifindex == t->parms.link) && (t->dev->flags & IFF_UP)) return t; } t = rcu_dereference(sitn->tunnels_wc[0]); if (t && (t->dev->flags & IFF_UP)) return t; return NULL; } static struct ip_tunnel __rcu **__ipip6_bucket(struct sit_net *sitn, struct ip_tunnel_parm *parms) { __be32 remote = parms->iph.daddr; __be32 local = parms->iph.saddr; unsigned int h = 0; int prio = 0; if (remote) { prio |= 2; h ^= HASH(remote); } if (local) { prio |= 1; h ^= HASH(local); } return &sitn->tunnels[prio][h]; } static inline struct ip_tunnel __rcu **ipip6_bucket(struct sit_net *sitn, struct ip_tunnel *t) { return __ipip6_bucket(sitn, &t->parms); } static void ipip6_tunnel_unlink(struct sit_net *sitn, struct ip_tunnel *t) { struct ip_tunnel __rcu **tp; struct ip_tunnel *iter; for (tp = ipip6_bucket(sitn, t); (iter = rtnl_dereference(*tp)) != NULL; tp = &iter->next) { if (t == iter) { rcu_assign_pointer(*tp, t->next); break; } } } static void ipip6_tunnel_link(struct sit_net *sitn, struct ip_tunnel *t) { struct ip_tunnel __rcu **tp = ipip6_bucket(sitn, t); rcu_assign_pointer(t->next, rtnl_dereference(*tp)); rcu_assign_pointer(*tp, t); } static void ipip6_tunnel_clone_6rd(struct net_device *dev, struct sit_net *sitn) { #ifdef CONFIG_IPV6_SIT_6RD struct ip_tunnel *t = netdev_priv(dev); if (dev == sitn->fb_tunnel_dev || !sitn->fb_tunnel_dev) { ipv6_addr_set(&t->ip6rd.prefix, htonl(0x20020000), 0, 0, 0); t->ip6rd.relay_prefix = 0; t->ip6rd.prefixlen = 16; t->ip6rd.relay_prefixlen = 0; } else { struct ip_tunnel *t0 = netdev_priv(sitn->fb_tunnel_dev); memcpy(&t->ip6rd, &t0->ip6rd, sizeof(t->ip6rd)); } #endif } static int ipip6_tunnel_create(struct net_device *dev) { struct ip_tunnel *t = netdev_priv(dev); struct net *net = dev_net(dev); struct sit_net *sitn = net_generic(net, sit_net_id); int err; memcpy(dev->dev_addr, &t->parms.iph.saddr, 4); memcpy(dev->broadcast, &t->parms.iph.daddr, 4); if ((__force u16)t->parms.i_flags & SIT_ISATAP) dev->priv_flags |= IFF_ISATAP; dev->rtnl_link_ops = &sit_link_ops; err = register_netdevice(dev); if (err < 0) goto out; ipip6_tunnel_clone_6rd(dev, sitn); dev_hold(dev); ipip6_tunnel_link(sitn, t); return 0; out: return err; } static struct ip_tunnel *ipip6_tunnel_locate(struct net *net, struct ip_tunnel_parm *parms, int create) { __be32 remote = parms->iph.daddr; __be32 local = parms->iph.saddr; struct ip_tunnel *t, *nt; struct ip_tunnel __rcu **tp; struct net_device *dev; char name[IFNAMSIZ]; struct sit_net *sitn = net_generic(net, sit_net_id); for (tp = __ipip6_bucket(sitn, parms); (t = rtnl_dereference(*tp)) != NULL; tp = &t->next) { if (local == t->parms.iph.saddr && remote == t->parms.iph.daddr && parms->link == t->parms.link) { if (create) return NULL; else return t; } } if (!create) goto failed; if (parms->name[0]) { if (!dev_valid_name(parms->name)) goto failed; strlcpy(name, parms->name, IFNAMSIZ); } else { strcpy(name, "sit%d"); } dev = alloc_netdev(sizeof(*t), name, NET_NAME_UNKNOWN, ipip6_tunnel_setup); if (!dev) return NULL; dev_net_set(dev, net); nt = netdev_priv(dev); nt->parms = *parms; if (ipip6_tunnel_create(dev) < 0) goto failed_free; return nt; failed_free: free_netdev(dev); failed: return NULL; } #define for_each_prl_rcu(start) \ for (prl = rcu_dereference(start); \ prl; \ prl = rcu_dereference(prl->next)) static struct ip_tunnel_prl_entry * __ipip6_tunnel_locate_prl(struct ip_tunnel *t, __be32 addr) { struct ip_tunnel_prl_entry *prl; for_each_prl_rcu(t->prl) if (prl->addr == addr) break; return prl; } static int ipip6_tunnel_get_prl(struct ip_tunnel *t, struct ip_tunnel_prl __user *a) { struct ip_tunnel_prl kprl, *kp; struct ip_tunnel_prl_entry *prl; unsigned int cmax, c = 0, ca, len; int ret = 0; if (copy_from_user(&kprl, a, sizeof(kprl))) return -EFAULT; cmax = kprl.datalen / sizeof(kprl); if (cmax > 1 && kprl.addr != htonl(INADDR_ANY)) cmax = 1; /* For simple GET or for root users, * we try harder to allocate. */ kp = (cmax <= 1 || capable(CAP_NET_ADMIN)) ? kcalloc(cmax, sizeof(*kp), GFP_KERNEL | __GFP_NOWARN) : NULL; rcu_read_lock(); ca = t->prl_count < cmax ? t->prl_count : cmax; if (!kp) { /* We don't try hard to allocate much memory for * non-root users. * For root users, retry allocating enough memory for * the answer. */ kp = kcalloc(ca, sizeof(*kp), GFP_ATOMIC); if (!kp) { ret = -ENOMEM; goto out; } } c = 0; for_each_prl_rcu(t->prl) { if (c >= cmax) break; if (kprl.addr != htonl(INADDR_ANY) && prl->addr != kprl.addr) continue; kp[c].addr = prl->addr; kp[c].flags = prl->flags; c++; if (kprl.addr != htonl(INADDR_ANY)) break; } out: rcu_read_unlock(); len = sizeof(*kp) * c; ret = 0; if ((len && copy_to_user(a + 1, kp, len)) || put_user(len, &a->datalen)) ret = -EFAULT; kfree(kp); return ret; } static int ipip6_tunnel_add_prl(struct ip_tunnel *t, struct ip_tunnel_prl *a, int chg) { struct ip_tunnel_prl_entry *p; int err = 0; if (a->addr == htonl(INADDR_ANY)) return -EINVAL; ASSERT_RTNL(); for (p = rtnl_dereference(t->prl); p; p = rtnl_dereference(p->next)) { if (p->addr == a->addr) { if (chg) { p->flags = a->flags; goto out; } err = -EEXIST; goto out; } } if (chg) { err = -ENXIO; goto out; } p = kzalloc(sizeof(struct ip_tunnel_prl_entry), GFP_KERNEL); if (!p) { err = -ENOBUFS; goto out; } p->next = t->prl; p->addr = a->addr; p->flags = a->flags; t->prl_count++; rcu_assign_pointer(t->prl, p); out: return err; } static void prl_list_destroy_rcu(struct rcu_head *head) { struct ip_tunnel_prl_entry *p, *n; p = container_of(head, struct ip_tunnel_prl_entry, rcu_head); do { n = rcu_dereference_protected(p->next, 1); kfree(p); p = n; } while (p); } static int ipip6_tunnel_del_prl(struct ip_tunnel *t, struct ip_tunnel_prl *a) { struct ip_tunnel_prl_entry *x; struct ip_tunnel_prl_entry __rcu **p; int err = 0; ASSERT_RTNL(); if (a && a->addr != htonl(INADDR_ANY)) { for (p = &t->prl; (x = rtnl_dereference(*p)) != NULL; p = &x->next) { if (x->addr == a->addr) { *p = x->next; kfree_rcu(x, rcu_head); t->prl_count--; goto out; } } err = -ENXIO; } else { x = rtnl_dereference(t->prl); if (x) { t->prl_count = 0; call_rcu(&x->rcu_head, prl_list_destroy_rcu); t->prl = NULL; } } out: return err; } static int isatap_chksrc(struct sk_buff *skb, const struct iphdr *iph, struct ip_tunnel *t) { struct ip_tunnel_prl_entry *p; int ok = 1; rcu_read_lock(); p = __ipip6_tunnel_locate_prl(t, iph->saddr); if (p) { if (p->flags & PRL_DEFAULT) skb->ndisc_nodetype = NDISC_NODETYPE_DEFAULT; else skb->ndisc_nodetype = NDISC_NODETYPE_NODEFAULT; } else { const struct in6_addr *addr6 = &ipv6_hdr(skb)->saddr; if (ipv6_addr_is_isatap(addr6) && (addr6->s6_addr32[3] == iph->saddr) && ipv6_chk_prefix(addr6, t->dev)) skb->ndisc_nodetype = NDISC_NODETYPE_HOST; else ok = 0; } rcu_read_unlock(); return ok; } static void ipip6_tunnel_uninit(struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); struct sit_net *sitn = net_generic(tunnel->net, sit_net_id); if (dev == sitn->fb_tunnel_dev) { RCU_INIT_POINTER(sitn->tunnels_wc[0], NULL); } else { ipip6_tunnel_unlink(sitn, tunnel); ipip6_tunnel_del_prl(tunnel, NULL); } dst_cache_reset(&tunnel->dst_cache); dev_put(dev); } static int ipip6_err(struct sk_buff *skb, u32 info) { const struct iphdr *iph = (const struct iphdr *)skb->data; const int type = icmp_hdr(skb)->type; const int code = icmp_hdr(skb)->code; unsigned int data_len = 0; struct ip_tunnel *t; int sifindex; int err; switch (type) { default: case ICMP_PARAMETERPROB: return 0; case ICMP_DEST_UNREACH: switch (code) { case ICMP_SR_FAILED: /* Impossible event. */ return 0; default: /* All others are translated to HOST_UNREACH. rfc2003 contains "deep thoughts" about NET_UNREACH, I believe they are just ether pollution. --ANK */ break; } break; case ICMP_TIME_EXCEEDED: if (code != ICMP_EXC_TTL) return 0; data_len = icmp_hdr(skb)->un.reserved[1] * 4; /* RFC 4884 4.1 */ break; case ICMP_REDIRECT: break; } err = -ENOENT; sifindex = netif_is_l3_master(skb->dev) ? IPCB(skb)->iif : 0; t = ipip6_tunnel_lookup(dev_net(skb->dev), skb->dev, iph->daddr, iph->saddr, sifindex); if (!t) goto out; if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED) { ipv4_update_pmtu(skb, dev_net(skb->dev), info, t->parms.link, iph->protocol); err = 0; goto out; } if (type == ICMP_REDIRECT) { ipv4_redirect(skb, dev_net(skb->dev), t->parms.link, iph->protocol); err = 0; goto out; } err = 0; if (__in6_dev_get(skb->dev) && !ip6_err_gen_icmpv6_unreach(skb, iph->ihl * 4, type, data_len)) goto out; if (t->parms.iph.daddr == 0) goto out; if (t->parms.iph.ttl == 0 && type == ICMP_TIME_EXCEEDED) goto out; if (time_before(jiffies, t->err_time + IPTUNNEL_ERR_TIMEO)) t->err_count++; else t->err_count = 1; t->err_time = jiffies; out: return err; } static inline bool is_spoofed_6rd(struct ip_tunnel *tunnel, const __be32 v4addr, const struct in6_addr *v6addr) { __be32 v4embed = 0; if (check_6rd(tunnel, v6addr, &v4embed) && v4addr != v4embed) return true; return false; } /* Checks if an address matches an address on the tunnel interface. * Used to detect the NAT of proto 41 packets and let them pass spoofing test. * Long story: * This function is called after we considered the packet as spoofed * in is_spoofed_6rd. * We may have a router that is doing NAT for proto 41 packets * for an internal station. Destination a.a.a.a/PREFIX:bbbb:bbbb * will be translated to n.n.n.n/PREFIX:bbbb:bbbb. And is_spoofed_6rd * function will return true, dropping the packet. * But, we can still check if is spoofed against the IP * addresses associated with the interface. */ static bool only_dnatted(const struct ip_tunnel *tunnel, const struct in6_addr *v6dst) { int prefix_len; #ifdef CONFIG_IPV6_SIT_6RD prefix_len = tunnel->ip6rd.prefixlen + 32 - tunnel->ip6rd.relay_prefixlen; #else prefix_len = 48; #endif return ipv6_chk_custom_prefix(v6dst, prefix_len, tunnel->dev); } /* Returns true if a packet is spoofed */ static bool packet_is_spoofed(struct sk_buff *skb, const struct iphdr *iph, struct ip_tunnel *tunnel) { const struct ipv6hdr *ipv6h; if (tunnel->dev->priv_flags & IFF_ISATAP) { if (!isatap_chksrc(skb, iph, tunnel)) return true; return false; } if (tunnel->dev->flags & IFF_POINTOPOINT) return false; ipv6h = ipv6_hdr(skb); if (unlikely(is_spoofed_6rd(tunnel, iph->saddr, &ipv6h->saddr))) { net_warn_ratelimited("Src spoofed %pI4/%pI6c -> %pI4/%pI6c\n", &iph->saddr, &ipv6h->saddr, &iph->daddr, &ipv6h->daddr); return true; } if (likely(!is_spoofed_6rd(tunnel, iph->daddr, &ipv6h->daddr))) return false; if (only_dnatted(tunnel, &ipv6h->daddr)) return false; net_warn_ratelimited("Dst spoofed %pI4/%pI6c -> %pI4/%pI6c\n", &iph->saddr, &ipv6h->saddr, &iph->daddr, &ipv6h->daddr); return true; } static int ipip6_rcv(struct sk_buff *skb) { const struct iphdr *iph = ip_hdr(skb); struct ip_tunnel *tunnel; int sifindex; int err; sifindex = netif_is_l3_master(skb->dev) ? IPCB(skb)->iif : 0; tunnel = ipip6_tunnel_lookup(dev_net(skb->dev), skb->dev, iph->saddr, iph->daddr, sifindex); if (tunnel) { struct pcpu_sw_netstats *tstats; if (tunnel->parms.iph.protocol != IPPROTO_IPV6 && tunnel->parms.iph.protocol != 0) goto out; skb->mac_header = skb->network_header; skb_reset_network_header(skb); IPCB(skb)->flags = 0; skb->dev = tunnel->dev; if (packet_is_spoofed(skb, iph, tunnel)) { tunnel->dev->stats.rx_errors++; goto out; } if (iptunnel_pull_header(skb, 0, htons(ETH_P_IPV6), !net_eq(tunnel->net, dev_net(tunnel->dev)))) goto out; err = IP_ECN_decapsulate(iph, skb); if (unlikely(err)) { if (log_ecn_error) net_info_ratelimited("non-ECT from %pI4 with TOS=%#x\n", &iph->saddr, iph->tos); if (err > 1) { ++tunnel->dev->stats.rx_frame_errors; ++tunnel->dev->stats.rx_errors; goto out; } } tstats = this_cpu_ptr(tunnel->dev->tstats); u64_stats_update_begin(&tstats->syncp); tstats->rx_packets++; tstats->rx_bytes += skb->len; u64_stats_update_end(&tstats->syncp); netif_rx(skb); return 0; } /* no tunnel matched, let upstream know, ipsec may handle it */ return 1; out: kfree_skb(skb); return 0; } static const struct tnl_ptk_info ipip_tpi = { /* no tunnel info required for ipip. */ .proto = htons(ETH_P_IP), }; #if IS_ENABLED(CONFIG_MPLS) static const struct tnl_ptk_info mplsip_tpi = { /* no tunnel info required for mplsip. */ .proto = htons(ETH_P_MPLS_UC), }; #endif static int sit_tunnel_rcv(struct sk_buff *skb, u8 ipproto) { const struct iphdr *iph; struct ip_tunnel *tunnel; int sifindex; sifindex = netif_is_l3_master(skb->dev) ? IPCB(skb)->iif : 0; iph = ip_hdr(skb); tunnel = ipip6_tunnel_lookup(dev_net(skb->dev), skb->dev, iph->saddr, iph->daddr, sifindex); if (tunnel) { const struct tnl_ptk_info *tpi; if (tunnel->parms.iph.protocol != ipproto && tunnel->parms.iph.protocol != 0) goto drop; if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) goto drop; #if IS_ENABLED(CONFIG_MPLS) if (ipproto == IPPROTO_MPLS) tpi = &mplsip_tpi; else #endif tpi = &ipip_tpi; if (iptunnel_pull_header(skb, 0, tpi->proto, false)) goto drop; return ip_tunnel_rcv(tunnel, skb, tpi, NULL, log_ecn_error); } return 1; drop: kfree_skb(skb); return 0; } static int ipip_rcv(struct sk_buff *skb) { return sit_tunnel_rcv(skb, IPPROTO_IPIP); } #if IS_ENABLED(CONFIG_MPLS) static int mplsip_rcv(struct sk_buff *skb) { return sit_tunnel_rcv(skb, IPPROTO_MPLS); } #endif /* * If the IPv6 address comes from 6rd / 6to4 (RFC 3056) addr space this function * stores the embedded IPv4 address in v4dst and returns true. */ static bool check_6rd(struct ip_tunnel *tunnel, const struct in6_addr *v6dst, __be32 *v4dst) { #ifdef CONFIG_IPV6_SIT_6RD if (ipv6_prefix_equal(v6dst, &tunnel->ip6rd.prefix, tunnel->ip6rd.prefixlen)) { unsigned int pbw0, pbi0; int pbi1; u32 d; pbw0 = tunnel->ip6rd.prefixlen >> 5; pbi0 = tunnel->ip6rd.prefixlen & 0x1f; d = (ntohl(v6dst->s6_addr32[pbw0]) << pbi0) >> tunnel->ip6rd.relay_prefixlen; pbi1 = pbi0 - tunnel->ip6rd.relay_prefixlen; if (pbi1 > 0) d |= ntohl(v6dst->s6_addr32[pbw0 + 1]) >> (32 - pbi1); *v4dst = tunnel->ip6rd.relay_prefix | htonl(d); return true; } #else if (v6dst->s6_addr16[0] == htons(0x2002)) { /* 6to4 v6 addr has 16 bits prefix, 32 v4addr, 16 SLA, ... */ memcpy(v4dst, &v6dst->s6_addr16[1], 4); return true; } #endif return false; } static inline __be32 try_6rd(struct ip_tunnel *tunnel, const struct in6_addr *v6dst) { __be32 dst = 0; check_6rd(tunnel, v6dst, &dst); return dst; } /* * This function assumes it is being called from dev_queue_xmit() * and that skb is filled properly by that function. */ static netdev_tx_t ipip6_tunnel_xmit(struct sk_buff *skb, struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); const struct iphdr *tiph = &tunnel->parms.iph; const struct ipv6hdr *iph6 = ipv6_hdr(skb); u8 tos = tunnel->parms.iph.tos; __be16 df = tiph->frag_off; struct rtable *rt; /* Route to the other host */ struct net_device *tdev; /* Device to other host */ unsigned int max_headroom; /* The extra header space needed */ __be32 dst = tiph->daddr; struct flowi4 fl4; int mtu; const struct in6_addr *addr6; int addr_type; u8 ttl; u8 protocol = IPPROTO_IPV6; int t_hlen = tunnel->hlen + sizeof(struct iphdr); if (tos == 1) tos = ipv6_get_dsfield(iph6); /* ISATAP (RFC4214) - must come before 6to4 */ if (dev->priv_flags & IFF_ISATAP) { struct neighbour *neigh = NULL; bool do_tx_error = false; if (skb_dst(skb)) neigh = dst_neigh_lookup(skb_dst(skb), &iph6->daddr); if (!neigh) { net_dbg_ratelimited("nexthop == NULL\n"); goto tx_error; } addr6 = (const struct in6_addr *)&neigh->primary_key; addr_type = ipv6_addr_type(addr6); if ((addr_type & IPV6_ADDR_UNICAST) && ipv6_addr_is_isatap(addr6)) dst = addr6->s6_addr32[3]; else do_tx_error = true; neigh_release(neigh); if (do_tx_error) goto tx_error; } if (!dst) dst = try_6rd(tunnel, &iph6->daddr); if (!dst) { struct neighbour *neigh = NULL; bool do_tx_error = false; if (skb_dst(skb)) neigh = dst_neigh_lookup(skb_dst(skb), &iph6->daddr); if (!neigh) { net_dbg_ratelimited("nexthop == NULL\n"); goto tx_error; } addr6 = (const struct in6_addr *)&neigh->primary_key; addr_type = ipv6_addr_type(addr6); if (addr_type == IPV6_ADDR_ANY) { addr6 = &ipv6_hdr(skb)->daddr; addr_type = ipv6_addr_type(addr6); } if ((addr_type & IPV6_ADDR_COMPATv4) != 0) dst = addr6->s6_addr32[3]; else do_tx_error = true; neigh_release(neigh); if (do_tx_error) goto tx_error; } flowi4_init_output(&fl4, tunnel->parms.link, tunnel->fwmark, RT_TOS(tos), RT_SCOPE_UNIVERSE, IPPROTO_IPV6, 0, dst, tiph->saddr, 0, 0, sock_net_uid(tunnel->net, NULL)); rt = ip_route_output_flow(tunnel->net, &fl4, NULL); if (IS_ERR(rt)) { dev->stats.tx_carrier_errors++; goto tx_error_icmp; } if (rt->rt_type != RTN_UNICAST) { ip_rt_put(rt); dev->stats.tx_carrier_errors++; goto tx_error_icmp; } tdev = rt->dst.dev; if (tdev == dev) { ip_rt_put(rt); dev->stats.collisions++; goto tx_error; } if (iptunnel_handle_offloads(skb, SKB_GSO_IPXIP4)) { ip_rt_put(rt); goto tx_error; } if (df) { mtu = dst_mtu(&rt->dst) - t_hlen; if (mtu < 68) { dev->stats.collisions++; ip_rt_put(rt); goto tx_error; } if (mtu < IPV6_MIN_MTU) { mtu = IPV6_MIN_MTU; df = 0; } if (tunnel->parms.iph.daddr) skb_dst_update_pmtu(skb, mtu); if (skb->len > mtu && !skb_is_gso(skb)) { icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); ip_rt_put(rt); goto tx_error; } } if (tunnel->err_count > 0) { if (time_before(jiffies, tunnel->err_time + IPTUNNEL_ERR_TIMEO)) { tunnel->err_count--; dst_link_failure(skb); } else tunnel->err_count = 0; } /* * Okay, now see if we can stuff it in the buffer as-is. */ max_headroom = LL_RESERVED_SPACE(tdev) + t_hlen; if (skb_headroom(skb) < max_headroom || skb_shared(skb) || (skb_cloned(skb) && !skb_clone_writable(skb, 0))) { struct sk_buff *new_skb = skb_realloc_headroom(skb, max_headroom); if (!new_skb) { ip_rt_put(rt); dev->stats.tx_dropped++; kfree_skb(skb); return NETDEV_TX_OK; } if (skb->sk) skb_set_owner_w(new_skb, skb->sk); dev_kfree_skb(skb); skb = new_skb; iph6 = ipv6_hdr(skb); } ttl = tiph->ttl; if (ttl == 0) ttl = iph6->hop_limit; tos = INET_ECN_encapsulate(tos, ipv6_get_dsfield(iph6)); if (ip_tunnel_encap(skb, tunnel, &protocol, &fl4) < 0) { ip_rt_put(rt); goto tx_error; } skb_set_inner_ipproto(skb, IPPROTO_IPV6); iptunnel_xmit(NULL, rt, skb, fl4.saddr, fl4.daddr, protocol, tos, ttl, df, !net_eq(tunnel->net, dev_net(dev))); return NETDEV_TX_OK; tx_error_icmp: dst_link_failure(skb); tx_error: kfree_skb(skb); dev->stats.tx_errors++; return NETDEV_TX_OK; } static netdev_tx_t sit_tunnel_xmit__(struct sk_buff *skb, struct net_device *dev, u8 ipproto) { struct ip_tunnel *tunnel = netdev_priv(dev); const struct iphdr *tiph = &tunnel->parms.iph; if (iptunnel_handle_offloads(skb, SKB_GSO_IPXIP4)) goto tx_error; skb_set_inner_ipproto(skb, ipproto); ip_tunnel_xmit(skb, dev, tiph, ipproto); return NETDEV_TX_OK; tx_error: kfree_skb(skb); dev->stats.tx_errors++; return NETDEV_TX_OK; } static netdev_tx_t sit_tunnel_xmit(struct sk_buff *skb, struct net_device *dev) { if (!pskb_inet_may_pull(skb)) goto tx_err; switch (skb->protocol) { case htons(ETH_P_IP): sit_tunnel_xmit__(skb, dev, IPPROTO_IPIP); break; case htons(ETH_P_IPV6): ipip6_tunnel_xmit(skb, dev); break; #if IS_ENABLED(CONFIG_MPLS) case htons(ETH_P_MPLS_UC): sit_tunnel_xmit__(skb, dev, IPPROTO_MPLS); break; #endif default: goto tx_err; } return NETDEV_TX_OK; tx_err: dev->stats.tx_errors++; kfree_skb(skb); return NETDEV_TX_OK; } static void ipip6_tunnel_bind_dev(struct net_device *dev) { struct net_device *tdev = NULL; struct ip_tunnel *tunnel; const struct iphdr *iph; struct flowi4 fl4; tunnel = netdev_priv(dev); iph = &tunnel->parms.iph; if (iph->daddr) { struct rtable *rt = ip_route_output_ports(tunnel->net, &fl4, NULL, iph->daddr, iph->saddr, 0, 0, IPPROTO_IPV6, RT_TOS(iph->tos), tunnel->parms.link); if (!IS_ERR(rt)) { tdev = rt->dst.dev; ip_rt_put(rt); } dev->flags |= IFF_POINTOPOINT; } if (!tdev && tunnel->parms.link) tdev = __dev_get_by_index(tunnel->net, tunnel->parms.link); if (tdev) { int t_hlen = tunnel->hlen + sizeof(struct iphdr); dev->hard_header_len = tdev->hard_header_len + sizeof(struct iphdr); dev->mtu = tdev->mtu - t_hlen; if (dev->mtu < IPV6_MIN_MTU) dev->mtu = IPV6_MIN_MTU; } } static void ipip6_tunnel_update(struct ip_tunnel *t, struct ip_tunnel_parm *p, __u32 fwmark) { struct net *net = t->net; struct sit_net *sitn = net_generic(net, sit_net_id); ipip6_tunnel_unlink(sitn, t); synchronize_net(); t->parms.iph.saddr = p->iph.saddr; t->parms.iph.daddr = p->iph.daddr; memcpy(t->dev->dev_addr, &p->iph.saddr, 4); memcpy(t->dev->broadcast, &p->iph.daddr, 4); ipip6_tunnel_link(sitn, t); t->parms.iph.ttl = p->iph.ttl; t->parms.iph.tos = p->iph.tos; t->parms.iph.frag_off = p->iph.frag_off; if (t->parms.link != p->link || t->fwmark != fwmark) { t->parms.link = p->link; t->fwmark = fwmark; ipip6_tunnel_bind_dev(t->dev); } dst_cache_reset(&t->dst_cache); netdev_state_change(t->dev); } #ifdef CONFIG_IPV6_SIT_6RD static int ipip6_tunnel_update_6rd(struct ip_tunnel *t, struct ip_tunnel_6rd *ip6rd) { struct in6_addr prefix; __be32 relay_prefix; if (ip6rd->relay_prefixlen > 32 || ip6rd->prefixlen + (32 - ip6rd->relay_prefixlen) > 64) return -EINVAL; ipv6_addr_prefix(&prefix, &ip6rd->prefix, ip6rd->prefixlen); if (!ipv6_addr_equal(&prefix, &ip6rd->prefix)) return -EINVAL; if (ip6rd->relay_prefixlen) relay_prefix = ip6rd->relay_prefix & htonl(0xffffffffUL << (32 - ip6rd->relay_prefixlen)); else relay_prefix = 0; if (relay_prefix != ip6rd->relay_prefix) return -EINVAL; t->ip6rd.prefix = prefix; t->ip6rd.relay_prefix = relay_prefix; t->ip6rd.prefixlen = ip6rd->prefixlen; t->ip6rd.relay_prefixlen = ip6rd->relay_prefixlen; dst_cache_reset(&t->dst_cache); netdev_state_change(t->dev); return 0; } #endif static bool ipip6_valid_ip_proto(u8 ipproto) { return ipproto == IPPROTO_IPV6 || ipproto == IPPROTO_IPIP || #if IS_ENABLED(CONFIG_MPLS) ipproto == IPPROTO_MPLS || #endif ipproto == 0; } static int ipip6_tunnel_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { int err = 0; struct ip_tunnel_parm p; struct ip_tunnel_prl prl; struct ip_tunnel *t = netdev_priv(dev); struct net *net = t->net; struct sit_net *sitn = net_generic(net, sit_net_id); #ifdef CONFIG_IPV6_SIT_6RD struct ip_tunnel_6rd ip6rd; #endif switch (cmd) { case SIOCGETTUNNEL: #ifdef CONFIG_IPV6_SIT_6RD case SIOCGET6RD: #endif if (dev == sitn->fb_tunnel_dev) { if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p))) { err = -EFAULT; break; } t = ipip6_tunnel_locate(net, &p, 0); if (!t) t = netdev_priv(dev); } err = -EFAULT; if (cmd == SIOCGETTUNNEL) { memcpy(&p, &t->parms, sizeof(p)); if (copy_to_user(ifr->ifr_ifru.ifru_data, &p, sizeof(p))) goto done; #ifdef CONFIG_IPV6_SIT_6RD } else { ip6rd.prefix = t->ip6rd.prefix; ip6rd.relay_prefix = t->ip6rd.relay_prefix; ip6rd.prefixlen = t->ip6rd.prefixlen; ip6rd.relay_prefixlen = t->ip6rd.relay_prefixlen; if (copy_to_user(ifr->ifr_ifru.ifru_data, &ip6rd, sizeof(ip6rd))) goto done; #endif } err = 0; break; case SIOCADDTUNNEL: case SIOCCHGTUNNEL: err = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) goto done; err = -EFAULT; if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p))) goto done; err = -EINVAL; if (!ipip6_valid_ip_proto(p.iph.protocol)) goto done; if (p.iph.version != 4 || p.iph.ihl != 5 || (p.iph.frag_off&htons(~IP_DF))) goto done; if (p.iph.ttl) p.iph.frag_off |= htons(IP_DF); t = ipip6_tunnel_locate(net, &p, cmd == SIOCADDTUNNEL); if (dev != sitn->fb_tunnel_dev && cmd == SIOCCHGTUNNEL) { if (t) { if (t->dev != dev) { err = -EEXIST; break; } } else { if (((dev->flags&IFF_POINTOPOINT) && !p.iph.daddr) || (!(dev->flags&IFF_POINTOPOINT) && p.iph.daddr)) { err = -EINVAL; break; } t = netdev_priv(dev); } ipip6_tunnel_update(t, &p, t->fwmark); } if (t) { err = 0; if (copy_to_user(ifr->ifr_ifru.ifru_data, &t->parms, sizeof(p))) err = -EFAULT; } else err = (cmd == SIOCADDTUNNEL ? -ENOBUFS : -ENOENT); break; case SIOCDELTUNNEL: err = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) goto done; if (dev == sitn->fb_tunnel_dev) { err = -EFAULT; if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p))) goto done; err = -ENOENT; t = ipip6_tunnel_locate(net, &p, 0); if (!t) goto done; err = -EPERM; if (t == netdev_priv(sitn->fb_tunnel_dev)) goto done; dev = t->dev; } unregister_netdevice(dev); err = 0; break; case SIOCGETPRL: err = -EINVAL; if (dev == sitn->fb_tunnel_dev) goto done; err = ipip6_tunnel_get_prl(t, ifr->ifr_ifru.ifru_data); break; case SIOCADDPRL: case SIOCDELPRL: case SIOCCHGPRL: err = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) goto done; err = -EINVAL; if (dev == sitn->fb_tunnel_dev) goto done; err = -EFAULT; if (copy_from_user(&prl, ifr->ifr_ifru.ifru_data, sizeof(prl))) goto done; switch (cmd) { case SIOCDELPRL: err = ipip6_tunnel_del_prl(t, &prl); break; case SIOCADDPRL: case SIOCCHGPRL: err = ipip6_tunnel_add_prl(t, &prl, cmd == SIOCCHGPRL); break; } dst_cache_reset(&t->dst_cache); netdev_state_change(dev); break; #ifdef CONFIG_IPV6_SIT_6RD case SIOCADD6RD: case SIOCCHG6RD: case SIOCDEL6RD: err = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) goto done; err = -EFAULT; if (copy_from_user(&ip6rd, ifr->ifr_ifru.ifru_data, sizeof(ip6rd))) goto done; if (cmd != SIOCDEL6RD) { err = ipip6_tunnel_update_6rd(t, &ip6rd); if (err < 0) goto done; } else ipip6_tunnel_clone_6rd(dev, sitn); err = 0; break; #endif default: err = -EINVAL; } done: return err; } static const struct net_device_ops ipip6_netdev_ops = { .ndo_init = ipip6_tunnel_init, .ndo_uninit = ipip6_tunnel_uninit, .ndo_start_xmit = sit_tunnel_xmit, .ndo_do_ioctl = ipip6_tunnel_ioctl, .ndo_get_stats64 = ip_tunnel_get_stats64, .ndo_get_iflink = ip_tunnel_get_iflink, }; static void ipip6_dev_free(struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); dst_cache_destroy(&tunnel->dst_cache); free_percpu(dev->tstats); } #define SIT_FEATURES (NETIF_F_SG | \ NETIF_F_FRAGLIST | \ NETIF_F_HIGHDMA | \ NETIF_F_GSO_SOFTWARE | \ NETIF_F_HW_CSUM) static void ipip6_tunnel_setup(struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); int t_hlen = tunnel->hlen + sizeof(struct iphdr); dev->netdev_ops = &ipip6_netdev_ops; dev->needs_free_netdev = true; dev->priv_destructor = ipip6_dev_free; dev->type = ARPHRD_SIT; dev->hard_header_len = LL_MAX_HEADER + t_hlen; dev->mtu = ETH_DATA_LEN - t_hlen; dev->min_mtu = IPV6_MIN_MTU; dev->max_mtu = IP6_MAX_MTU - t_hlen; dev->flags = IFF_NOARP; netif_keep_dst(dev); dev->addr_len = 4; dev->features |= NETIF_F_LLTX; dev->features |= SIT_FEATURES; dev->hw_features |= SIT_FEATURES; } static int ipip6_tunnel_init(struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); int err; tunnel->dev = dev; tunnel->net = dev_net(dev); strcpy(tunnel->parms.name, dev->name); ipip6_tunnel_bind_dev(dev); dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats); if (!dev->tstats) return -ENOMEM; err = dst_cache_init(&tunnel->dst_cache, GFP_KERNEL); if (err) { free_percpu(dev->tstats); dev->tstats = NULL; return err; } return 0; } static void __net_init ipip6_fb_tunnel_init(struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); struct iphdr *iph = &tunnel->parms.iph; struct net *net = dev_net(dev); struct sit_net *sitn = net_generic(net, sit_net_id); iph->version = 4; iph->protocol = IPPROTO_IPV6; iph->ihl = 5; iph->ttl = 64; dev_hold(dev); rcu_assign_pointer(sitn->tunnels_wc[0], tunnel); } static int ipip6_validate(struct nlattr *tb[], struct nlattr *data[], struct netlink_ext_ack *extack) { u8 proto; if (!data || !data[IFLA_IPTUN_PROTO]) return 0; proto = nla_get_u8(data[IFLA_IPTUN_PROTO]); if (!ipip6_valid_ip_proto(proto)) return -EINVAL; return 0; } static void ipip6_netlink_parms(struct nlattr *data[], struct ip_tunnel_parm *parms, __u32 *fwmark) { memset(parms, 0, sizeof(*parms)); parms->iph.version = 4; parms->iph.protocol = IPPROTO_IPV6; parms->iph.ihl = 5; parms->iph.ttl = 64; if (!data) return; if (data[IFLA_IPTUN_LINK]) parms->link = nla_get_u32(data[IFLA_IPTUN_LINK]); if (data[IFLA_IPTUN_LOCAL]) parms->iph.saddr = nla_get_be32(data[IFLA_IPTUN_LOCAL]); if (data[IFLA_IPTUN_REMOTE]) parms->iph.daddr = nla_get_be32(data[IFLA_IPTUN_REMOTE]); if (data[IFLA_IPTUN_TTL]) { parms->iph.ttl = nla_get_u8(data[IFLA_IPTUN_TTL]); if (parms->iph.ttl) parms->iph.frag_off = htons(IP_DF); } if (data[IFLA_IPTUN_TOS]) parms->iph.tos = nla_get_u8(data[IFLA_IPTUN_TOS]); if (!data[IFLA_IPTUN_PMTUDISC] || nla_get_u8(data[IFLA_IPTUN_PMTUDISC])) parms->iph.frag_off = htons(IP_DF); if (data[IFLA_IPTUN_FLAGS]) parms->i_flags = nla_get_be16(data[IFLA_IPTUN_FLAGS]); if (data[IFLA_IPTUN_PROTO]) parms->iph.protocol = nla_get_u8(data[IFLA_IPTUN_PROTO]); if (data[IFLA_IPTUN_FWMARK]) *fwmark = nla_get_u32(data[IFLA_IPTUN_FWMARK]); } /* This function returns true when ENCAP attributes are present in the nl msg */ static bool ipip6_netlink_encap_parms(struct nlattr *data[], struct ip_tunnel_encap *ipencap) { bool ret = false; memset(ipencap, 0, sizeof(*ipencap)); if (!data) return ret; if (data[IFLA_IPTUN_ENCAP_TYPE]) { ret = true; ipencap->type = nla_get_u16(data[IFLA_IPTUN_ENCAP_TYPE]); } if (data[IFLA_IPTUN_ENCAP_FLAGS]) { ret = true; ipencap->flags = nla_get_u16(data[IFLA_IPTUN_ENCAP_FLAGS]); } if (data[IFLA_IPTUN_ENCAP_SPORT]) { ret = true; ipencap->sport = nla_get_be16(data[IFLA_IPTUN_ENCAP_SPORT]); } if (data[IFLA_IPTUN_ENCAP_DPORT]) { ret = true; ipencap->dport = nla_get_be16(data[IFLA_IPTUN_ENCAP_DPORT]); } return ret; } #ifdef CONFIG_IPV6_SIT_6RD /* This function returns true when 6RD attributes are present in the nl msg */ static bool ipip6_netlink_6rd_parms(struct nlattr *data[], struct ip_tunnel_6rd *ip6rd) { bool ret = false; memset(ip6rd, 0, sizeof(*ip6rd)); if (!data) return ret; if (data[IFLA_IPTUN_6RD_PREFIX]) { ret = true; ip6rd->prefix = nla_get_in6_addr(data[IFLA_IPTUN_6RD_PREFIX]); } if (data[IFLA_IPTUN_6RD_RELAY_PREFIX]) { ret = true; ip6rd->relay_prefix = nla_get_be32(data[IFLA_IPTUN_6RD_RELAY_PREFIX]); } if (data[IFLA_IPTUN_6RD_PREFIXLEN]) { ret = true; ip6rd->prefixlen = nla_get_u16(data[IFLA_IPTUN_6RD_PREFIXLEN]); } if (data[IFLA_IPTUN_6RD_RELAY_PREFIXLEN]) { ret = true; ip6rd->relay_prefixlen = nla_get_u16(data[IFLA_IPTUN_6RD_RELAY_PREFIXLEN]); } return ret; } #endif static int ipip6_newlink(struct net *src_net, struct net_device *dev, struct nlattr *tb[], struct nlattr *data[], struct netlink_ext_ack *extack) { struct net *net = dev_net(dev); struct ip_tunnel *nt; struct ip_tunnel_encap ipencap; #ifdef CONFIG_IPV6_SIT_6RD struct ip_tunnel_6rd ip6rd; #endif int err; nt = netdev_priv(dev); if (ipip6_netlink_encap_parms(data, &ipencap)) { err = ip_tunnel_encap_setup(nt, &ipencap); if (err < 0) return err; } ipip6_netlink_parms(data, &nt->parms, &nt->fwmark); if (ipip6_tunnel_locate(net, &nt->parms, 0)) return -EEXIST; err = ipip6_tunnel_create(dev); if (err < 0) return err; if (tb[IFLA_MTU]) { u32 mtu = nla_get_u32(tb[IFLA_MTU]); if (mtu >= IPV6_MIN_MTU && mtu <= IP6_MAX_MTU - dev->hard_header_len) dev->mtu = mtu; } #ifdef CONFIG_IPV6_SIT_6RD if (ipip6_netlink_6rd_parms(data, &ip6rd)) err = ipip6_tunnel_update_6rd(nt, &ip6rd); #endif return err; } static int ipip6_changelink(struct net_device *dev, struct nlattr *tb[], struct nlattr *data[], struct netlink_ext_ack *extack) { struct ip_tunnel *t = netdev_priv(dev); struct ip_tunnel_parm p; struct ip_tunnel_encap ipencap; struct net *net = t->net; struct sit_net *sitn = net_generic(net, sit_net_id); #ifdef CONFIG_IPV6_SIT_6RD struct ip_tunnel_6rd ip6rd; #endif __u32 fwmark = t->fwmark; int err; if (dev == sitn->fb_tunnel_dev) return -EINVAL; if (ipip6_netlink_encap_parms(data, &ipencap)) { err = ip_tunnel_encap_setup(t, &ipencap); if (err < 0) return err; } ipip6_netlink_parms(data, &p, &fwmark); if (((dev->flags & IFF_POINTOPOINT) && !p.iph.daddr) || (!(dev->flags & IFF_POINTOPOINT) && p.iph.daddr)) return -EINVAL; t = ipip6_tunnel_locate(net, &p, 0); if (t) { if (t->dev != dev) return -EEXIST; } else t = netdev_priv(dev); ipip6_tunnel_update(t, &p, fwmark); #ifdef CONFIG_IPV6_SIT_6RD if (ipip6_netlink_6rd_parms(data, &ip6rd)) return ipip6_tunnel_update_6rd(t, &ip6rd); #endif return 0; } static size_t ipip6_get_size(const struct net_device *dev) { return /* IFLA_IPTUN_LINK */ nla_total_size(4) + /* IFLA_IPTUN_LOCAL */ nla_total_size(4) + /* IFLA_IPTUN_REMOTE */ nla_total_size(4) + /* IFLA_IPTUN_TTL */ nla_total_size(1) + /* IFLA_IPTUN_TOS */ nla_total_size(1) + /* IFLA_IPTUN_PMTUDISC */ nla_total_size(1) + /* IFLA_IPTUN_FLAGS */ nla_total_size(2) + /* IFLA_IPTUN_PROTO */ nla_total_size(1) + #ifdef CONFIG_IPV6_SIT_6RD /* IFLA_IPTUN_6RD_PREFIX */ nla_total_size(sizeof(struct in6_addr)) + /* IFLA_IPTUN_6RD_RELAY_PREFIX */ nla_total_size(4) + /* IFLA_IPTUN_6RD_PREFIXLEN */ nla_total_size(2) + /* IFLA_IPTUN_6RD_RELAY_PREFIXLEN */ nla_total_size(2) + #endif /* IFLA_IPTUN_ENCAP_TYPE */ nla_total_size(2) + /* IFLA_IPTUN_ENCAP_FLAGS */ nla_total_size(2) + /* IFLA_IPTUN_ENCAP_SPORT */ nla_total_size(2) + /* IFLA_IPTUN_ENCAP_DPORT */ nla_total_size(2) + /* IFLA_IPTUN_FWMARK */ nla_total_size(4) + 0; } static int ipip6_fill_info(struct sk_buff *skb, const struct net_device *dev) { struct ip_tunnel *tunnel = netdev_priv(dev); struct ip_tunnel_parm *parm = &tunnel->parms; if (nla_put_u32(skb, IFLA_IPTUN_LINK, parm->link) || nla_put_in_addr(skb, IFLA_IPTUN_LOCAL, parm->iph.saddr) || nla_put_in_addr(skb, IFLA_IPTUN_REMOTE, parm->iph.daddr) || nla_put_u8(skb, IFLA_IPTUN_TTL, parm->iph.ttl) || nla_put_u8(skb, IFLA_IPTUN_TOS, parm->iph.tos) || nla_put_u8(skb, IFLA_IPTUN_PMTUDISC, !!(parm->iph.frag_off & htons(IP_DF))) || nla_put_u8(skb, IFLA_IPTUN_PROTO, parm->iph.protocol) || nla_put_be16(skb, IFLA_IPTUN_FLAGS, parm->i_flags) || nla_put_u32(skb, IFLA_IPTUN_FWMARK, tunnel->fwmark)) goto nla_put_failure; #ifdef CONFIG_IPV6_SIT_6RD if (nla_put_in6_addr(skb, IFLA_IPTUN_6RD_PREFIX, &tunnel->ip6rd.prefix) || nla_put_in_addr(skb, IFLA_IPTUN_6RD_RELAY_PREFIX, tunnel->ip6rd.relay_prefix) || nla_put_u16(skb, IFLA_IPTUN_6RD_PREFIXLEN, tunnel->ip6rd.prefixlen) || nla_put_u16(skb, IFLA_IPTUN_6RD_RELAY_PREFIXLEN, tunnel->ip6rd.relay_prefixlen)) goto nla_put_failure; #endif if (nla_put_u16(skb, IFLA_IPTUN_ENCAP_TYPE, tunnel->encap.type) || nla_put_be16(skb, IFLA_IPTUN_ENCAP_SPORT, tunnel->encap.sport) || nla_put_be16(skb, IFLA_IPTUN_ENCAP_DPORT, tunnel->encap.dport) || nla_put_u16(skb, IFLA_IPTUN_ENCAP_FLAGS, tunnel->encap.flags)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } static const struct nla_policy ipip6_policy[IFLA_IPTUN_MAX + 1] = { [IFLA_IPTUN_LINK] = { .type = NLA_U32 }, [IFLA_IPTUN_LOCAL] = { .type = NLA_U32 }, [IFLA_IPTUN_REMOTE] = { .type = NLA_U32 }, [IFLA_IPTUN_TTL] = { .type = NLA_U8 }, [IFLA_IPTUN_TOS] = { .type = NLA_U8 }, [IFLA_IPTUN_PMTUDISC] = { .type = NLA_U8 }, [IFLA_IPTUN_FLAGS] = { .type = NLA_U16 }, [IFLA_IPTUN_PROTO] = { .type = NLA_U8 }, #ifdef CONFIG_IPV6_SIT_6RD [IFLA_IPTUN_6RD_PREFIX] = { .len = sizeof(struct in6_addr) }, [IFLA_IPTUN_6RD_RELAY_PREFIX] = { .type = NLA_U32 }, [IFLA_IPTUN_6RD_PREFIXLEN] = { .type = NLA_U16 }, [IFLA_IPTUN_6RD_RELAY_PREFIXLEN] = { .type = NLA_U16 }, #endif [IFLA_IPTUN_ENCAP_TYPE] = { .type = NLA_U16 }, [IFLA_IPTUN_ENCAP_FLAGS] = { .type = NLA_U16 }, [IFLA_IPTUN_ENCAP_SPORT] = { .type = NLA_U16 }, [IFLA_IPTUN_ENCAP_DPORT] = { .type = NLA_U16 }, [IFLA_IPTUN_FWMARK] = { .type = NLA_U32 }, }; static void ipip6_dellink(struct net_device *dev, struct list_head *head) { struct net *net = dev_net(dev); struct sit_net *sitn = net_generic(net, sit_net_id); if (dev != sitn->fb_tunnel_dev) unregister_netdevice_queue(dev, head); } static struct rtnl_link_ops sit_link_ops __read_mostly = { .kind = "sit", .maxtype = IFLA_IPTUN_MAX, .policy = ipip6_policy, .priv_size = sizeof(struct ip_tunnel), .setup = ipip6_tunnel_setup, .validate = ipip6_validate, .newlink = ipip6_newlink, .changelink = ipip6_changelink, .get_size = ipip6_get_size, .fill_info = ipip6_fill_info, .dellink = ipip6_dellink, .get_link_net = ip_tunnel_get_link_net, }; static struct xfrm_tunnel sit_handler __read_mostly = { .handler = ipip6_rcv, .err_handler = ipip6_err, .priority = 1, }; static struct xfrm_tunnel ipip_handler __read_mostly = { .handler = ipip_rcv, .err_handler = ipip6_err, .priority = 2, }; #if IS_ENABLED(CONFIG_MPLS) static struct xfrm_tunnel mplsip_handler __read_mostly = { .handler = mplsip_rcv, .err_handler = ipip6_err, .priority = 2, }; #endif static void __net_exit sit_destroy_tunnels(struct net *net, struct list_head *head) { struct sit_net *sitn = net_generic(net, sit_net_id); struct net_device *dev, *aux; int prio; for_each_netdev_safe(net, dev, aux) if (dev->rtnl_link_ops == &sit_link_ops) unregister_netdevice_queue(dev, head); for (prio = 1; prio < 4; prio++) { int h; for (h = 0; h < IP6_SIT_HASH_SIZE; h++) { struct ip_tunnel *t; t = rtnl_dereference(sitn->tunnels[prio][h]); while (t) { /* If dev is in the same netns, it has already * been added to the list by the previous loop. */ if (!net_eq(dev_net(t->dev), net)) unregister_netdevice_queue(t->dev, head); t = rtnl_dereference(t->next); } } } } static int __net_init sit_init_net(struct net *net) { struct sit_net *sitn = net_generic(net, sit_net_id); struct ip_tunnel *t; int err; sitn->tunnels[0] = sitn->tunnels_wc; sitn->tunnels[1] = sitn->tunnels_l; sitn->tunnels[2] = sitn->tunnels_r; sitn->tunnels[3] = sitn->tunnels_r_l; if (!net_has_fallback_tunnels(net)) return 0; sitn->fb_tunnel_dev = alloc_netdev(sizeof(struct ip_tunnel), "sit0", NET_NAME_UNKNOWN, ipip6_tunnel_setup); if (!sitn->fb_tunnel_dev) { err = -ENOMEM; goto err_alloc_dev; } dev_net_set(sitn->fb_tunnel_dev, net); sitn->fb_tunnel_dev->rtnl_link_ops = &sit_link_ops; /* FB netdevice is special: we have one, and only one per netns. * Allowing to move it to another netns is clearly unsafe. */ sitn->fb_tunnel_dev->features |= NETIF_F_NETNS_LOCAL; err = register_netdev(sitn->fb_tunnel_dev); if (err) goto err_reg_dev; ipip6_tunnel_clone_6rd(sitn->fb_tunnel_dev, sitn); ipip6_fb_tunnel_init(sitn->fb_tunnel_dev); t = netdev_priv(sitn->fb_tunnel_dev); strcpy(t->parms.name, sitn->fb_tunnel_dev->name); return 0; err_reg_dev: ipip6_dev_free(sitn->fb_tunnel_dev); free_netdev(sitn->fb_tunnel_dev); err_alloc_dev: return err; } static void __net_exit sit_exit_batch_net(struct list_head *net_list) { LIST_HEAD(list); struct net *net; rtnl_lock(); list_for_each_entry(net, net_list, exit_list) sit_destroy_tunnels(net, &list); unregister_netdevice_many(&list); rtnl_unlock(); } static struct pernet_operations sit_net_ops = { .init = sit_init_net, .exit_batch = sit_exit_batch_net, .id = &sit_net_id, .size = sizeof(struct sit_net), }; static void __exit sit_cleanup(void) { rtnl_link_unregister(&sit_link_ops); xfrm4_tunnel_deregister(&sit_handler, AF_INET6); xfrm4_tunnel_deregister(&ipip_handler, AF_INET); #if IS_ENABLED(CONFIG_MPLS) xfrm4_tunnel_deregister(&mplsip_handler, AF_MPLS); #endif unregister_pernet_device(&sit_net_ops); rcu_barrier(); /* Wait for completion of call_rcu()'s */ } static int __init sit_init(void) { int err; pr_info("IPv6, IPv4 and MPLS over IPv4 tunneling driver\n"); err = register_pernet_device(&sit_net_ops); if (err < 0) return err; err = xfrm4_tunnel_register(&sit_handler, AF_INET6); if (err < 0) { pr_info("%s: can't register ip6ip4\n", __func__); goto xfrm_tunnel_failed; } err = xfrm4_tunnel_register(&ipip_handler, AF_INET); if (err < 0) { pr_info("%s: can't register ip4ip4\n", __func__); goto xfrm_tunnel4_failed; } #if IS_ENABLED(CONFIG_MPLS) err = xfrm4_tunnel_register(&mplsip_handler, AF_MPLS); if (err < 0) { pr_info("%s: can't register mplsip\n", __func__); goto xfrm_tunnel_mpls_failed; } #endif err = rtnl_link_register(&sit_link_ops); if (err < 0) goto rtnl_link_failed; out: return err; rtnl_link_failed: #if IS_ENABLED(CONFIG_MPLS) xfrm4_tunnel_deregister(&mplsip_handler, AF_MPLS); xfrm_tunnel_mpls_failed: #endif xfrm4_tunnel_deregister(&ipip_handler, AF_INET); xfrm_tunnel4_failed: xfrm4_tunnel_deregister(&sit_handler, AF_INET6); xfrm_tunnel_failed: unregister_pernet_device(&sit_net_ops); goto out; } module_init(sit_init); module_exit(sit_cleanup); MODULE_LICENSE("GPL"); MODULE_ALIAS_RTNL_LINK("sit"); MODULE_ALIAS_NETDEV("sit0");
./CrossVul/dataset_final_sorted/CWE-772/c/good_1161_0
crossvul-cpp_data_bad_1168_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-772/c/bad_1168_1
crossvul-cpp_data_good_362_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT IIIII FFFFF FFFFF % % T I F F % % T I FFF FFF % % T I F F % % T IIIII F F % % % % % % Read/Write TIFF Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ #ifdef __VMS #define JPEG_SUPPORT 1 #endif /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/profile.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread_.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_TIFF_DELEGATE) # if defined(MAGICKCORE_HAVE_TIFFCONF_H) # include "tiffconf.h" # endif # include "tiff.h" # include "tiffio.h" # if !defined(COMPRESSION_ADOBE_DEFLATE) # define COMPRESSION_ADOBE_DEFLATE 8 # endif # if !defined(PREDICTOR_HORIZONTAL) # define PREDICTOR_HORIZONTAL 2 # endif # if !defined(TIFFTAG_COPYRIGHT) # define TIFFTAG_COPYRIGHT 33432 # endif # if !defined(TIFFTAG_OPIIMAGEID) # define TIFFTAG_OPIIMAGEID 32781 # endif #include "psd-private.h" /* Typedef declarations. */ typedef enum { ReadSingleSampleMethod, ReadRGBAMethod, ReadCMYKAMethod, ReadYCCKMethod, ReadStripMethod, ReadTileMethod, ReadGenericMethod } TIFFMethodType; typedef struct _PhotoshopProfile { StringInfo *data; MagickOffsetType offset; size_t length, extent, quantum; } PhotoshopProfile; #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) typedef struct _ExifInfo { unsigned int tag, type, variable_length; const char *property; } ExifInfo; static const ExifInfo exif_info[] = { { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" }, { EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" }, { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" }, { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" }, { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" }, { EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" }, { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" }, { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" }, { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" }, { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" }, { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" }, { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" }, { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" }, { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" }, { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" }, { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" }, { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" }, { EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" }, { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" }, { EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" }, { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" }, { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" }, { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" }, { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" }, { EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" }, { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" }, { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" }, { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" }, { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" }, { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" }, { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" }, { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" }, { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" }, { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" }, { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" }, { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" }, { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" }, { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" }, { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" }, { EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" }, { EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" }, { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" }, { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" }, { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" }, { EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" }, { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" }, { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" }, { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" }, { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" }, { EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" }, { EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" }, { EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" }, { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" }, { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" }, { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" }, { 0, 0, 0, (char *) NULL } }; #endif #endif /* MAGICKCORE_TIFF_DELEGATE */ /* Global declarations. */ static MagickThreadKey tiff_exception; static SemaphoreInfo *tiff_semaphore = (SemaphoreInfo *) NULL; static TIFFErrorHandler error_handler, warning_handler; static volatile MagickBooleanType instantiate_key = MagickFalse; /* Forward declarations. */ #if defined(MAGICKCORE_TIFF_DELEGATE) static Image * ReadTIFFImage(const ImageInfo *,ExceptionInfo *); static MagickBooleanType WriteGROUP4Image(const ImageInfo *,Image *,ExceptionInfo *), WritePTIFImage(const ImageInfo *,Image *,ExceptionInfo *), WriteTIFFImage(const ImageInfo *,Image *,ExceptionInfo *); static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset, const int whence,void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; switch (whence) { case SEEK_SET: default: { if (offset < 0) return(-1); profile->offset=offset; break; } case SEEK_CUR: { if ((profile->offset+offset) < 0) return(-1); profile->offset+=offset; break; } case SEEK_END: { if (((MagickOffsetType) profile->length+offset) < 0) return(-1); profile->offset=profile->length+offset; break; } } return(profile->offset); } static MagickOffsetType TIFFTellCustomStream(void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; return(profile->offset); } static void InitPSDInfo(const Image *image, PSDInfo *info) { info->version=1; info->columns=image->columns; info->rows=image->rows; /* Setting the mode to a value that won't change the colorspace */ info->mode=10; info->channels=1U; if (image->storage_class == PseudoClass) info->mode=2; // indexed mode else { info->channels=(unsigned short) image->number_channels; info->min_channels=info->channels; if (image->alpha_trait == BlendPixelTrait) info->min_channels--; } } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T I F F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTIFF() returns MagickTrue if the image format type, identified by the % magick string, is TIFF. % % The format of the IsTIFF method is: % % MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\115\115\000\052",4) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\052\000",4) == 0) return(MagickTrue); #if defined(TIFF_VERSION_BIG) if (length < 8) return(MagickFalse); if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0) return(MagickTrue); #endif return(MagickFalse); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadGROUP4Image method is: % % Image *ReadGROUP4Image(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline size_t WriteLSBLong(FILE *file,const size_t value) { unsigned char buffer[4]; buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); return(fwrite(buffer,1,4,file)); } static Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file); if (length != 10) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\000\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite("\001\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file); length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\021\001\003\000\001\000\000\000",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite("\022\001\003\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\026\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite("\032\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\033\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file); length=fwrite("\000\000\000\000",1,4,file); length=WriteLSBLong(file,(long) image->resolution.x); length=WriteLSBLong(file,1); status=MagickTrue; for (length=0; (c=ReadBlobByte(image)) != EOF; length++) if (fputc(c,file) != c) status=MagickFalse; offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); if (ferror(file) != 0) { (void) fclose(file); ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); } (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent); } (void) RelinquishUniqueFileResource(filename); if (status == MagickFalse) image=DestroyImage(image); return(image); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTIFFImage() reads a Tagged image file and returns it. It allocates the % memory necessary for the new Image structure and returns a pointer to the % new image. % % The format of the ReadTIFFImage method is: % % Image *ReadTIFFImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline unsigned char ClampYCC(double value) { value=255.0-value; if (value < 0.0) return((unsigned char)0); if (value > 255.0) return((unsigned char)255); return((unsigned char)(value)); } static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(image,q)+0.5; if (a > 1.0) a-=1.0; b=QuantumScale*GetPixelb(image,q)+0.5; if (b > 1.0) b-=1.0; SetPixela(image,QuantumRange*a,q); SetPixelb(image,QuantumRange*b,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) { status=MagickFalse; break; } } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType ReadProfile(Image *image,const char *name, const unsigned char *datum,ssize_t length,ExceptionInfo *exception) { MagickBooleanType status; StringInfo *profile; if (length < 4) return(MagickFalse); profile=BlobToStringInfo(datum,(size_t) length); if (profile == (StringInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=SetImageProfile(image,name,profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); return(MagickTrue); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int TIFFCloseBlob(thandle_t image) { (void) CloseBlob((Image *) image); return(0); } static void TIFFErrors(const char *module,const char *format,va_list error) { char message[MagickPathExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MagickPathExtent,format,error); #else (void) vsprintf(message,format,error); #endif (void) ConcatenateMagickString(message,".",MagickPathExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message, "`%s'",module); } static toff_t TIFFGetBlobSize(thandle_t image) { return((toff_t) GetBlobSize((Image *) image)); } static void TIFFGetProfiles(TIFF *tiff,Image *image,ExceptionInfo *exception) { uint32 length; unsigned char *profile; length=0; #if defined(TIFFTAG_ICCPROFILE) if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"icc",profile,(ssize_t) length,exception); #endif #if defined(TIFFTAG_PHOTOSHOP) if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"8bim",profile,(ssize_t) length,exception); #endif #if defined(TIFFTAG_RICHTIFFIPTC) if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) { if (TIFFIsByteSwapped(tiff) != 0) TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length); (void) ReadProfile(image,"iptc",profile,4L*length,exception); } #endif #if defined(TIFFTAG_XMLPACKET) if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"xmp",profile,(ssize_t) length,exception); #endif if ((TIFFGetField(tiff,34118,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length, exception); if ((TIFFGetField(tiff,37724,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception); } static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception) { char message[MagickPathExtent], *text; uint32 count, length, type; unsigned long *tietz; if ((TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:artist",text,exception); if ((TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:copyright",text,exception); if ((TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:timestamp",text,exception); if ((TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:document",text,exception); if ((TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:hostcomputer",text,exception); if ((TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"comment",text,exception); if ((TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:make",text,exception); if ((TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:model",text,exception); if ((TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) && (text != (char *) NULL)) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message,exception); } if ((TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"label",text,exception); if ((TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:software",text,exception); if ((TIFFGetField(tiff,33423,&count,&text) == 1) && (text != (char *) NULL)) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message,exception); } if ((TIFFGetField(tiff,36867,&count,&text) == 1) && (text != (char *) NULL)) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message,exception); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE", exception); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK",exception); break; } default: break; } if ((TIFFGetField(tiff,37706,&length,&tietz) == 1) && (tietz != (unsigned long *) NULL)) { (void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]); (void) SetImageProperty(image,"tiff:tietz_offset",message,exception); } } static void TIFFGetEXIFProperties(TIFF *tiff,Image *image, ExceptionInfo *exception) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) char value[MagickPathExtent]; register ssize_t i; tdir_t directory; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif offset; void *sans[2] = { NULL, NULL }; /* Read EXIF properties. */ offset=0; if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1) return; directory=TIFFCurrentDirectory(tiff); if (TIFFReadEXIFDirectory(tiff,offset) != 1) { TIFFSetDirectory(tiff,directory); return; } for (i=0; exif_info[i].tag != 0; i++) { *value='\0'; switch (exif_info[i].type) { case TIFF_ASCII: { char *ascii; ascii=(char *) NULL; if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,sans) == 1) && (ascii != (char *) NULL) && (*ascii != '\0')) (void) CopyMagickString(value,ascii,MagickPathExtent); break; } case TIFF_SHORT: { if (exif_info[i].variable_length == 0) { uint16 shorty; shorty=0; if (TIFFGetField(tiff,exif_info[i].tag,&shorty,sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d",shorty); } else { int tiff_status; uint16 *shorty; uint16 shorty_num; tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty, sans); if (tiff_status == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d", shorty_num != 0 ? shorty[0] : 0); } break; } case TIFF_LONG: { uint32 longy; longy=0; if (TIFFGetField(tiff,exif_info[i].tag,&longy,sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d",longy); break; } #if defined(TIFF_VERSION_BIG) case TIFF_LONG8: { uint64 long8y; long8y=0; if (TIFFGetField(tiff,exif_info[i].tag,&long8y,sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) ((MagickOffsetType) long8y)); break; } #endif case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float floaty; floaty=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&floaty,sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%g",(double) floaty); break; } case TIFF_DOUBLE: { double doubley; doubley=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&doubley,sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%g",doubley); break; } default: break; } if (*value != '\0') (void) SetImageProperty(image,exif_info[i].property,value,exception); } TIFFSetDirectory(tiff,directory); #else (void) tiff; (void) image; #endif } static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size) { *base=(tdata_t *) GetBlobStreamData((Image *) image); if (*base != (tdata_t *) NULL) *size=(toff_t) GetBlobSize((Image *) image); if (*base != (tdata_t *) NULL) return(1); return(0); } static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) ReadBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static int32 TIFFReadPixels(TIFF *tiff,const tsample_t sample,const ssize_t row, tdata_t scanline) { int32 status; status=TIFFReadScanline(tiff,scanline,(uint32) row,sample); return(status); } static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence) { return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence)); } static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size) { (void) image; (void) base; (void) size; } static void TIFFWarnings(const char *module,const char *format,va_list warning) { char message[MagickPathExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MagickPathExtent,format,warning); #else (void) vsprintf(message,format,warning); #endif (void) ConcatenateMagickString(message,".",MagickPathExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'",module); } static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) WriteBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric, uint16 bits_per_sample,uint16 samples_per_pixel) { #define BUFFER_SIZE 2048 MagickOffsetType position, offset; register size_t i; TIFFMethodType method; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif *value; unsigned char buffer[BUFFER_SIZE+32]; unsigned short length; /* Only support 8 bit for now. */ if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) || (samples_per_pixel != 4)) return(ReadGenericMethod); /* Search for Adobe APP14 JPEG marker. */ value=NULL; if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value) || (value == NULL)) return(ReadRGBAMethod); position=TellBlob(image); offset=(MagickOffsetType) (value[0]); if (SeekBlob(image,offset,SEEK_SET) != offset) return(ReadRGBAMethod); method=ReadRGBAMethod; if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE) { for (i=0; i < BUFFER_SIZE; i++) { while (i < BUFFER_SIZE) { if (buffer[i++] == 255) break; } while (i < BUFFER_SIZE) { if (buffer[++i] != 255) break; } if (buffer[i++] == 216) /* JPEG_MARKER_SOI */ continue; length=(unsigned short) (((unsigned int) (buffer[i] << 8) | (unsigned int) buffer[i+1]) & 0xffff); if (i+(size_t) length >= BUFFER_SIZE) break; if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */ { if (length != 14) break; /* 0 == CMYK, 1 == YCbCr, 2 = YCCK */ if (buffer[i+13] == 2) method=ReadYCCKMethod; break; } i+=(size_t) length; } } (void) SeekBlob(image,position,SEEK_SET); return(method); } static ssize_t TIFFReadCustomStream(unsigned char *data,const size_t count, void *user_data) { PhotoshopProfile *profile; size_t total; ssize_t remaining; if (count == 0) return(0); profile=(PhotoshopProfile *) user_data; remaining=(MagickOffsetType) profile->length-profile->offset; if (remaining <= 0) return(-1); total=MagickMin(count, (size_t) remaining); (void) memcpy(data,profile->data->datum+profile->offset,total); profile->offset+=total; return(total); } static CustomStreamInfo *TIFFAcquireCustomStreamForReading( PhotoshopProfile *profile,ExceptionInfo *exception) { CustomStreamInfo *custom_stream; custom_stream=AcquireCustomStreamInfo(exception); if (custom_stream == (CustomStreamInfo *) NULL) return(custom_stream); SetCustomStreamData(custom_stream,(void *) profile); SetCustomStreamReader(custom_stream,TIFFReadCustomStream); SetCustomStreamSeeker(custom_stream,TIFFSeekCustomStream); SetCustomStreamTeller(custom_stream,TIFFTellCustomStream); return(custom_stream); } static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; const StringInfo *profile; CustomStreamInfo *custom_stream; Image *layers; PhotoshopProfile photoshop_profile; PSDInfo info; register ssize_t i; if (GetImageListLength(image) != 1) return; if ((image_info->number_scenes == 1) && (image_info->scene == 0)) return; option=GetImageOption(image_info,"tiff:ignore-layers"); if (option != (const char * ) NULL) return; profile=GetImageProfile(image,"tiff:37724"); if (profile == (const StringInfo *) NULL) return; for (i=0; i < (ssize_t) profile->length-8; i++) { if (LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0) continue; i+=4; if ((LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) || (LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) || (LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) || (LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0)) break; } i+=4; if (i >= (ssize_t) (profile->length-8)) return; photoshop_profile.data=(StringInfo *) profile; photoshop_profile.length=profile->length; custom_stream=TIFFAcquireCustomStreamForReading(&photoshop_profile,exception); if (custom_stream == (CustomStreamInfo *) NULL) return; layers=CloneImage(image,0,0,MagickTrue,exception); if (layers == (Image *) NULL) { custom_stream=DestroyCustomStreamInfo(custom_stream); return; } (void) DeleteImageProfile(layers,"tiff:37724"); AttachCustomStream(layers->blob,custom_stream); SeekBlob(layers,(MagickOffsetType) i,SEEK_SET); InitPSDInfo(layers,&info); (void) ReadPSDLayers(layers,image_info,&info,exception); DeleteImageFromList(&layers); if (layers != (Image *) NULL) { SetImageArtifact(image,"tiff:has-layers","true"); AppendImageToList(&image,layers); while (layers != (Image *) NULL) { SetImageArtifact(layers,"tiff:has-layers","true"); DetachBlob(layers->blob); layers=GetNextImageInList(layers); } } custom_stream=DestroyCustomStreamInfo(custom_stream); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define ThrowTIFFException(severity,message) \ { \ if (tiff_pixels != (unsigned char *) NULL) \ tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); \ if (quantum_info != (QuantumInfo *) NULL) \ quantum_info=DestroyQuantumInfo(quantum_info); \ TIFFClose(tiff); \ ThrowReaderException(severity,message); \ } const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType more_frames, status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *tiff_pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } more_frames=MagickTrue; do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning photometric=PHOTOMETRIC_RGB; if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point", exception); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black", exception); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white", exception); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette",exception); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB",exception); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB",exception); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)", exception); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV",exception); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK",exception); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated",exception); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR",exception); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown",exception); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric", exception)); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb",exception); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb",exception); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace,exception); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace,exception); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace,exception); TIFFGetProfiles(tiff,image,exception); TIFFGetProperties(tiff,image,exception); option=GetImageOption(image_info,"tiff:exif-properties"); if (IsStringFalse(option) == MagickFalse) /* enabled by default */ TIFFGetEXIFProperties(tiff,image,exception); (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->resolution.x=x_resolution; image->resolution.y=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5); image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MagickPathExtent]; uint16 horizontal, vertical; tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal, &vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MagickPathExtent, "%dx%d",horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor,exception); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } quantum_info=(QuantumInfo *) NULL; if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors,exception) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } value=(unsigned short) image->scene; if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { TIFFClose(tiff); return(DestroyImageList(image)); } status=ResetImagePixels(image,exception); if (status == MagickFalse) { TIFFClose(tiff); return(DestroyImageList(image)); } /* Allocate memory for the image and pixel buffer. */ tiff_pixels=(unsigned char *) NULL; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified",exception); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->alpha_trait=BlendPixelTrait; } else for (i=0; i < extra_samples; i++) { image->alpha_trait=BlendPixelTrait; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated", exception); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated", exception); } } if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); method=ReadGenericMethod; rows_per_strip=(uint32) image->rows; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char buffer[MagickPathExtent]; method=ReadStripMethod; (void) FormatLocaleString(buffer,MagickPathExtent,"%u", (unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",buffer,exception); } if (rows_per_strip > (uint32) image->rows) rows_per_strip=(uint32) image->rows; if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG)) if ((image->alpha_trait == UndefinedPixelTrait) || (samples_per_pixel >= 4)) method=ReadRGBAMethod; if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE)) if ((image->alpha_trait == UndefinedPixelTrait) || (samples_per_pixel >= 5)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; if (TIFFScanlineSize(tiff) <= 0) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (((MagickSizeType) TIFFScanlineSize(tiff)) > GetBlobSize(image)) ThrowTIFFException(CorruptImageError,"InsufficientImageDataInFile"); number_pixels=MagickMax(TIFFScanlineSize(tiff),MagickMax((ssize_t) image->columns*samples_per_pixel*pow(2.0,ceil(log(bits_per_sample)/ log(2.0))),image->columns*rows_per_strip)*sizeof(uint32)); tiff_pixels=(unsigned char *) AcquireMagickMemory(number_pixels); if (tiff_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(tiff_pixels,0,number_pixels); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); if (image->alpha_trait != UndefinedPixelTrait) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; tiff_status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels); if (tiff_status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; tiff_status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels); if (tiff_status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; tiff_status=TIFFReadPixels(tiff,(tsample_t) i,y,(char *) tiff_pixels); if (tiff_status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; unsigned char *p; tiff_status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels); if (tiff_status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=tiff_pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456)),q); SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984)),q); SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816)),q); SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q); q+=GetPixelChannels(image); p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) tiff_pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) tiff_pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p))),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p))),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p))),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) ThrowTIFFException(CoderError,"ImageIsNotTiled"); if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) || (AcquireMagickResource(HeightResource,rows) == MagickFalse)) ThrowTIFFException(ImageError,"WidthOrHeightExceedsLimit"); (void) SetImageStorageClass(image,DirectClass,exception); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows* sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y+=rows) { register ssize_t x; register Quantum *magick_restrict q, *magick_restrict tile; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+ x); for (row=rows_remaining; row > 0; row--) { if (image->alpha_trait != UndefinedPixelTrait) for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p++; q+=GetPixelChannels(image); } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); p++; q+=GetPixelChannels(image); } p+=columns-columns_remaining; q-=GetPixelChannels(image)*(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; q+=GetPixelChannels(image)*(image->columns-1); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p--; q-=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (more_frames != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while ((status != MagickFalse) && (more_frames != MagickFalse)); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if ((image_info->number_scenes != 0) && (image_info->scene >= GetImageListLength(image))) status=MagickFalse; if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterTIFFImage() adds properties for the TIFF image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterTIFFImage method is: % % size_t RegisterTIFFImage(void) % */ #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) static TIFFExtendProc tag_extender = (TIFFExtendProc) NULL; static void TIFFIgnoreTags(TIFF *tiff) { char *q; const char *p, *tags; Image *image; register ssize_t i; size_t count; TIFFFieldInfo *ignore; if (TIFFGetReadProc(tiff) != TIFFReadBlob) return; image=(Image *)TIFFClientdata(tiff); tags=GetImageArtifact(image,"tiff:ignore-tags"); if (tags == (const char *) NULL) return; count=0; p=tags; while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; (void) strtol(p,&q,10); if (p == q) return; p=q; count++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (count == 0) return; i=0; p=tags; ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore)); if (ignore == (TIFFFieldInfo *) NULL) return; /* This also sets field_bit to 0 (FIELD_IGNORE) */ memset(ignore,0,count*sizeof(*ignore)); while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; ignore[i].field_tag=(ttag_t) strtol(p,&q,10); p=q; i++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } (void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count); ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore); } static void TIFFTagExtender(TIFF *tiff) { static const TIFFFieldInfo TIFFExtensions[] = { { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "PhotoshopLayerData" }, { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "Microscope" } }; TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/ sizeof(*TIFFExtensions)); if (tag_extender != (TIFFExtendProc) NULL) (*tag_extender)(tiff); TIFFIgnoreTags(tiff); } #endif ModuleExport size_t RegisterTIFFImage(void) { #define TIFFDescription "Tagged Image File Format" char version[MagickPathExtent]; MagickInfo *entry; if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key == MagickFalse) { if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); error_handler=TIFFSetErrorHandler(TIFFErrors); warning_handler=TIFFSetWarningHandler(TIFFWarnings); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) tag_extender=TIFFSetTagExtender(TIFFTagExtender); #endif instantiate_key=MagickTrue; } UnlockSemaphoreInfo(tiff_semaphore); *version='\0'; #if defined(TIFF_VERSION) (void) FormatLocaleString(version,MagickPathExtent,"%d",TIFF_VERSION); #endif #if defined(MAGICKCORE_TIFF_DELEGATE) { const char *p; register ssize_t i; p=TIFFGetVersion(); for (i=0; (i < (MagickPathExtent-1)) && (*p != 0) && (*p != '\n'); i++) version[i]=(*p++); version[i]='\0'; } #endif entry=AcquireMagickInfo("TIFF","GROUP4","Raw CCITT Group4"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadGROUP4Image; entry->encoder=(EncodeImageHandler *) WriteGROUP4Image; #endif entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderUseExtensionFlag; entry->format_type=ImplicitFormatType; entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","PTIF","Pyramid encoded TIFF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WritePTIFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags^=CoderUseExtensionFlag; entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIF",TIFFDescription); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags|=CoderStealthFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIFF",TIFFDescription); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->magick=(IsImageFormatHandler *) IsTIFF; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIFF64","Tagged Image File Format (64-bit)"); #if defined(TIFF_VERSION_BIG) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterTIFFImage() removes format registrations made by the TIFF module % from the list of supported formats. % % The format of the UnregisterTIFFImage method is: % % UnregisterTIFFImage(void) % */ ModuleExport void UnregisterTIFFImage(void) { (void) UnregisterMagickInfo("TIFF64"); (void) UnregisterMagickInfo("TIFF"); (void) UnregisterMagickInfo("TIF"); (void) UnregisterMagickInfo("PTIF"); if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key != MagickFalse) { #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) (void) TIFFSetTagExtender(tag_extender); #endif if (DeleteMagickThreadKey(tiff_exception) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); instantiate_key=MagickFalse; } UnlockSemaphoreInfo(tiff_semaphore); RelinquishSemaphoreInfo(&tiff_semaphore); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format. % % The format of the WriteGROUP4Image method is: % % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, % Image *image,ExceptionInfo *) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *huffman_image; ImageInfo *write_info; int unique_file; MagickBooleanType status; register ssize_t i; ssize_t count; TIFF *tiff; toff_t *byte_count, strip_size; unsigned char *buffer; /* Write image as CCITT Group4 TIFF image to a temporary file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); huffman_image=CloneImage(image,0,0,MagickTrue,exception); if (huffman_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } huffman_image->endian=MSBEndian; file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MagickPathExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType,exception); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageDepth(image,1,exception); (void) SetImageType(image,BilevelType,exception); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image,exception); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } tiff=TIFFOpen(filename,"rb"); if (tiff == (TIFF *) NULL) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError,"UnableToOpenFile", image_info->filename); return(MagickFalse); } /* Allocate raw strip buffer. */ if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } strip_size=byte_count[0]; for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) if (byte_count[i] > strip_size) strip_size=byte_count[i]; buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image_info->filename); } /* Compress runlength encoded to 2D Huffman pixels. */ for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) { count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size); if (WriteBlob(image,(size_t) count,buffer) != count) status=MagickFalse; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); (void) CloseBlob(image); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P T I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file % format. % % The format of the WritePTIFImage method is: % % MagickBooleanType WritePTIFImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePTIFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { Image *images, *next, *pyramid_image; ImageInfo *write_info; MagickBooleanType status; PointInfo resolution; size_t columns, rows; /* Create pyramid-encoded TIFF image. */ images=NewImageList(); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { Image *clone_image; clone_image=CloneImage(next,0,0,MagickFalse,exception); if (clone_image == (Image *) NULL) break; clone_image->previous=NewImageList(); clone_image->next=NewImageList(); (void) SetImageProperty(clone_image,"tiff:subfiletype","none",exception); AppendImageToList(&images,clone_image); columns=next->columns; rows=next->rows; resolution=next->resolution; while ((columns > 64) && (rows > 64)) { columns/=2; rows/=2; resolution.x/=2; resolution.y/=2; pyramid_image=ResizeImage(next,columns,rows,image->filter,exception); if (pyramid_image == (Image *) NULL) break; pyramid_image->resolution=resolution; (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE", exception); AppendImageToList(&images,pyramid_image); } } status=MagickFalse; if (images != (Image *) NULL) { /* Write pyramid-encoded TIFF image. */ images=GetFirstImageInList(images); write_info=CloneImageInfo(image_info); write_info->adjoin=MagickTrue; (void) CopyMagickString(write_info->magick,"TIFF",MagickPathExtent); (void) CopyMagickString(images->magick,"TIFF",MagickPathExtent); status=WriteTIFFImage(write_info,images,exception); images=DestroyImageList(images); write_info=DestroyImageInfo(write_info); } return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W r i t e T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteTIFFImage() writes an image in the Tagged image file format. % % The format of the WriteTIFFImage method is: % % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ typedef struct _TIFFInfo { RectangleInfo tile_geometry; unsigned char *scanline, *scanlines, *pixels; } TIFFInfo; static void DestroyTIFFInfo(TIFFInfo *tiff_info) { assert(tiff_info != (TIFFInfo *) NULL); if (tiff_info->scanlines != (unsigned char *) NULL) tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory( tiff_info->scanlines); if (tiff_info->pixels != (unsigned char *) NULL) tiff_info->pixels=(unsigned char *) RelinquishMagickMemory( tiff_info->pixels); } static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(image,q)-0.5; if (a < 0.0) a+=1.0; b=QuantumScale*GetPixelb(image,q)-0.5; if (b < 0.0) b+=1.0; SetPixela(image,QuantumRange*a,q); SetPixelb(image,QuantumRange*b,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) { status=MagickFalse; break; } } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info, TIFF *tiff,TIFFInfo *tiff_info) { const char *option; MagickStatusType flags; uint32 tile_columns, tile_rows; assert(tiff_info != (TIFFInfo *) NULL); (void) memset(tiff_info,0,sizeof(*tiff_info)); option=GetImageOption(image_info,"tiff:tile-geometry"); if (option == (const char *) NULL) { uint32 rows_per_strip; option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(size_t) strtol(option,(char **) NULL,10); else if (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows_per_strip) == 0) rows_per_strip=0; /* use default */ rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); return(MagickTrue); } /* Create tiled TIFF, ignore "tiff:rows-per-strip". */ flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry); if ((flags & HeightValue) == 0) tiff_info->tile_geometry.height=tiff_info->tile_geometry.width; tile_columns=(uint32) tiff_info->tile_geometry.width; tile_rows=(uint32) tiff_info->tile_geometry.height; TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows); (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns); (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows); tiff_info->tile_geometry.width=tile_columns; tiff_info->tile_geometry.height=tile_rows; if ((TIFFScanlineSize(tiff) <= 0) || (TIFFTileSize(tiff) <= 0)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines)); tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines)); if ((tiff_info->scanlines == (unsigned char *) NULL) || (tiff_info->pixels == (unsigned char *) NULL)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } return(MagickTrue); } static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row, tsample_t sample,Image *image) { int32 status; register ssize_t i; register unsigned char *p, *q; size_t number_tiles, tile_width; ssize_t bytes_per_pixel, j, k, l; if (TIFFIsTiled(tiff) == 0) return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample)); /* Fill scanlines to tile height. */ i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff); (void) memcpy(tiff_info->scanlines+i,(char *) tiff_info->scanline, (size_t) TIFFScanlineSize(tiff)); if (((size_t) (row % tiff_info->tile_geometry.height) != (tiff_info->tile_geometry.height-1)) && (row != (ssize_t) (image->rows-1))) return(0); /* Write tile to TIFF image. */ status=0; bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) ( tiff_info->tile_geometry.height*tiff_info->tile_geometry.width); number_tiles=(image->columns+tiff_info->tile_geometry.width)/ tiff_info->tile_geometry.width; for (i=0; i < (ssize_t) number_tiles; i++) { tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i* tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width; for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++) for (k=0; k < (ssize_t) tile_width; k++) { if (bytes_per_pixel == 0) { p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)/8); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8); *q++=(*p++); continue; } p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)*bytes_per_pixel); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel); for (l=0; l < bytes_per_pixel; l++) *q++=(*p++); } if ((i*tiff_info->tile_geometry.width) != image->columns) status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i* tiff_info->tile_geometry.width),(uint32) ((row/ tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0, sample); if (status < 0) break; } return(status); } static ssize_t TIFFWriteCustomStream(unsigned char *data,const size_t count, void *user_data) { PhotoshopProfile *profile; if (count == 0) return(0); profile=(PhotoshopProfile *) user_data; if ((profile->offset+(MagickOffsetType) count) >= (MagickOffsetType) profile->extent) { profile->extent+=count+profile->quantum; profile->quantum<<=1; SetStringInfoLength(profile->data,profile->extent); } (void) memcpy(profile->data->datum+profile->offset,data,count); profile->offset+=count; return(count); } static CustomStreamInfo *TIFFAcquireCustomStreamForWriting( PhotoshopProfile *profile,ExceptionInfo *exception) { CustomStreamInfo *custom_stream; custom_stream=AcquireCustomStreamInfo(exception); if (custom_stream == (CustomStreamInfo *) NULL) return(custom_stream); SetCustomStreamData(custom_stream,(void *) profile); SetCustomStreamWriter(custom_stream,TIFFWriteCustomStream); SetCustomStreamSeeker(custom_stream,TIFFSeekCustomStream); SetCustomStreamTeller(custom_stream,TIFFTellCustomStream); return(custom_stream); } static MagickBooleanType TIFFWritePhotoshopLayers(Image* image, const ImageInfo *image_info,EndianType endian,ExceptionInfo *exception) { BlobInfo *blob; CustomStreamInfo *custom_stream; Image *base_image, *next; ImageInfo *clone_info; MagickBooleanType status; PhotoshopProfile profile; PSDInfo info; StringInfo *layers; base_image=CloneImage(image,0,0,MagickFalse,exception); if (base_image == (Image *) NULL) return(MagickTrue); clone_info=CloneImageInfo(image_info); if (clone_info == (ImageInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); profile.offset=0; profile.quantum=MagickMinBlobExtent; layers=AcquireStringInfo(profile.quantum); if (layers == (StringInfo *) NULL) { base_image=DestroyImage(base_image); clone_info=DestroyImageInfo(clone_info); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } profile.data=layers; profile.extent=layers->length; custom_stream=TIFFAcquireCustomStreamForWriting(&profile,exception); if (custom_stream == (CustomStreamInfo *) NULL) { base_image=DestroyImage(base_image); clone_info=DestroyImageInfo(clone_info); layers=DestroyStringInfo(layers); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } blob=CloneBlobInfo((BlobInfo *) NULL); if (blob == (BlobInfo *) NULL) { base_image=DestroyImage(base_image); clone_info=DestroyImageInfo(clone_info); layers=DestroyStringInfo(layers); custom_stream=DestroyCustomStreamInfo(custom_stream); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } DestroyBlob(base_image); base_image->blob=blob; next=base_image; while (next != (Image *) NULL) next=SyncNextImageInList(next); AttachCustomStream(base_image->blob,custom_stream); InitPSDInfo(image,&info); base_image->endian=endian; WriteBlobString(base_image,"Adobe Photoshop Document Data Block"); WriteBlobByte(base_image,0); WriteBlobString(base_image,base_image->endian == LSBEndian ? "MIB8ryaL" : "8BIMLayr"); status=WritePSDLayers(base_image,clone_info,&info,exception); if (status != MagickFalse) { SetStringInfoLength(layers,(size_t) profile.offset); status=SetImageProfile(image,"tiff:37724",layers,exception); } next=base_image; while (next != (Image *) NULL) { CloseBlob(next); next=next->next; } layers=DestroyStringInfo(layers); clone_info=DestroyImageInfo(clone_info); custom_stream=DestroyCustomStreamInfo(custom_stream); return(status); } static void TIFFSetProfiles(TIFF *tiff,Image *image) { const char *name; const StringInfo *profile; if (image->profiles == (void *) NULL) return; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (GetStringInfoLength(profile) == 0) { name=GetNextImageProfile(image); continue; } #if defined(TIFFTAG_XMLPACKET) if (LocaleCompare(name,"xmp") == 0) (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif #if defined(TIFFTAG_ICCPROFILE) if (LocaleCompare(name,"icc") == 0) (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"iptc") == 0) { size_t length; StringInfo *iptc_profile; iptc_profile=CloneStringInfo(profile); length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) & 0x03); SetStringInfoLength(iptc_profile,length); if (TIFFIsByteSwapped(tiff)) TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile), (unsigned long) (length/4)); (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32) GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile)); iptc_profile=DestroyStringInfo(iptc_profile); } #if defined(TIFFTAG_PHOTOSHOP) if (LocaleCompare(name,"8bim") == 0) (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32) GetStringInfoLength(profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"tiff:37724") == 0) (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); if (LocaleCompare(name,"tiff:34118") == 0) (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); name=GetNextImageProfile(image); } } static void TIFFSetProperties(TIFF *tiff,const MagickBooleanType adjoin, Image *image,ExceptionInfo *exception) { const char *value; value=GetImageArtifact(image,"tiff:document"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value); value=GetImageArtifact(image,"tiff:hostcomputer"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value); value=GetImageArtifact(image,"tiff:artist"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value); value=GetImageArtifact(image,"tiff:timestamp"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value); value=GetImageArtifact(image,"tiff:make"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MAKE,value); value=GetImageArtifact(image,"tiff:model"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MODEL,value); value=GetImageArtifact(image,"tiff:software"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value); value=GetImageArtifact(image,"tiff:copyright"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value); value=GetImageArtifact(image,"kodak-33423"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,33423,value); value=GetImageArtifact(image,"kodak-36867"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,36867,value); value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value); value=GetImageArtifact(image,"tiff:subfiletype"); if (value != (const char *) NULL) { if (LocaleCompare(value,"REDUCEDIMAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); else if (LocaleCompare(value,"PAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); else if (LocaleCompare(value,"MASK") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK); } else { uint16 page, pages; page=(uint16) image->scene; pages=(uint16) GetImageListLength(image); if ((adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } } static void TIFFSetEXIFProperties(TIFF *tiff,Image *image, ExceptionInfo *exception) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) const char *value; register ssize_t i; uint32 offset; /* Write EXIF properties. */ offset=0; (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset); for (i=0; exif_info[i].tag != 0; i++) { value=GetImageProperty(image,exif_info[i].property,exception); if (value == (const char *) NULL) continue; switch (exif_info[i].type) { case TIFF_ASCII: { (void) TIFFSetField(tiff,exif_info[i].tag,value); break; } case TIFF_SHORT: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_LONG: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_RATIONAL: case TIFF_SRATIONAL: { float field; field=StringToDouble(value,(char **) NULL); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } default: break; } } /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */ #else (void) tiff; (void) image; #endif } static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType adjoin, debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t imageListLength, length; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric, predictor; unsigned char *pixels; /* Open TIFF file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) SetMagickThreadValue(tiff_exception,exception); endian_type=(HOST_FILLORDER == FILLORDER_LSB2MSB) ? LSBEndian : MSBEndian; option=GetImageOption(image_info,"tiff:endian"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,"lsb",3) == 0) endian_type=LSBEndian; } mode=endian_type == LSBEndian ? "wl" : "wb"; #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) mode=endian_type == LSBEndian ? "wl8" : "wb8"; #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); scene=0; debug=IsEventLogging(); (void) debug; adjoin=image_info->adjoin; imageListLength=GetImageListLength(image); do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type,exception); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType,exception); (void) SetImageDepth(image,1,exception); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { quantum_info=DestroyQuantumInfo(quantum_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } } if ((LocaleCompare(image_info->magick,"PTIF") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->alpha_trait == UndefinedPixelTrait)) SetImageMonochrome(image,exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } else if ((compress_tag == COMPRESSION_CCITTFAX4) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } option=GetImageOption(image_info,"tiff:fill-order"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,"lsb",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->alpha_trait != UndefinedPixelTrait) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,"tiff:alpha"); if (option != (const char *) NULL) { if (LocaleCompare(option,"associated") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,"unspecified") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); predictor=0; switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); if (image->colorspace == YCbCrColorspace) { const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor",exception); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: break; #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; break; } default: break; } option=GetImageOption(image_info,"tiff:predictor"); if (option != (const char * ) NULL) predictor=(size_t) strtol(option,(char **) NULL,10); if (predictor != 0) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor); if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "TIFF: negative image positions unsupported","%s",image->filename); if ((image->page.x > 0) && (image->resolution.x > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->resolution.x); } if ((image->page.y > 0) && (image->resolution.y > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->resolution.y); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } option=GetImageOption(image_info,"tiff:write-layers"); if (IsStringTrue(option) != MagickFalse) { (void) TIFFWritePhotoshopLayers(image,image_info,endian_type,exception); adjoin=MagickFalse; } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (adjoin != MagickFalse) && (imageListLength > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, imageListLength); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) imageListLength; if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,adjoin,image,exception); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image,exception); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=(unsigned char *) GetQuantumPixels(quantum_info); tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) length; if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->alpha_trait != UndefinedPixelTrait) for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) { if (red != (uint16 *) NULL) red=(uint16 *) RelinquishMagickMemory(red); if (green != (uint16 *) NULL) green=(uint16 *) RelinquishMagickMemory(green); if (blue != (uint16 *) NULL) blue=(uint16 *) RelinquishMagickMemory(blue); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialize TIFF colormap. */ (void) memset(red,0,65536*sizeof(*red)); (void) memset(green,0,65536*sizeof(*green)); (void) memset(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->alpha_trait != UndefinedPixelTrait) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,exception); DestroyTIFFInfo(&tiff_info); DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-772/c/good_362_0
crossvul-cpp_data_bad_2618_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP AAA L M M % % P P A A L MM MM % % PPPP AAAAA L M M M % % P A A L M M % % P A A LLLLL M M % % % % % % Read/Write Palm Pixmap. % % % % % % Software Design % % Christopher R. Hawks % % December 2001 % % % % Copyright 1999-2004 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Based on pnmtopalm by Bill Janssen and ppmtobmp by Ian Goldberg. % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/exception.h" #include "magick/histogram.h" #include "magick/image.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/paint.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/utility.h" /* Define declarations. */ #define PALM_IS_COMPRESSED_FLAG 0x8000 #define PALM_HAS_COLORMAP_FLAG 0x4000 #define PALM_HAS_FOUR_BYTE_FIELD 0x0200 #define PALM_HAS_TRANSPARENCY_FLAG 0x2000 #define PALM_IS_INDIRECT 0x1000 #define PALM_IS_FOR_SCREEN 0x0800 #define PALM_IS_DIRECT_COLOR 0x0400 #define PALM_COMPRESSION_SCANLINE 0x00 #define PALM_COMPRESSION_RLE 0x01 #define PALM_COMPRESSION_NONE 0xFF /* The 256 color system palette for Palm Computing Devices. */ static const unsigned char PalmPalette[256][3] = { {255, 255,255}, {255, 204,255}, {255, 153,255}, {255, 102,255}, {255, 51,255}, {255, 0,255}, {255, 255,204}, {255, 204,204}, {255, 153,204}, {255, 102,204}, {255, 51,204}, {255, 0,204}, {255, 255,153}, {255, 204,153}, {255, 153,153}, {255, 102,153}, {255, 51,153}, {255, 0,153}, {204, 255,255}, {204, 204,255}, {204, 153,255}, {204, 102,255}, {204, 51,255}, {204, 0,255}, {204, 255,204}, {204, 204,204}, {204, 153,204}, {204, 102,204}, {204, 51,204}, {204, 0,204}, {204, 255,153}, {204, 204,153}, {204, 153,153}, {204, 102,153}, {204, 51,153}, {204, 0,153}, {153, 255,255}, {153, 204,255}, {153, 153,255}, {153, 102,255}, {153, 51,255}, {153, 0,255}, {153, 255,204}, {153, 204,204}, {153, 153,204}, {153, 102,204}, {153, 51,204}, {153, 0,204}, {153, 255,153}, {153, 204,153}, {153, 153,153}, {153, 102,153}, {153, 51,153}, {153, 0,153}, {102, 255,255}, {102, 204,255}, {102, 153,255}, {102, 102,255}, {102, 51,255}, {102, 0,255}, {102, 255,204}, {102, 204,204}, {102, 153,204}, {102, 102,204}, {102, 51,204}, {102, 0,204}, {102, 255,153}, {102, 204,153}, {102, 153,153}, {102, 102,153}, {102, 51,153}, {102, 0,153}, { 51, 255,255}, { 51, 204,255}, { 51, 153,255}, { 51, 102,255}, { 51, 51,255}, { 51, 0,255}, { 51, 255,204}, { 51, 204,204}, { 51, 153,204}, { 51, 102,204}, { 51, 51,204}, { 51, 0,204}, { 51, 255,153}, { 51, 204,153}, { 51, 153,153}, { 51, 102,153}, { 51, 51,153}, { 51, 0,153}, { 0, 255,255}, { 0, 204,255}, { 0, 153,255}, { 0, 102,255}, { 0, 51,255}, { 0, 0,255}, { 0, 255,204}, { 0, 204,204}, { 0, 153,204}, { 0, 102,204}, { 0, 51,204}, { 0, 0,204}, { 0, 255,153}, { 0, 204,153}, { 0, 153,153}, { 0, 102,153}, { 0, 51,153}, { 0, 0,153}, {255, 255,102}, {255, 204,102}, {255, 153,102}, {255, 102,102}, {255, 51,102}, {255, 0,102}, {255, 255, 51}, {255, 204, 51}, {255, 153, 51}, {255, 102, 51}, {255, 51, 51}, {255, 0, 51}, {255, 255, 0}, {255, 204, 0}, {255, 153, 0}, {255, 102, 0}, {255, 51, 0}, {255, 0, 0}, {204, 255,102}, {204, 204,102}, {204, 153,102}, {204, 102,102}, {204, 51,102}, {204, 0,102}, {204, 255, 51}, {204, 204, 51}, {204, 153, 51}, {204, 102, 51}, {204, 51, 51}, {204, 0, 51}, {204, 255, 0}, {204, 204, 0}, {204, 153, 0}, {204, 102, 0}, {204, 51, 0}, {204, 0, 0}, {153, 255,102}, {153, 204,102}, {153, 153,102}, {153, 102,102}, {153, 51,102}, {153, 0,102}, {153, 255, 51}, {153, 204, 51}, {153, 153, 51}, {153, 102, 51}, {153, 51, 51}, {153, 0, 51}, {153, 255, 0}, {153, 204, 0}, {153, 153, 0}, {153, 102, 0}, {153, 51, 0}, {153, 0, 0}, {102, 255,102}, {102, 204,102}, {102, 153,102}, {102, 102,102}, {102, 51,102}, {102, 0,102}, {102, 255, 51}, {102, 204, 51}, {102, 153, 51}, {102, 102, 51}, {102, 51, 51}, {102, 0, 51}, {102, 255, 0}, {102, 204, 0}, {102, 153, 0}, {102, 102, 0}, {102, 51, 0}, {102, 0, 0}, { 51, 255,102}, { 51, 204,102}, { 51, 153,102}, { 51, 102,102}, { 51, 51,102}, { 51, 0,102}, { 51, 255, 51}, { 51, 204, 51}, { 51, 153, 51}, { 51, 102, 51}, { 51, 51, 51}, { 51, 0, 51}, { 51, 255, 0}, { 51, 204, 0}, { 51, 153, 0}, { 51, 102, 0}, { 51, 51, 0}, { 51, 0, 0}, { 0, 255,102}, { 0, 204,102}, { 0, 153,102}, { 0, 102,102}, { 0, 51,102}, { 0, 0,102}, { 0, 255, 51}, { 0, 204, 51}, { 0, 153, 51}, { 0, 102, 51}, { 0, 51, 51}, { 0, 0, 51}, { 0, 255, 0}, { 0, 204, 0}, { 0, 153, 0}, { 0, 102, 0}, { 0, 51, 0}, { 17, 17, 17}, { 34, 34, 34}, { 68, 68, 68}, { 85, 85, 85}, {119, 119,119}, {136, 136,136}, {170, 170,170}, {187, 187,187}, {221, 221,221}, {238, 238,238}, {192, 192,192}, {128, 0, 0}, {128, 0,128}, { 0, 128, 0}, { 0, 128,128}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0} }; /* Forward declarations. */ static MagickBooleanType WritePALMImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F i n d C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FindColor() returns the index of the matching entry from PalmPalette for a % given PixelPacket. % % The format of the FindColor method is: % % int FindColor(PixelPacket *pixel) % % A description of each parameter follows: % % o int: the index of the matching color or -1 if not found/ % % o pixel: a pointer to the PixelPacket to be matched. % */ static ssize_t FindColor(PixelPacket *pixel) { register ssize_t i; for (i=0; i < 256; i++) if (ScaleQuantumToChar(GetPixelRed(pixel)) == PalmPalette[i][0] && ScaleQuantumToChar(GetPixelGreen(pixel)) == PalmPalette[i][1] && ScaleQuantumToChar(GetPixelBlue(pixel)) == PalmPalette[i][2]) return(i); return(-1); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P A L M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPALMImage() reads an image of raw bites in LSB order and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPALMImage method is: % % Image *ReadPALMImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Specifies a pointer to an ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadPALMImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; IndexPacket index; MagickBooleanType status; MagickOffsetType totalOffset, seekNextDepth; MagickPixelPacket transpix; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; size_t bytes_per_row, flags, bits_per_pixel, version, nextDepthOffset, transparentIndex, compressionType, byte, mask, redbits, greenbits, bluebits, one, pad, size, bit; ssize_t count, y; unsigned char *lastrow, *one_row, *ptr; unsigned short color16; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { (void) DestroyImageList(image); return((Image *) NULL); } totalOffset=0; do { image->columns=ReadBlobMSBShort(image); image->rows=ReadBlobMSBShort(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } bytes_per_row=ReadBlobMSBShort(image); flags=ReadBlobMSBShort(image); bits_per_pixel=(size_t) ReadBlobByte(image); if ((bits_per_pixel != 1) && (bits_per_pixel != 2) && (bits_per_pixel != 4) && (bits_per_pixel != 8) && (bits_per_pixel != 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); version=(size_t) ReadBlobByte(image); if ((version != 0) && (version != 1) && (version != 2)) ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch"); nextDepthOffset=(size_t) ReadBlobMSBShort(image); transparentIndex=(size_t) ReadBlobByte(image); compressionType=(size_t) ReadBlobByte(image); if ((compressionType != PALM_COMPRESSION_NONE) && (compressionType != PALM_COMPRESSION_SCANLINE ) && (compressionType != PALM_COMPRESSION_RLE)) ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); pad=ReadBlobMSBShort(image); (void) pad; /* Initialize image colormap. */ one=1; if ((bits_per_pixel < 16) && (AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetMagickPixelPacket(image,&transpix); if (bits_per_pixel == 16) /* Direct Color */ { redbits=(size_t) ReadBlobByte(image); /* # of bits of red */ (void) redbits; greenbits=(size_t) ReadBlobByte(image); /* # of bits of green */ (void) greenbits; bluebits=(size_t) ReadBlobByte(image); /* # of bits of blue */ (void) bluebits; ReadBlobByte(image); /* reserved by Palm */ ReadBlobByte(image); /* reserved by Palm */ transpix.red=(MagickRealType) (QuantumRange*ReadBlobByte(image)/31); transpix.green=(MagickRealType) (QuantumRange*ReadBlobByte(image)/63); transpix.blue=(MagickRealType) (QuantumRange*ReadBlobByte(image)/31); } if (bits_per_pixel == 8) { IndexPacket index; if (flags & PALM_HAS_COLORMAP_FLAG) { count=(ssize_t) ReadBlobMSBShort(image); for (i=0; i < (ssize_t) count; i++) { ReadBlobByte(image); index=ConstrainColormapIndex(image,(size_t) (255-i)); image->colormap[(int) index].red=ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); image->colormap[(int) index].green=ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); image->colormap[(int) index].blue=ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); } } else for (i=0; i < (ssize_t) (1L << bits_per_pixel); i++) { index=ConstrainColormapIndex(image,(size_t) (255-i)); image->colormap[(int) index].red=ScaleCharToQuantum( PalmPalette[i][0]); image->colormap[(int) index].green=ScaleCharToQuantum( PalmPalette[i][1]); image->colormap[(int) index].blue=ScaleCharToQuantum( PalmPalette[i][2]); } } if (flags & PALM_IS_COMPRESSED_FLAG) size=ReadBlobMSBShort(image); (void) size; image->storage_class=DirectClass; if (bits_per_pixel < 16) { image->storage_class=PseudoClass; image->depth=8; } if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } one_row=(unsigned char *) AcquireQuantumMemory(MagickMax(bytes_per_row, 2*image->columns),sizeof(*one_row)); if (one_row == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); lastrow=(unsigned char *) NULL; if (compressionType == PALM_COMPRESSION_SCANLINE) { lastrow=(unsigned char *) AcquireQuantumMemory(MagickMax(bytes_per_row, 2*image->columns),sizeof(*lastrow)); if (lastrow == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } mask=(size_t) (1U << bits_per_pixel)-1; for (y=0; y < (ssize_t) image->rows; y++) { if ((flags & PALM_IS_COMPRESSED_FLAG) == 0) { /* TODO move out of loop! */ image->compression=NoCompression; count=ReadBlob(image,bytes_per_row,one_row); if (count != (ssize_t) bytes_per_row) break; } else { if (compressionType == PALM_COMPRESSION_RLE) { /* TODO move out of loop! */ image->compression=RLECompression; for (i=0; i < (ssize_t) bytes_per_row; ) { count=(ssize_t) ReadBlobByte(image); if (count < 0) break; count=MagickMin(count,(ssize_t) bytes_per_row-i); byte=(size_t) ReadBlobByte(image); (void) ResetMagickMemory(one_row+i,(int) byte,(size_t) count); i+=count; } } else if (compressionType == PALM_COMPRESSION_SCANLINE) { size_t one; /* TODO move out of loop! */ one=1; image->compression=FaxCompression; for (i=0; i < (ssize_t) bytes_per_row; i+=8) { count=(ssize_t) ReadBlobByte(image); if (count < 0) break; byte=(size_t) MagickMin((ssize_t) bytes_per_row-i,8); for (bit=0; bit < byte; bit++) { if ((y == 0) || (count & (one << (7 - bit)))) one_row[i+bit]=(unsigned char) ReadBlobByte(image); else one_row[i+bit]=lastrow[i+bit]; } } (void) CopyMagickMemory(lastrow, one_row, bytes_per_row); } } ptr=one_row; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); if (bits_per_pixel == 16) { if (image->columns > (2*bytes_per_row)) { one_row=(unsigned char *) RelinquishMagickMemory(one_row); if (compressionType == PALM_COMPRESSION_SCANLINE) lastrow=(unsigned char *) RelinquishMagickMemory(lastrow); ThrowReaderException(CorruptImageError,"CorruptImage"); } for (x=0; x < (ssize_t) image->columns; x++) { color16=(*ptr++ << 8); color16|=(*ptr++); SetPixelRed(q,(QuantumRange*((color16 >> 11) & 0x1f))/0x1f); SetPixelGreen(q,(QuantumRange*((color16 >> 5) & 0x3f))/0x3f); SetPixelBlue(q,(QuantumRange*((color16 >> 0) & 0x1f))/0x1f); SetPixelOpacity(q,OpaqueOpacity); q++; } } else { bit=8-bits_per_pixel; for (x=0; x < (ssize_t) image->columns; x++) { if ((size_t) (ptr-one_row) >= bytes_per_row) { one_row=(unsigned char *) RelinquishMagickMemory(one_row); if (compressionType == PALM_COMPRESSION_SCANLINE) lastrow=(unsigned char *) RelinquishMagickMemory(lastrow); ThrowReaderException(CorruptImageError,"CorruptImage"); } index=(IndexPacket) (mask-(((*ptr) & (mask << bit)) >> bit)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); if (bit) bit-=bits_per_pixel; else { ptr++; bit=8-bits_per_pixel; } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (flags & PALM_HAS_TRANSPARENCY_FLAG) { IndexPacket index=ConstrainColormapIndex(image,(mask-transparentIndex)); if (bits_per_pixel != 16) SetMagickPixelPacket(image,image->colormap+(ssize_t) index, (const IndexPacket *) NULL,&transpix); (void) TransparentPaintImage(image,&transpix,(Quantum) TransparentOpacity,MagickFalse); } one_row=(unsigned char *) RelinquishMagickMemory(one_row); if (compressionType == PALM_COMPRESSION_SCANLINE) lastrow=(unsigned char *) RelinquishMagickMemory(lastrow); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. Copied from coders/pnm.c */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (nextDepthOffset != 0) { /* Skip to next image. */ totalOffset+=(MagickOffsetType) (nextDepthOffset*4); if (totalOffset >= (MagickOffsetType) GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader") else seekNextDepth=SeekBlob(image,totalOffset,SEEK_SET); if (seekNextDepth != totalOffset) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Allocate next image structure. Copied from coders/pnm.c */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { (void) DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (nextDepthOffset != 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P A L M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPALMImage() adds properties for the PALM image format to the list of % supported formats. The properties include the image format tag, a method to % read and/or write the format, whether the format supports the saving of more % than one frame to the same file or blob, whether the format supports native % in-memory I/O, and a brief description of the format. % % The format of the RegisterPALMImage method is: % % size_t RegisterPALMImage(void) % */ ModuleExport size_t RegisterPALMImage(void) { MagickInfo *entry; entry=SetMagickInfo("PALM"); entry->decoder=(DecodeImageHandler *) ReadPALMImage; entry->encoder=(EncodeImageHandler *) WritePALMImage; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Palm pixmap"); entry->module=ConstantString("PALM"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P A L M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPALMImage() removes format registrations made by the PALM % module from the list of supported formats. % % The format of the UnregisterPALMImage method is: % % UnregisterPALMImage(void) % */ ModuleExport void UnregisterPALMImage(void) { (void) UnregisterMagickInfo("PALM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P A L M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePALMImage() writes an image of raw bits in LSB order to a file. % % The format of the WritePALMImage method is: % % MagickBooleanType WritePALMImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows. % % o image_info: Specifies a pointer to an ImageInfo structure. % % o image: A pointer to a Image structure. % */ static MagickBooleanType WritePALMImage(const ImageInfo *image_info, Image *image) { ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType currentOffset, offset, scene; MagickSizeType cc; PixelPacket transpix; QuantizeInfo *quantize_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *p; ssize_t y; size_t count, bits_per_pixel, bytes_per_row, nextDepthOffset, one; unsigned char bit, byte, color, *lastrow, *one_row, *ptr, version; unsigned int transparentIndex; unsigned short color16, flags; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=AcquireExceptionInfo(); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); quantize_info=AcquireQuantizeInfo(image_info); flags=0; currentOffset=0; transparentIndex=0; transpix.red=0; transpix.green=0; transpix.blue=0; transpix.opacity=0; one=1; version=0; scene=0; do { (void) TransformImageColorspace(image,sRGBColorspace); count=GetNumberColors(image,NULL,exception); for (bits_per_pixel=1; (one << bits_per_pixel) < count; bits_per_pixel*=2) ; if (bits_per_pixel > 16) bits_per_pixel=16; else if (bits_per_pixel < 16) (void) TransformImageColorspace(image,image->colorspace); if (bits_per_pixel < 8) { (void) TransformImageColorspace(image,GRAYColorspace); (void) SetImageType(image,PaletteType); (void) SortColormapByIntensity(image); } if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageStorageClass(image,DirectClass); if (image->storage_class == PseudoClass) flags|=PALM_HAS_COLORMAP_FLAG; else flags|=PALM_IS_DIRECT_COLOR; (void) WriteBlobMSBShort(image,(unsigned short) image->columns); /* width */ (void) WriteBlobMSBShort(image,(unsigned short) image->rows); /* height */ bytes_per_row=((image->columns+(16/bits_per_pixel-1))/(16/ bits_per_pixel))*2; (void) WriteBlobMSBShort(image,(unsigned short) bytes_per_row); if ((image_info->compression == RLECompression) || (image_info->compression == FaxCompression)) flags|=PALM_IS_COMPRESSED_FLAG; (void) WriteBlobMSBShort(image, flags); (void) WriteBlobByte(image,(unsigned char) bits_per_pixel); if (bits_per_pixel > 1) version=1; if ((image_info->compression == RLECompression) || (image_info->compression == FaxCompression)) version=2; (void) WriteBlobByte(image,version); (void) WriteBlobMSBShort(image,0); /* nextDepthOffset */ (void) WriteBlobByte(image,(unsigned char) transparentIndex); if (image_info->compression == RLECompression) (void) WriteBlobByte(image,PALM_COMPRESSION_RLE); else if (image_info->compression == FaxCompression) (void) WriteBlobByte(image,PALM_COMPRESSION_SCANLINE); else (void) WriteBlobByte(image,PALM_COMPRESSION_NONE); (void) WriteBlobMSBShort(image,0); /* reserved */ offset=16; if (bits_per_pixel == 16) { (void) WriteBlobByte(image,5); /* # of bits of red */ (void) WriteBlobByte(image,6); /* # of bits of green */ (void) WriteBlobByte(image,5); /* # of bits of blue */ (void) WriteBlobByte(image,0); /* reserved by Palm */ (void) WriteBlobMSBLong(image,0); /* no transparent color, YET */ offset+=8; } if (bits_per_pixel == 8) { if (flags & PALM_HAS_COLORMAP_FLAG) /* Write out colormap */ { quantize_info->dither=IsPaletteImage(image,&image->exception); quantize_info->number_colors=image->colors; (void) QuantizeImage(quantize_info,image); (void) WriteBlobMSBShort(image,(unsigned short) image->colors); for (count = 0; count < image->colors; count++) { (void) WriteBlobByte(image,(unsigned char) count); (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[count].red)); (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[count].green)); (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[count].blue)); } offset+=2+count*4; } else /* Map colors to Palm standard colormap */ { Image *affinity_image; affinity_image=ConstituteImage(256,1,"RGB",CharPixel,&PalmPalette, exception); (void) TransformImageColorspace(affinity_image, affinity_image->colorspace); (void) RemapImage(quantize_info,image,affinity_image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetAuthenticPixels(image,0,y,image->columns,1,exception); indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,FindColor(&image->colormap[ (ssize_t) GetPixelIndex(indexes+x)])); } affinity_image=DestroyImage(affinity_image); } } if (flags & PALM_IS_COMPRESSED_FLAG) (void) WriteBlobMSBShort(image,0); /* fill in size later */ lastrow=(unsigned char *) NULL; if (image_info->compression == FaxCompression) lastrow=(unsigned char *) AcquireQuantumMemory(bytes_per_row, sizeof(*lastrow)); /* TODO check whether memory really was acquired? */ one_row=(unsigned char *) AcquireQuantumMemory(bytes_per_row, sizeof(*one_row)); if (one_row == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { ptr=one_row; (void) ResetMagickMemory(ptr,0,bytes_per_row); p=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (p == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); if (bits_per_pixel == 16) { for (x=0; x < (ssize_t) image->columns; x++) { color16=(unsigned short) ((((31*(size_t) GetPixelRed(p))/ (size_t) QuantumRange) << 11) | (((63*(size_t) GetPixelGreen(p))/(size_t) QuantumRange) << 5) | ((31*(size_t) GetPixelBlue(p))/(size_t) QuantumRange)); if (GetPixelOpacity(p) == (Quantum) TransparentOpacity) { transpix.red=GetPixelRed(p); transpix.green=GetPixelGreen(p); transpix.blue=GetPixelBlue(p); transpix.opacity=GetPixelOpacity(p); flags|=PALM_HAS_TRANSPARENCY_FLAG; } *ptr++=(unsigned char) ((color16 >> 8) & 0xff); *ptr++=(unsigned char) (color16 & 0xff); p++; } } else { byte=0x00; bit=(unsigned char) (8-bits_per_pixel); for (x=0; x < (ssize_t) image->columns; x++) { if (bits_per_pixel >= 8) color=(unsigned char) GetPixelIndex(indexes+x); else color=(unsigned char) (GetPixelIndex(indexes+x)* ((one << bits_per_pixel)-1)/MagickMax(1*image->colors-1,1)); byte|=color << bit; if (bit != 0) bit-=(unsigned char) bits_per_pixel; else { *ptr++=byte; byte=0x00; bit=(unsigned char) (8-bits_per_pixel); } } if ((image->columns % (8/bits_per_pixel)) != 0) *ptr++=byte; } if (image_info->compression == RLECompression) { x=0; while (x < (ssize_t) bytes_per_row) { byte=one_row[x]; count=1; while ((one_row[++x] == byte) && (count < 255) && (x < (ssize_t) bytes_per_row)) count++; (void) WriteBlobByte(image,(unsigned char) count); (void) WriteBlobByte(image,(unsigned char) byte); } } else if (image_info->compression == FaxCompression) { char tmpbuf[8], *tptr; for (x = 0; x < (ssize_t) bytes_per_row; x += 8) { tptr = tmpbuf; for (bit=0, byte=0; bit < (unsigned char) MagickMin(8,(ssize_t) bytes_per_row-x); bit++) { if ((y == 0) || (lastrow[x + bit] != one_row[x + bit])) { byte |= (1 << (7 - bit)); *tptr++ = (char) one_row[x + bit]; } } (void) WriteBlobByte(image, byte); (void) WriteBlob(image,tptr-tmpbuf,(unsigned char *) tmpbuf); } (void) CopyMagickMemory(lastrow,one_row,bytes_per_row); } else (void) WriteBlob(image,bytes_per_row,one_row); } if (flags & PALM_HAS_TRANSPARENCY_FLAG) { offset=SeekBlob(image,currentOffset+6,SEEK_SET); (void) WriteBlobMSBShort(image,flags); offset=SeekBlob(image,currentOffset+12,SEEK_SET); (void) WriteBlobByte(image,(unsigned char) transparentIndex); /* trans index */ } if (bits_per_pixel == 16) { offset=SeekBlob(image,currentOffset+20,SEEK_SET); (void) WriteBlobByte(image,0); /* reserved by Palm */ (void) WriteBlobByte(image,(unsigned char) ((31*transpix.red)/QuantumRange)); (void) WriteBlobByte(image,(unsigned char) ((63*transpix.green)/QuantumRange)); (void) WriteBlobByte(image,(unsigned char) ((31*transpix.blue)/QuantumRange)); } if (flags & PALM_IS_COMPRESSED_FLAG) /* fill in size now */ { offset=SeekBlob(image,currentOffset+offset,SEEK_SET); (void) WriteBlobMSBShort(image,(unsigned short) (GetBlobSize(image)- currentOffset-offset)); } if (one_row != (unsigned char *) NULL) one_row=(unsigned char *) RelinquishMagickMemory(one_row); if (lastrow != (unsigned char *) NULL) lastrow=(unsigned char *) RelinquishMagickMemory(lastrow); if (GetNextImageInList(image) == (Image *) NULL) break; /* padding to 4 byte word */ for (cc=(GetBlobSize(image)) % 4; cc > 0; cc--) (void) WriteBlobByte(image,0); /* write nextDepthOffset and return to end of image */ (void) SeekBlob(image,currentOffset+10,SEEK_SET); nextDepthOffset=(size_t) ((GetBlobSize(image)-currentOffset)/4); (void) WriteBlobMSBShort(image,(unsigned short) nextDepthOffset); currentOffset=(MagickOffsetType) GetBlobSize(image); (void) SeekBlob(image,currentOffset,SEEK_SET); image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); quantize_info=DestroyQuantizeInfo(quantize_info); (void) CloseBlob(image); (void) DestroyExceptionInfo(exception); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2618_0
crossvul-cpp_data_good_3103_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M PPPP CCCC % % MM MM P P C % % M M M PPPP C % % M M P C % % M M P CCCC % % % % % % Read/Write Magick Persistant Cache Image Format % % % % Software Design % % Cristy % % March 2000 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/constitute.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/hashmap.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/utility.h" #include "magick/version-private.h" /* Forward declarations. */ static MagickBooleanType WriteMPCImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M P C % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMPC() returns MagickTrue if the image format type, identified by the % magick string, is an Magick Persistent Cache image. % % The format of the IsMPC method is: % % MagickBooleanType IsMPC(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsMPC(const unsigned char *magick,const size_t length) { if (length < 14) return(MagickFalse); if (LocaleNCompare((const char *) magick,"id=MagickCache",14) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d C A C H E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMPCImage() reads an Magick Persistent Cache image file and returns % it. It allocates the memory necessary for the new Image structure and % returns a pointer to the new image. % % The format of the ReadMPCImage method is: % % Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) % % Decompression code contributed by Kyle Shorter. % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) { char cache_filename[MaxTextExtent], id[MaxTextExtent], keyword[MaxTextExtent], *options; const unsigned char *p; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; MagickBooleanType status; MagickOffsetType offset; MagickStatusType flags; register ssize_t i; size_t depth, length; ssize_t count; StringInfo *profile; unsigned int signature; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(cache_filename,image->filename,MaxTextExtent); AppendImageFormat("cache",cache_filename); c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } *id='\0'; (void) ResetMagickMemory(keyword,0,sizeof(keyword)); offset=0; do { /* Decode image header; header terminates one character beyond a ':'. */ profiles=(LinkedListInfo *) NULL; length=MaxTextExtent; options=AcquireString((char *) NULL); signature=GetMagickSignature((const StringInfo *) NULL); image->depth=8; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if (c == (int) '\\') c=ReadBlobByte(image); else if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ length=MaxTextExtent; p=keyword; do { if (c == (int) '=') break; if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MaxTextExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } *p++=(char) c; c=ReadBlobByte(image); if (c == '\\') { c=ReadBlobByte(image); if (c == (int) '}') { *p++=(char) c; c=ReadBlobByte(image); } } if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,strlen(options)); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorDatabase(options,&image->background_color, exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorDatabase(options,&image->border_color, exception); break; } (void) SetImageProperty(image,keyword,options); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { ssize_t storage_class; storage_class=ParseCommandOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { image->colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { ssize_t endian; endian=ParseCommandOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } if (LocaleCompare(keyword,"error") == 0) { image->error.mean_error_per_pixel=StringToDouble(options, (char **) NULL); break; } (void) SetImageProperty(image,keyword,options); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options,(char **) NULL); break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MaxTextExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"magick-signature") == 0) { signature=(unsigned int) StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"matte") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"matte-color") == 0) { (void) QueryColorDatabase(options,&image->matte_color, exception); break; } if (LocaleCompare(keyword,"maximum-error") == 0) { image->error.normalized_maximum_error=StringToDouble( options,(char **) NULL); break; } if (LocaleCompare(keyword,"mean-error") == 0) { image->error.normalized_mean_error=StringToDouble(options, (char **) NULL); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'o': case 'O': { if (LocaleCompare(keyword,"opaque") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"orientation") == 0) { ssize_t orientation; orientation=ParseCommandOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"pixel-intensity") == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,options); if (intensity < 0) break; image->intensity=(PixelIntensityMethod) intensity; break; } if ((LocaleNCompare(keyword,"profile:",8) == 0) || (LocaleNCompare(keyword,"profile-",8) == 0)) { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(keyword+8)); profile=BlobToStringInfo((const void *) NULL,(size_t) StringToLong(options)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); (void) SetImageProfile(image,keyword+8,profile); profile=DestroyStringInfo(profile); break; } (void) SetImageProperty(image,keyword,options); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; if ((flags & SigmaValue) != 0) image->chromaticity.red_primary.y=geometry_info.sigma; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(ssize_t) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } if (LocaleCompare(keyword,"type") == 0) { ssize_t type; type=ParseCommandOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions,MagickFalse, options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options); break; } default: { (void) SetImageProperty(image,keyword,options); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"MagickCache") != 0) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (signature != GetMagickSignature((const StringInfo *) NULL)) ThrowReaderException(CacheError,"IncompatibleAPI"); if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MaxTextExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MaxTextExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MaxTextExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; const StringInfo *profile; register unsigned char *p; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); (void) ReadBlob(image,GetStringInfoLength(profile),p); } name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { /* Create image colormap. */ image->colormap=(PixelPacket *) AcquireQuantumMemory(image->colors+1, sizeof(*image->colormap)); if (image->colormap == (PixelPacket *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->colors != 0) { size_t packet_size; unsigned char *colormap; /* Read image colormap from file. */ packet_size=(size_t) (3UL*depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); if (count != (ssize_t) (packet_size*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=colormap; switch (depth) { default: ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned int pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); /* Attach persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception); if (status == MagickFalse) ThrowReaderException(CacheError,"UnableToPersistPixelCache"); /* Proceed to next image. */ do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (c != EOF); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M P C I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterMPCImage() adds properties for the Cache image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterMPCImage method is: % % size_t RegisterMPCImage(void) % */ ModuleExport size_t RegisterMPCImage(void) { MagickInfo *entry; entry=SetMagickInfo("CACHE"); entry->description=ConstantString("Magick Persistent Cache image format"); entry->module=ConstantString("MPC"); entry->stealth=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("MPC"); entry->decoder=(DecodeImageHandler *) ReadMPCImage; entry->encoder=(EncodeImageHandler *) WriteMPCImage; entry->magick=(IsImageFormatHandler *) IsMPC; entry->description=ConstantString("Magick Persistent Cache image format"); entry->module=ConstantString("MPC"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M P C I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterMPCImage() removes format registrations made by the % MPC module from the list of supported formats. % % The format of the UnregisterMPCImage method is: % % UnregisterMPCImage(void) % */ ModuleExport void UnregisterMPCImage(void) { (void) UnregisterMagickInfo("CACHE"); (void) UnregisterMagickInfo("MPC"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M P C I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMPCImage() writes an Magick Persistent Cache image to a file. % % The format of the WriteMPCImage method is: % % MagickBooleanType WriteMPCImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % */ static MagickBooleanType WriteMPCImage(const ImageInfo *image_info,Image *image) { char buffer[MaxTextExtent], cache_filename[MaxTextExtent]; const char *property, *value; MagickBooleanType status; MagickOffsetType offset, scene; register ssize_t i; size_t depth, one; /* Open persistent cache. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) CopyMagickString(cache_filename,image->filename,MaxTextExtent); AppendImageFormat("cache",cache_filename); scene=0; offset=0; one=1; do { /* Write persistent cache meta-information. */ depth=GetImageQuantumDepth(image,MagickTrue); if ((image->storage_class == PseudoClass) && (image->colors > (one << depth))) image->storage_class=DirectClass; (void) WriteBlobString(image,"id=MagickCache\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"magick-signature=%u\n", GetMagickSignature((const StringInfo *) NULL)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "class=%s colors=%.20g matte=%s\n",CommandOptionToMnemonic( MagickClassOptions,image->storage_class),(double) image->colors, CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) image->matte)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "columns=%.20g rows=%.20g depth=%.20g\n",(double) image->columns, (double) image->rows,(double) image->depth); (void) WriteBlobString(image,buffer); if (image->type != UndefinedType) { (void) FormatLocaleString(buffer,MaxTextExtent,"type=%s\n", CommandOptionToMnemonic(MagickTypeOptions,image->type)); (void) WriteBlobString(image,buffer); } if (image->colorspace != UndefinedColorspace) { (void) FormatLocaleString(buffer,MaxTextExtent,"colorspace=%s\n", CommandOptionToMnemonic(MagickColorspaceOptions,image->colorspace)); (void) WriteBlobString(image,buffer); } if (image->intensity != UndefinedPixelIntensityMethod) { (void) FormatLocaleString(buffer,MaxTextExtent,"pixel-intensity=%s\n", CommandOptionToMnemonic(MagickPixelIntensityOptions, image->intensity)); (void) WriteBlobString(image,buffer); } if (image->endian != UndefinedEndian) { (void) FormatLocaleString(buffer,MaxTextExtent,"endian=%s\n", CommandOptionToMnemonic(MagickEndianOptions,image->endian)); (void) WriteBlobString(image,buffer); } if (image->compression != UndefinedCompression) { (void) FormatLocaleString(buffer,MaxTextExtent, "compression=%s quality=%.20g\n",CommandOptionToMnemonic( MagickCompressOptions,image->compression),(double) image->quality); (void) WriteBlobString(image,buffer); } if (image->units != UndefinedResolution) { (void) FormatLocaleString(buffer,MaxTextExtent,"units=%s\n", CommandOptionToMnemonic(MagickResolutionOptions,image->units)); (void) WriteBlobString(image,buffer); } if ((image->x_resolution != 0) || (image->y_resolution != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent, "resolution=%gx%g\n",image->x_resolution,image->y_resolution); (void) WriteBlobString(image,buffer); } if ((image->page.width != 0) || (image->page.height != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent, "page=%.20gx%.20g%+.20g%+.20g\n",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); (void) WriteBlobString(image,buffer); } else if ((image->page.x != 0) || (image->page.y != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent,"page=%+ld%+ld\n", (long) image->page.x,(long) image->page.y); (void) WriteBlobString(image,buffer); } if ((image->tile_offset.x != 0) || (image->tile_offset.y != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent,"tile-offset=%+ld%+ld\n", (long) image->tile_offset.x,(long) image->tile_offset.y); (void) WriteBlobString(image,buffer); } if ((GetNextImageInList(image) != (Image *) NULL) || (GetPreviousImageInList(image) != (Image *) NULL)) { if (image->scene == 0) (void) FormatLocaleString(buffer,MaxTextExtent, "iterations=%.20g delay=%.20g ticks-per-second=%.20g\n",(double) image->iterations,(double) image->delay,(double) image->ticks_per_second); else (void) FormatLocaleString(buffer,MaxTextExtent,"scene=%.20g " "iterations=%.20g delay=%.20g ticks-per-second=%.20g\n", (double) image->scene,(double) image->iterations,(double) image->delay,(double) image->ticks_per_second); (void) WriteBlobString(image,buffer); } else { if (image->scene != 0) { (void) FormatLocaleString(buffer,MaxTextExtent,"scene=%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); } if (image->iterations != 0) { (void) FormatLocaleString(buffer,MaxTextExtent,"iterations=%.20g\n", (double) image->iterations); (void) WriteBlobString(image,buffer); } if (image->delay != 0) { (void) FormatLocaleString(buffer,MaxTextExtent,"delay=%.20g\n", (double) image->delay); (void) WriteBlobString(image,buffer); } if (image->ticks_per_second != UndefinedTicksPerSecond) { (void) FormatLocaleString(buffer,MaxTextExtent, "ticks-per-second=%.20g\n",(double) image->ticks_per_second); (void) WriteBlobString(image,buffer); } } if (image->gravity != UndefinedGravity) { (void) FormatLocaleString(buffer,MaxTextExtent,"gravity=%s\n", CommandOptionToMnemonic(MagickGravityOptions,image->gravity)); (void) WriteBlobString(image,buffer); } if (image->dispose != UndefinedDispose) { (void) FormatLocaleString(buffer,MaxTextExtent,"dispose=%s\n", CommandOptionToMnemonic(MagickDisposeOptions,image->dispose)); (void) WriteBlobString(image,buffer); } if (image->rendering_intent != UndefinedIntent) { (void) FormatLocaleString(buffer,MaxTextExtent, "rendering-intent=%s\n",CommandOptionToMnemonic(MagickIntentOptions, image->rendering_intent)); (void) WriteBlobString(image,buffer); } if (image->gamma != 0.0) { (void) FormatLocaleString(buffer,MaxTextExtent,"gamma=%g\n", image->gamma); (void) WriteBlobString(image,buffer); } if (image->chromaticity.white_point.x != 0.0) { /* Note chomaticity points. */ (void) FormatLocaleString(buffer,MaxTextExtent,"red-primary=" "%g,%g green-primary=%g,%g blue-primary=%g,%g\n", image->chromaticity.red_primary.x,image->chromaticity.red_primary.y, image->chromaticity.green_primary.x, image->chromaticity.green_primary.y, image->chromaticity.blue_primary.x, image->chromaticity.blue_primary.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "white-point=%g,%g\n",image->chromaticity.white_point.x, image->chromaticity.white_point.y); (void) WriteBlobString(image,buffer); } if (image->orientation != UndefinedOrientation) { (void) FormatLocaleString(buffer,MaxTextExtent, "orientation=%s\n",CommandOptionToMnemonic(MagickOrientationOptions, image->orientation)); (void) WriteBlobString(image,buffer); } if (image->profiles != (void *) NULL) { const char *name; const StringInfo *profile; /* Generic profile. */ ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent, "profile:%s=%.20g\n",name,(double) GetStringInfoLength(profile)); (void) WriteBlobString(image,buffer); } name=GetNextImageProfile(image); } } if (image->montage != (char *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent,"montage=%s\n", image->montage); (void) WriteBlobString(image,buffer); } ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s=",property); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,property); if (value != (const char *) NULL) { size_t length; length=strlen(value); for (i=0; i < (ssize_t) length; i++) if (isspace((int) ((unsigned char) value[i])) != 0) break; if ((i == (ssize_t) length) && (i != 0)) (void) WriteBlob(image,length,(const unsigned char *) value); else { (void) WriteBlobByte(image,'{'); if (strchr(value,'}') == (char *) NULL) (void) WriteBlob(image,length,(const unsigned char *) value); else for (i=0; i < (ssize_t) length; i++) { if (value[i] == (int) '}') (void) WriteBlobByte(image,'\\'); (void) WriteBlobByte(image,value[i]); } (void) WriteBlobByte(image,'}'); } } (void) WriteBlobByte(image,'\n'); property=GetNextImageProperty(image); } (void) WriteBlobString(image,"\f\n:\032"); if (image->montage != (char *) NULL) { /* Write montage tile directory. */ if (image->directory != (char *) NULL) (void) WriteBlobString(image,image->directory); (void) WriteBlobByte(image,'\0'); } if (image->profiles != 0) { const char *name; const StringInfo *profile; /* Write image profiles. */ ResetImageProfileIterator(image); name=GetNextImageProfile(image); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); name=GetNextImageProfile(image); } } if (image->storage_class == PseudoClass) { size_t packet_size; unsigned char *colormap, *q; /* Allocate colormap. */ packet_size=(size_t) (3UL*depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) return(MagickFalse); /* Write colormap to file. */ q=colormap; for (i=0; i < (ssize_t) image->colors; i++) { switch (depth) { default: ThrowWriterException(CorruptImageError,"ImageDepthNotSupported"); case 32: { unsigned int pixel; pixel=ScaleQuantumToLong(image->colormap[i].red); q=PopLongPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToLong(image->colormap[i].green); q=PopLongPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToLong(image->colormap[i].blue); q=PopLongPixel(MSBEndian,pixel,q); break; } case 16: { unsigned short pixel; pixel=ScaleQuantumToShort(image->colormap[i].red); q=PopShortPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToShort(image->colormap[i].green); q=PopShortPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToShort(image->colormap[i].blue); q=PopShortPixel(MSBEndian,pixel,q); break; } case 8: { unsigned char pixel; pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].red); q=PopCharPixel(pixel,q); pixel=(unsigned char) ScaleQuantumToChar( image->colormap[i].green); q=PopCharPixel(pixel,q); pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue); q=PopCharPixel(pixel,q); break; } } } (void) WriteBlob(image,packet_size*image->colors,colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); } /* Initialize persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickFalse,&offset, &image->exception); if (status == MagickFalse) ThrowWriterException(CacheError,"UnableToPersistPixelCache"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); if (image->progress_monitor != (MagickProgressMonitor) NULL) { status=image->progress_monitor(SaveImagesTag,scene, GetImageListLength(image),image->client_data); if (status == MagickFalse) break; } scene++; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-772/c/good_3103_1
crossvul-cpp_data_good_1039_0
/* * rfbserver.c - deal with server-side of the RFB protocol. */ /* * Copyright (C) 2011-2012 D. R. Commander * Copyright (C) 2005 Rohit Kumar, Johannes E. Schindelin * Copyright (C) 2002 RealVNC Ltd. * OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>. * Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge. * All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #ifdef __STRICT_ANSI__ #define _BSD_SOURCE #define _POSIX_SOURCE #define _XOPEN_SOURCE 600 #endif #include <stdio.h> #include <string.h> #include <rfb/rfb.h> #include <rfb/rfbregion.h> #include "private.h" #include "rfb/rfbconfig.h" #ifdef LIBVNCSERVER_HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #include <io.h> #define write(sock,buf,len) send(sock,buf,len,0) #else #ifdef LIBVNCSERVER_HAVE_UNISTD_H #include <unistd.h> #endif #include <pwd.h> #ifdef LIBVNCSERVER_HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef LIBVNCSERVER_HAVE_NETINET_IN_H #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <arpa/inet.h> #endif #endif #ifdef DEBUGPROTO #undef DEBUGPROTO #define DEBUGPROTO(x) x #else #define DEBUGPROTO(x) #endif #include <stdarg.h> #include <scale.h> /* stst() */ #include <sys/types.h> #include <sys/stat.h> #if LIBVNCSERVER_HAVE_UNISTD_H #include <unistd.h> #endif #ifndef WIN32 /* readdir() */ #include <dirent.h> #endif /* errno */ #include <errno.h> /* strftime() */ #include <time.h> /* INT_MAX */ #include <limits.h> #ifdef LIBVNCSERVER_WITH_WEBSOCKETS #include "rfbssl.h" #endif #ifdef _MSC_VER #define snprintf _snprintf /* Missing in MSVC */ /* Prevent POSIX deprecation warnings */ #define close _close #define strdup _strdup #endif #ifdef WIN32 #include <direct.h> #ifdef __MINGW32__ #define mkdir(path, perms) mkdir(path) /* Omit the perms argument to match POSIX signature */ #else /* MSVC and other windows compilers */ #define mkdir(path, perms) _mkdir(path) /* Omit the perms argument to match POSIX signature */ #endif /* __MINGW32__ else... */ #ifndef S_ISDIR #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR) #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* * Map of quality levels to provide compatibility with TightVNC/TigerVNC * clients. This emulates the behavior of the TigerVNC Server. */ static const int tight2turbo_qual[10] = { 15, 29, 41, 42, 62, 77, 79, 86, 92, 100 }; static const int tight2turbo_subsamp[10] = { 1, 1, 1, 2, 2, 2, 0, 0, 0, 0 }; #endif static void rfbProcessClientProtocolVersion(rfbClientPtr cl); static void rfbProcessClientNormalMessage(rfbClientPtr cl); static void rfbProcessClientInitMessage(rfbClientPtr cl); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD void rfbIncrClientRef(rfbClientPtr cl) { LOCK(cl->refCountMutex); cl->refCount++; UNLOCK(cl->refCountMutex); } void rfbDecrClientRef(rfbClientPtr cl) { LOCK(cl->refCountMutex); cl->refCount--; if(cl->refCount<=0) /* just to be sure also < 0 */ TSIGNAL(cl->deleteCond); UNLOCK(cl->refCountMutex); } #else void rfbIncrClientRef(rfbClientPtr cl) {} void rfbDecrClientRef(rfbClientPtr cl) {} #endif #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD static MUTEX(rfbClientListMutex); #endif struct rfbClientIterator { rfbClientPtr next; rfbScreenInfoPtr screen; rfbBool closedToo; }; void rfbClientListInit(rfbScreenInfoPtr rfbScreen) { if(sizeof(rfbBool)!=1) { /* a sanity check */ fprintf(stderr,"rfbBool's size is not 1 (%d)!\n",(int)sizeof(rfbBool)); /* we cannot continue, because rfbBool is supposed to be char everywhere */ exit(1); } rfbScreen->clientHead = NULL; INIT_MUTEX(rfbClientListMutex); } rfbClientIteratorPtr rfbGetClientIterator(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i = (rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator)); i->next = NULL; i->screen = rfbScreen; i->closedToo = FALSE; return i; } rfbClientIteratorPtr rfbGetClientIteratorWithClosed(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i = (rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator)); i->next = NULL; i->screen = rfbScreen; i->closedToo = TRUE; return i; } rfbClientPtr rfbClientIteratorHead(rfbClientIteratorPtr i) { #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(i->next != 0) { rfbDecrClientRef(i->next); rfbIncrClientRef(i->screen->clientHead); } #endif LOCK(rfbClientListMutex); i->next = i->screen->clientHead; UNLOCK(rfbClientListMutex); return i->next; } rfbClientPtr rfbClientIteratorNext(rfbClientIteratorPtr i) { if(i->next == 0) { LOCK(rfbClientListMutex); i->next = i->screen->clientHead; UNLOCK(rfbClientListMutex); } else { IF_PTHREADS(rfbClientPtr cl = i->next); i->next = i->next->next; IF_PTHREADS(rfbDecrClientRef(cl)); } #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(!i->closedToo) while(i->next && i->next->sock<0) i->next = i->next->next; if(i->next) rfbIncrClientRef(i->next); #endif return i->next; } void rfbReleaseClientIterator(rfbClientIteratorPtr iterator) { IF_PTHREADS(if(iterator->next) rfbDecrClientRef(iterator->next)); free(iterator); } /* * rfbNewClientConnection is called from sockets.c when a new connection * comes in. */ void rfbNewClientConnection(rfbScreenInfoPtr rfbScreen, int sock) { rfbNewClient(rfbScreen,sock); } /* * rfbReverseConnection is called to make an outward * connection to a "listening" RFB client. */ rfbClientPtr rfbReverseConnection(rfbScreenInfoPtr rfbScreen, char *host, int port) { int sock; rfbClientPtr cl; if ((sock = rfbConnect(rfbScreen, host, port)) < 0) return (rfbClientPtr)NULL; cl = rfbNewClient(rfbScreen, sock); if (cl) { cl->reverseConnection = TRUE; } return cl; } void rfbSetProtocolVersion(rfbScreenInfoPtr rfbScreen, int major_, int minor_) { /* Permit the server to set the version to report */ /* TODO: sanity checking */ if ((major_==3) && (minor_ > 2 && minor_ < 9)) { rfbScreen->protocolMajorVersion = major_; rfbScreen->protocolMinorVersion = minor_; } else rfbLog("rfbSetProtocolVersion(%d,%d) set to invalid values\n", major_, minor_); } /* * rfbNewClient is called when a new connection has been made by whatever * means. */ static rfbClientPtr rfbNewTCPOrUDPClient(rfbScreenInfoPtr rfbScreen, int sock, rfbBool isUDP) { rfbProtocolVersionMsg pv; rfbClientIteratorPtr iterator; rfbClientPtr cl,cl_; #ifdef LIBVNCSERVER_IPv6 struct sockaddr_storage addr; #else struct sockaddr_in addr; #endif socklen_t addrlen = sizeof(addr); rfbProtocolExtension* extension; cl = (rfbClientPtr)calloc(sizeof(rfbClientRec),1); cl->screen = rfbScreen; cl->sock = sock; cl->viewOnly = FALSE; /* setup pseudo scaling */ cl->scaledScreen = rfbScreen; cl->scaledScreen->scaledScreenRefCount++; rfbResetStats(cl); cl->clientData = NULL; cl->clientGoneHook = rfbDoNothingWithClient; if(isUDP) { rfbLog(" accepted UDP client\n"); } else { #ifdef LIBVNCSERVER_IPv6 char host[1024]; #endif int one=1; size_t otherClientsCount = 0; getpeername(sock, (struct sockaddr *)&addr, &addrlen); #ifdef LIBVNCSERVER_IPv6 if(getnameinfo((struct sockaddr*)&addr, addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST) != 0) { rfbLogPerror("rfbNewClient: error in getnameinfo"); cl->host = strdup(""); } else cl->host = strdup(host); #else cl->host = strdup(inet_ntoa(addr.sin_addr)); #endif iterator = rfbGetClientIterator(rfbScreen); while ((cl_ = rfbClientIteratorNext(iterator)) != NULL) ++otherClientsCount; rfbReleaseClientIterator(iterator); rfbLog(" %lu other clients\n", (unsigned long) otherClientsCount); if(!rfbSetNonBlocking(sock)) { close(sock); return NULL; } if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&one, sizeof(one)) < 0) { rfbLogPerror("setsockopt failed: can't set TCP_NODELAY flag, non TCP socket?"); } FD_SET(sock,&(rfbScreen->allFds)); rfbScreen->maxFd = rfbMax(sock,rfbScreen->maxFd); INIT_MUTEX(cl->outputMutex); INIT_MUTEX(cl->refCountMutex); INIT_MUTEX(cl->sendMutex); INIT_COND(cl->deleteCond); cl->state = RFB_PROTOCOL_VERSION; cl->reverseConnection = FALSE; cl->readyForSetColourMapEntries = FALSE; cl->useCopyRect = FALSE; cl->preferredEncoding = -1; cl->correMaxWidth = 48; cl->correMaxHeight = 48; #ifdef LIBVNCSERVER_HAVE_LIBZ cl->zrleData = NULL; #endif cl->copyRegion = sraRgnCreate(); cl->copyDX = 0; cl->copyDY = 0; cl->modifiedRegion = sraRgnCreateRect(0,0,rfbScreen->width,rfbScreen->height); INIT_MUTEX(cl->updateMutex); INIT_COND(cl->updateCond); cl->requestedRegion = sraRgnCreate(); cl->format = cl->screen->serverFormat; cl->translateFn = rfbTranslateNone; cl->translateLookupTable = NULL; LOCK(rfbClientListMutex); IF_PTHREADS(cl->refCount = 0); cl->next = rfbScreen->clientHead; cl->prev = NULL; if (rfbScreen->clientHead) rfbScreen->clientHead->prev = cl; rfbScreen->clientHead = cl; UNLOCK(rfbClientListMutex); #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) cl->tightQualityLevel = -1; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP; { int i; for (i = 0; i < 4; i++) cl->zsActive[i] = FALSE; } #endif #endif cl->fileTransfer.fd = -1; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorPosUpdates = FALSE; cl->useRichCursorEncoding = FALSE; cl->enableLastRectEncoding = FALSE; cl->enableKeyboardLedState = FALSE; cl->enableSupportedMessages = FALSE; cl->enableSupportedEncodings = FALSE; cl->enableServerIdentity = FALSE; cl->lastKeyboardLedState = -1; cl->cursorX = rfbScreen->cursorX; cl->cursorY = rfbScreen->cursorY; cl->useNewFBSize = FALSE; cl->useExtDesktopSize = FALSE; cl->requestedDesktopSizeChange = 0; cl->lastDesktopSizeChangeError = 0; #ifdef LIBVNCSERVER_HAVE_LIBZ cl->compStreamInited = FALSE; cl->compStream.total_in = 0; cl->compStream.total_out = 0; cl->compStream.zalloc = Z_NULL; cl->compStream.zfree = Z_NULL; cl->compStream.opaque = Z_NULL; cl->zlibCompressLevel = 5; #endif cl->progressiveSliceY = 0; cl->extensions = NULL; cl->lastPtrX = -1; #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD cl->pipe_notify_client_thread[0] = -1; cl->pipe_notify_client_thread[1] = -1; #endif #ifdef LIBVNCSERVER_WITH_WEBSOCKETS /* * Wait a few ms for the client to send WebSockets connection (TLS/SSL or plain) */ if (!webSocketsCheck(cl)) { /* Error reporting handled in webSocketsHandshake */ rfbCloseClient(cl); rfbClientConnectionGone(cl); return NULL; } #endif sprintf(pv,rfbProtocolVersionFormat,rfbScreen->protocolMajorVersion, rfbScreen->protocolMinorVersion); if (rfbWriteExact(cl, pv, sz_rfbProtocolVersionMsg) < 0) { rfbLogPerror("rfbNewClient: write"); rfbCloseClient(cl); rfbClientConnectionGone(cl); return NULL; } } for(extension = rfbGetExtensionIterator(); extension; extension=extension->next) { void* data = NULL; /* if the extension does not have a newClient method, it wants * to be initialized later. */ if(extension->newClient && extension->newClient(cl, &data)) rfbEnableExtension(cl, extension, data); } rfbReleaseExtensionIterator(); switch (cl->screen->newClientHook(cl)) { case RFB_CLIENT_ON_HOLD: cl->onHold = TRUE; break; case RFB_CLIENT_ACCEPT: cl->onHold = FALSE; break; case RFB_CLIENT_REFUSE: rfbCloseClient(cl); rfbClientConnectionGone(cl); cl = NULL; break; } return cl; } rfbClientPtr rfbNewClient(rfbScreenInfoPtr rfbScreen, int sock) { return(rfbNewTCPOrUDPClient(rfbScreen,sock,FALSE)); } rfbClientPtr rfbNewUDPClient(rfbScreenInfoPtr rfbScreen) { return((rfbScreen->udpClient= rfbNewTCPOrUDPClient(rfbScreen,rfbScreen->udpSock,TRUE))); } /* * rfbClientConnectionGone is called from sockets.c just after a connection * has gone away. */ void rfbClientConnectionGone(rfbClientPtr cl) { #if defined(LIBVNCSERVER_HAVE_LIBZ) && defined(LIBVNCSERVER_HAVE_LIBJPEG) int i; #endif LOCK(rfbClientListMutex); if (cl->prev) cl->prev->next = cl->next; else cl->screen->clientHead = cl->next; if (cl->next) cl->next->prev = cl->prev; UNLOCK(rfbClientListMutex); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(cl->screen->backgroundLoop != FALSE) { int i; do { LOCK(cl->refCountMutex); i=cl->refCount; if(i>0) WAIT(cl->deleteCond,cl->refCountMutex); UNLOCK(cl->refCountMutex); } while(i>0); } #endif if(cl->sock>=0) close(cl->sock); if (cl->scaledScreen!=NULL) cl->scaledScreen->scaledScreenRefCount--; #ifdef LIBVNCSERVER_HAVE_LIBZ rfbFreeZrleData(cl); #endif rfbFreeUltraData(cl); /* free buffers holding pixel data before and after encoding */ free(cl->beforeEncBuf); free(cl->afterEncBuf); if(cl->sock>=0) FD_CLR(cl->sock,&(cl->screen->allFds)); cl->clientGoneHook(cl); rfbLog("Client %s gone\n",cl->host); free(cl->host); #ifdef LIBVNCSERVER_HAVE_LIBZ /* Release the compression state structures if any. */ if ( cl->compStreamInited ) { deflateEnd( &(cl->compStream) ); } #ifdef LIBVNCSERVER_HAVE_LIBJPEG for (i = 0; i < 4; i++) { if (cl->zsActive[i]) deflateEnd(&cl->zsStruct[i]); } #endif #endif if (cl->screen->pointerClient == cl) cl->screen->pointerClient = NULL; sraRgnDestroy(cl->modifiedRegion); sraRgnDestroy(cl->requestedRegion); sraRgnDestroy(cl->copyRegion); if (cl->translateLookupTable) free(cl->translateLookupTable); TINI_COND(cl->updateCond); TINI_MUTEX(cl->updateMutex); /* make sure outputMutex is unlocked before destroying */ LOCK(cl->outputMutex); UNLOCK(cl->outputMutex); TINI_MUTEX(cl->outputMutex); LOCK(cl->sendMutex); UNLOCK(cl->sendMutex); TINI_MUTEX(cl->sendMutex); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD close(cl->pipe_notify_client_thread[0]); close(cl->pipe_notify_client_thread[1]); #endif rfbPrintStats(cl); rfbResetStats(cl); free(cl); } /* * rfbProcessClientMessage is called when there is data to read from a client. */ void rfbProcessClientMessage(rfbClientPtr cl) { switch (cl->state) { case RFB_PROTOCOL_VERSION: rfbProcessClientProtocolVersion(cl); return; case RFB_SECURITY_TYPE: rfbProcessClientSecurityType(cl); return; case RFB_AUTHENTICATION: rfbAuthProcessClientMessage(cl); return; case RFB_INITIALISATION: case RFB_INITIALISATION_SHARED: rfbProcessClientInitMessage(cl); return; default: rfbProcessClientNormalMessage(cl); return; } } /* * rfbProcessClientProtocolVersion is called when the client sends its * protocol version. */ static void rfbProcessClientProtocolVersion(rfbClientPtr cl) { rfbProtocolVersionMsg pv; int n, major_, minor_; if ((n = rfbReadExact(cl, pv, sz_rfbProtocolVersionMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientProtocolVersion: client gone\n"); else rfbLogPerror("rfbProcessClientProtocolVersion: read"); rfbCloseClient(cl); return; } pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv,rfbProtocolVersionFormat,&major_,&minor_) != 2) { rfbErr("rfbProcessClientProtocolVersion: not a valid RFB client: %s\n", pv); rfbCloseClient(cl); return; } rfbLog("Client Protocol Version %d.%d\n", major_, minor_); if (major_ != rfbProtocolMajorVersion) { rfbErr("RFB protocol version mismatch - server %d.%d, client %d.%d", cl->screen->protocolMajorVersion, cl->screen->protocolMinorVersion, major_,minor_); rfbCloseClient(cl); return; } /* Check for the minor version use either of the two standard version of RFB */ /* * UltraVNC Viewer detects FileTransfer compatible servers via rfb versions * 3.4, 3.6, 3.14, 3.16 * It's a bad method, but it is what they use to enable features... * maintaining RFB version compatibility across multiple servers is a pain * Should use something like ServerIdentity encoding */ cl->protocolMajorVersion = major_; cl->protocolMinorVersion = minor_; rfbLog("Protocol version sent %d.%d, using %d.%d\n", major_, minor_, rfbProtocolMajorVersion, cl->protocolMinorVersion); rfbAuthNewClient(cl); } void rfbClientSendString(rfbClientPtr cl, const char *reason) { char *buf; int len = strlen(reason); rfbLog("rfbClientSendString(\"%s\")\n", reason); buf = (char *)malloc(4 + len); ((uint32_t *)buf)[0] = Swap32IfLE(len); memcpy(buf + 4, reason, len); if (rfbWriteExact(cl, buf, 4 + len) < 0) rfbLogPerror("rfbClientSendString: write"); free(buf); rfbCloseClient(cl); } /* * rfbClientConnFailed is called when a client connection has failed either * because it talks the wrong protocol or it has failed authentication. */ void rfbClientConnFailed(rfbClientPtr cl, const char *reason) { char *buf; int len = strlen(reason); rfbLog("rfbClientConnFailed(\"%s\")\n", reason); buf = (char *)malloc(8 + len); ((uint32_t *)buf)[0] = Swap32IfLE(rfbConnFailed); ((uint32_t *)buf)[1] = Swap32IfLE(len); memcpy(buf + 8, reason, len); if (rfbWriteExact(cl, buf, 8 + len) < 0) rfbLogPerror("rfbClientConnFailed: write"); free(buf); rfbCloseClient(cl); } /* * rfbProcessClientInitMessage is called when the client sends its * initialisation message. */ static void rfbProcessClientInitMessage(rfbClientPtr cl) { rfbClientInitMsg ci; union { char buf[256]; rfbServerInitMsg si; } u; int len, n; rfbClientIteratorPtr iterator; rfbClientPtr otherCl; rfbExtensionData* extension; if (cl->state == RFB_INITIALISATION_SHARED) { /* In this case behave as though an implicit ClientInit message has * already been received with a shared-flag of true. */ ci.shared = 1; /* Avoid the possibility of exposing the RFB_INITIALISATION_SHARED * state to calling software. */ cl->state = RFB_INITIALISATION; } else { if ((n = rfbReadExact(cl, (char *)&ci,sz_rfbClientInitMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientInitMessage: client gone\n"); else rfbLogPerror("rfbProcessClientInitMessage: read"); rfbCloseClient(cl); return; } } memset(u.buf,0,sizeof(u.buf)); u.si.framebufferWidth = Swap16IfLE(cl->screen->width); u.si.framebufferHeight = Swap16IfLE(cl->screen->height); u.si.format = cl->screen->serverFormat; u.si.format.redMax = Swap16IfLE(u.si.format.redMax); u.si.format.greenMax = Swap16IfLE(u.si.format.greenMax); u.si.format.blueMax = Swap16IfLE(u.si.format.blueMax); strncpy(u.buf + sz_rfbServerInitMsg, cl->screen->desktopName, 127); len = strlen(u.buf + sz_rfbServerInitMsg); u.si.nameLength = Swap32IfLE(len); if (rfbWriteExact(cl, u.buf, sz_rfbServerInitMsg + len) < 0) { rfbLogPerror("rfbProcessClientInitMessage: write"); rfbCloseClient(cl); return; } for(extension = cl->extensions; extension;) { rfbExtensionData* next = extension->next; if(extension->extension->init && !extension->extension->init(cl, extension->data)) /* extension requested that it be removed */ rfbDisableExtension(cl, extension->extension); extension = next; } cl->state = RFB_NORMAL; if (!cl->reverseConnection && (cl->screen->neverShared || (!cl->screen->alwaysShared && !ci.shared))) { if (cl->screen->dontDisconnect) { iterator = rfbGetClientIterator(cl->screen); while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("-dontdisconnect: Not shared & existing client\n"); rfbLog(" refusing new client %s\n", cl->host); rfbCloseClient(cl); rfbReleaseClientIterator(iterator); return; } } rfbReleaseClientIterator(iterator); } else { iterator = rfbGetClientIterator(cl->screen); while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("Not shared - closing connection to client %s\n", otherCl->host); rfbCloseClient(otherCl); } } rfbReleaseClientIterator(iterator); } } } /* The values come in based on the scaled screen, we need to convert them to * values based on the man screen's coordinate system */ static rfbBool rectSwapIfLEAndClip(uint16_t* x,uint16_t* y,uint16_t* w,uint16_t* h, rfbClientPtr cl) { int x1=Swap16IfLE(*x); int y1=Swap16IfLE(*y); int w1=Swap16IfLE(*w); int h1=Swap16IfLE(*h); rfbScaledCorrection(cl->scaledScreen, cl->screen, &x1, &y1, &w1, &h1, "rectSwapIfLEAndClip"); *x = x1; *y = y1; *w = w1; *h = h1; if(*w>cl->screen->width-*x) *w=cl->screen->width-*x; /* possible underflow */ if(*w>cl->screen->width-*x) return FALSE; if(*h>cl->screen->height-*y) *h=cl->screen->height-*y; if(*h>cl->screen->height-*y) return FALSE; return TRUE; } /* * Send keyboard state (PointerPos pseudo-encoding). */ rfbBool rfbSendKeyboardLedState(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingKeyboardLedState); rect.r.x = Swap16IfLE(cl->lastKeyboardLedState); rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingKeyboardLedState, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } #define rfbSetBit(buffer, position) (buffer[(position & 255) / 8] |= (1 << (position % 8))) /* * Send rfbEncodingSupportedMessages. */ rfbBool rfbSendSupportedMessages(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; rfbSupportedMessages msgs; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbSupportedMessages > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingSupportedMessages); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(sz_rfbSupportedMessages); rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; memset((char *)&msgs, 0, sz_rfbSupportedMessages); rfbSetBit(msgs.client2server, rfbSetPixelFormat); rfbSetBit(msgs.client2server, rfbFixColourMapEntries); rfbSetBit(msgs.client2server, rfbSetEncodings); rfbSetBit(msgs.client2server, rfbFramebufferUpdateRequest); rfbSetBit(msgs.client2server, rfbKeyEvent); rfbSetBit(msgs.client2server, rfbPointerEvent); rfbSetBit(msgs.client2server, rfbClientCutText); rfbSetBit(msgs.client2server, rfbFileTransfer); rfbSetBit(msgs.client2server, rfbSetScale); /*rfbSetBit(msgs.client2server, rfbSetServerInput); */ /*rfbSetBit(msgs.client2server, rfbSetSW); */ /*rfbSetBit(msgs.client2server, rfbTextChat); */ rfbSetBit(msgs.client2server, rfbPalmVNCSetScaleFactor); rfbSetBit(msgs.server2client, rfbFramebufferUpdate); rfbSetBit(msgs.server2client, rfbSetColourMapEntries); rfbSetBit(msgs.server2client, rfbBell); rfbSetBit(msgs.server2client, rfbServerCutText); rfbSetBit(msgs.server2client, rfbResizeFrameBuffer); rfbSetBit(msgs.server2client, rfbPalmVNCReSizeFrameBuffer); rfbSetBit(msgs.client2server, rfbSetDesktopSize); if (cl->screen->xvpHook) { rfbSetBit(msgs.client2server, rfbXvp); rfbSetBit(msgs.server2client, rfbXvp); } memcpy(&cl->updateBuf[cl->ublen], (char *)&msgs, sz_rfbSupportedMessages); cl->ublen += sz_rfbSupportedMessages; rfbStatRecordEncodingSent(cl, rfbEncodingSupportedMessages, sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages, sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } /* * Send rfbEncodingSupportedEncodings. */ rfbBool rfbSendSupportedEncodings(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; static uint32_t supported[] = { rfbEncodingRaw, rfbEncodingCopyRect, rfbEncodingRRE, rfbEncodingCoRRE, rfbEncodingHextile, #ifdef LIBVNCSERVER_HAVE_LIBZ rfbEncodingZlib, rfbEncodingZRLE, rfbEncodingZYWRLE, #endif #ifdef LIBVNCSERVER_HAVE_LIBJPEG rfbEncodingTight, #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG rfbEncodingTightPng, #endif rfbEncodingUltra, rfbEncodingUltraZip, rfbEncodingXCursor, rfbEncodingRichCursor, rfbEncodingPointerPos, rfbEncodingLastRect, rfbEncodingNewFBSize, rfbEncodingExtDesktopSize, rfbEncodingKeyboardLedState, rfbEncodingSupportedMessages, rfbEncodingSupportedEncodings, rfbEncodingServerIdentity, }; uint32_t nEncodings = sizeof(supported) / sizeof(supported[0]), i; /* think rfbSetEncodingsMsg */ if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + (nEncodings * sizeof(uint32_t)) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingSupportedEncodings); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(nEncodings * sizeof(uint32_t)); rect.r.h = Swap16IfLE(nEncodings); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; for (i = 0; i < nEncodings; i++) { uint32_t encoding = Swap32IfLE(supported[i]); memcpy(&cl->updateBuf[cl->ublen], (char *)&encoding, sizeof(encoding)); cl->ublen += sizeof(encoding); } rfbStatRecordEncodingSent(cl, rfbEncodingSupportedEncodings, sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t)), sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t))); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } void rfbSetServerVersionIdentity(rfbScreenInfoPtr screen, char *fmt, ...) { char buffer[256]; va_list ap; va_start(ap, fmt); vsnprintf(buffer, sizeof(buffer)-1, fmt, ap); va_end(ap); if (screen->versionString!=NULL) free(screen->versionString); screen->versionString = strdup(buffer); } /* * Send rfbEncodingServerIdentity. */ rfbBool rfbSendServerIdentity(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; char buffer[512]; /* tack on our library version */ snprintf(buffer,sizeof(buffer)-1, "%s (%s)", (cl->screen->versionString==NULL ? "unknown" : cl->screen->versionString), LIBVNCSERVER_PACKAGE_STRING); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + (strlen(buffer)+1) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingServerIdentity); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(strlen(buffer)+1); rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; memcpy(&cl->updateBuf[cl->ublen], buffer, strlen(buffer)+1); cl->ublen += strlen(buffer)+1; rfbStatRecordEncodingSent(cl, rfbEncodingServerIdentity, sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1, sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } /* * Send an xvp server message */ rfbBool rfbSendXvp(rfbClientPtr cl, uint8_t version, uint8_t code) { rfbXvpMsg xvp; xvp.type = rfbXvp; xvp.pad = 0; xvp.version = version; xvp.code = code; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&xvp, sz_rfbXvpMsg) < 0) { rfbLogPerror("rfbSendXvp: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbXvp, sz_rfbXvpMsg, sz_rfbXvpMsg); return TRUE; } rfbBool rfbSendTextChatMessage(rfbClientPtr cl, uint32_t length, char *buffer) { rfbTextChatMsg tc; int bytesToSend=0; memset((char *)&tc, 0, sizeof(tc)); tc.type = rfbTextChat; tc.length = Swap32IfLE(length); switch(length) { case rfbTextChatOpen: case rfbTextChatClose: case rfbTextChatFinished: bytesToSend=0; break; default: bytesToSend=length; if (bytesToSend>rfbTextMaxSize) bytesToSend=rfbTextMaxSize; } if (cl->ublen + sz_rfbTextChatMsg + bytesToSend > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } memcpy(&cl->updateBuf[cl->ublen], (char *)&tc, sz_rfbTextChatMsg); cl->ublen += sz_rfbTextChatMsg; if (bytesToSend>0) { memcpy(&cl->updateBuf[cl->ublen], buffer, bytesToSend); cl->ublen += bytesToSend; } rfbStatRecordMessageSent(cl, rfbTextChat, sz_rfbTextChatMsg+bytesToSend, sz_rfbTextChatMsg+bytesToSend); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } #define FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(msg, cl, ret) \ if ((cl->screen->getFileTransferPermission != NULL \ && cl->screen->getFileTransferPermission(cl) != TRUE) \ || cl->screen->permitFileTransfer != TRUE) { \ rfbLog("%sUltra File Transfer is disabled, dropping client: %s\n", msg, cl->host); \ rfbCloseClient(cl); \ return ret; \ } int DB = 1; rfbBool rfbSendFileTransferMessage(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length, const char *buffer) { rfbFileTransferMsg ft; ft.type = rfbFileTransfer; ft.contentType = contentType; ft.contentParam = contentParam; ft.pad = 0; /* UltraVNC did not Swap16LE(ft.contentParam) (Looks like it might be BigEndian) */ ft.size = Swap32IfLE(size); ft.length = Swap32IfLE(length); FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* rfbLog("rfbSendFileTransferMessage( %dtype, %dparam, %dsize, %dlen, %p)\n", contentType, contentParam, size, length, buffer); */ LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&ft, sz_rfbFileTransferMsg) < 0) { rfbLogPerror("rfbSendFileTransferMessage: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); return FALSE; } if (length>0) { if (rfbWriteExact(cl, buffer, length) < 0) { rfbLogPerror("rfbSendFileTransferMessage: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); return FALSE; } } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbFileTransfer, sz_rfbFileTransferMsg+length, sz_rfbFileTransferMsg+length); return TRUE; } /* * UltraVNC uses Windows Structures */ #define MAX_PATH 260 typedef struct { uint32_t dwLowDateTime; uint32_t dwHighDateTime; } RFB_FILETIME; typedef struct { uint32_t dwFileAttributes; RFB_FILETIME ftCreationTime; RFB_FILETIME ftLastAccessTime; RFB_FILETIME ftLastWriteTime; uint32_t nFileSizeHigh; uint32_t nFileSizeLow; uint32_t dwReserved0; uint32_t dwReserved1; uint8_t cFileName[ MAX_PATH ]; uint8_t cAlternateFileName[ 14 ]; } RFB_FIND_DATA; #define RFB_FILE_ATTRIBUTE_READONLY 0x1 #define RFB_FILE_ATTRIBUTE_HIDDEN 0x2 #define RFB_FILE_ATTRIBUTE_SYSTEM 0x4 #define RFB_FILE_ATTRIBUTE_DIRECTORY 0x10 #define RFB_FILE_ATTRIBUTE_ARCHIVE 0x20 #define RFB_FILE_ATTRIBUTE_NORMAL 0x80 #define RFB_FILE_ATTRIBUTE_TEMPORARY 0x100 #define RFB_FILE_ATTRIBUTE_COMPRESSED 0x800 rfbBool rfbFilenameTranslate2UNIX(rfbClientPtr cl, /* in */ char *path, /* out */ char *unixPath, size_t unixPathMaxLen) { int x; char *home=NULL; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* * Do not use strncpy() - truncating the file name would probably have undesirable side effects * Instead check if destination buffer is big enough */ if (strlen(path) >= unixPathMaxLen) return FALSE; /* C: */ if (path[0]=='C' && path[1]==':') strcpy(unixPath, &path[2]); else { home = getenv("HOME"); if (home!=NULL) { /* Re-check buffer size */ if ((strlen(path) + strlen(home) + 1) >= unixPathMaxLen) return FALSE; strcpy(unixPath, home); strcat(unixPath,"/"); strcat(unixPath, path); } else strcpy(unixPath, path); } for (x=0;x<strlen(unixPath);x++) if (unixPath[x]=='\\') unixPath[x]='/'; return TRUE; } rfbBool rfbFilenameTranslate2DOS(rfbClientPtr cl, char *unixPath, char *path) { int x; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); sprintf(path,"C:%s", unixPath); for (x=2;x<strlen(path);x++) if (path[x]=='/') path[x]='\\'; return TRUE; } rfbBool rfbSendDirContent(rfbClientPtr cl, int length, char *buffer) { char retfilename[MAX_PATH]; char path[MAX_PATH]; struct stat statbuf; RFB_FIND_DATA win32filename; int nOptLen = 0, retval=0; #ifdef WIN32 WIN32_FIND_DATAA winFindData; HANDLE findHandle; int pathLen, basePathLength; char *basePath; #else DIR *dirp=NULL; struct dirent *direntp=NULL; #endif FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* Client thinks we are Winblows */ if (!rfbFilenameTranslate2UNIX(cl, buffer, path, sizeof(path))) return FALSE; if (DB) rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: \"%s\"->\"%s\"\n",buffer, path); #ifdef WIN32 // Create a search string, like C:\folder\* pathLen = strlen(path); basePath = malloc(pathLen + 3); memcpy(basePath, path, pathLen); basePathLength = pathLen; basePath[basePathLength] = '\\'; basePath[basePathLength + 1] = '*'; basePath[basePathLength + 2] = '\0'; // Start a search memset(&winFindData, 0, sizeof(winFindData)); findHandle = FindFirstFileA(path, &winFindData); free(basePath); if (findHandle == INVALID_HANDLE_VALUE) #else dirp=opendir(path); if (dirp==NULL) #endif return rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, 0, NULL); /* send back the path name (necessary for links) */ if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, length, buffer)==FALSE) return FALSE; #ifdef WIN32 while (findHandle != INVALID_HANDLE_VALUE) #else for (direntp=readdir(dirp); direntp!=NULL; direntp=readdir(dirp)) #endif { /* get stats */ #ifdef WIN32 snprintf(retfilename,sizeof(retfilename),"%s/%s", path, winFindData.cFileName); #else snprintf(retfilename,sizeof(retfilename),"%s/%s", path, direntp->d_name); #endif retval = stat(retfilename, &statbuf); if (retval==0) { memset((char *)&win32filename, 0, sizeof(win32filename)); #ifdef WIN32 win32filename.dwFileAttributes = winFindData.dwFileAttributes; win32filename.ftCreationTime.dwLowDateTime = winFindData.ftCreationTime.dwLowDateTime; win32filename.ftCreationTime.dwHighDateTime = winFindData.ftCreationTime.dwHighDateTime; win32filename.ftLastAccessTime.dwLowDateTime = winFindData.ftLastAccessTime.dwLowDateTime; win32filename.ftLastAccessTime.dwHighDateTime = winFindData.ftLastAccessTime.dwHighDateTime; win32filename.ftLastWriteTime.dwLowDateTime = winFindData.ftLastWriteTime.dwLowDateTime; win32filename.ftLastWriteTime.dwHighDateTime = winFindData.ftLastWriteTime.dwHighDateTime; win32filename.nFileSizeLow = winFindData.nFileSizeLow; win32filename.nFileSizeHigh = winFindData.nFileSizeHigh; win32filename.dwReserved0 = winFindData.dwReserved0; win32filename.dwReserved1 = winFindData.dwReserved1; strcpy((char *)win32filename.cFileName, winFindData.cFileName); strcpy((char *)win32filename.cAlternateFileName, winFindData.cAlternateFileName); #else win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_NORMAL); if (S_ISDIR(statbuf.st_mode)) win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_DIRECTORY); win32filename.ftCreationTime.dwLowDateTime = Swap32IfBE(statbuf.st_ctime); /* Intel Order */ win32filename.ftCreationTime.dwHighDateTime = 0; win32filename.ftLastAccessTime.dwLowDateTime = Swap32IfBE(statbuf.st_atime); /* Intel Order */ win32filename.ftLastAccessTime.dwHighDateTime = 0; win32filename.ftLastWriteTime.dwLowDateTime = Swap32IfBE(statbuf.st_mtime); /* Intel Order */ win32filename.ftLastWriteTime.dwHighDateTime = 0; win32filename.nFileSizeLow = Swap32IfBE(statbuf.st_size); /* Intel Order */ win32filename.nFileSizeHigh = 0; win32filename.dwReserved0 = 0; win32filename.dwReserved1 = 0; /* If this had the full path, we would need to translate to DOS format ("C:\") */ /* rfbFilenameTranslate2DOS(cl, retfilename, win32filename.cFileName); */ strcpy((char *)win32filename.cFileName, direntp->d_name); #endif /* Do not show hidden files (but show how to move up the tree) */ if ((strcmp((char *)win32filename.cFileName, "..")==0) || (win32filename.cFileName[0]!='.')) { nOptLen = sizeof(RFB_FIND_DATA) - MAX_PATH - 14 + strlen((char *)win32filename.cFileName); /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: Sending \"%s\"\n", (char *)win32filename.cFileName); */ if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, nOptLen, (char *)&win32filename)==FALSE) { #ifdef WIN32 FindClose(findHandle); #else closedir(dirp); #endif return FALSE; } } } #ifdef WIN32 if (FindNextFileA(findHandle, &winFindData) == 0) { FindClose(findHandle); findHandle = INVALID_HANDLE_VALUE; } #endif } #ifdef WIN32 if (findHandle != INVALID_HANDLE_VALUE) { FindClose(findHandle); } #else closedir(dirp); #endif /* End of the transfer */ return rfbSendFileTransferMessage(cl, rfbDirPacket, 0, 0, 0, NULL); } char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length) { char *buffer=NULL; int n=0; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, NULL); /* We later alloc length+1, which might wrap around on 32-bit systems if length equals 0XFFFFFFFF, i.e. SIZE_MAX for 32-bit systems. On 64-bit systems, a length of 0XFFFFFFFF will safely be allocated since this check will never trigger and malloc() can digest length+1 without problems as length is a uint32_t. We also later pass length to rfbReadExact() that expects a signed int type and that might wrap on platforms with a 32-bit int type if length is bigger than 0X7FFFFFFF. */ if(length == SIZE_MAX || length > INT_MAX) { rfbErr("rfbProcessFileTransferReadBuffer: too big file transfer length requested: %u", (unsigned int)length); rfbCloseClient(cl); return NULL; } if (length>0) { buffer=malloc((size_t)length+1); if (buffer!=NULL) { if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransferReadBuffer: read"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return NULL; } /* Null Terminate */ buffer[length]=0; } } return buffer; } rfbBool rfbSendFileTransferChunk(rfbClientPtr cl) { /* Allocate buffer for compression */ unsigned char readBuf[sz_rfbBlockSize]; int bytesRead=0; int retval=0; fd_set wfds; struct timeval tv; int n; #ifdef LIBVNCSERVER_HAVE_LIBZ unsigned char compBuf[sz_rfbBlockSize + 1024]; unsigned long nMaxCompSize = sizeof(compBuf); int nRetC = 0; #endif /* * Don't close the client if we get into this one because * it is called from many places to service file transfers. * Note that permitFileTransfer is checked first. */ if (cl->screen->permitFileTransfer != TRUE || (cl->screen->getFileTransferPermission != NULL && cl->screen->getFileTransferPermission(cl) != TRUE)) { return TRUE; } /* If not sending, or no file open... Return as if we sent something! */ if ((cl->fileTransfer.fd!=-1) && (cl->fileTransfer.sending==1)) { FD_ZERO(&wfds); FD_SET(cl->sock, &wfds); /* return immediately */ tv.tv_sec = 0; tv.tv_usec = 0; n = select(cl->sock + 1, NULL, &wfds, NULL, &tv); if (n<0) { #ifdef WIN32 errno=WSAGetLastError(); #endif rfbLog("rfbSendFileTransferChunk() select failed: %s\n", strerror(errno)); } /* We have space on the transmit queue */ if (n > 0) { bytesRead = read(cl->fileTransfer.fd, readBuf, sz_rfbBlockSize); switch (bytesRead) { case 0: /* rfbLog("rfbSendFileTransferChunk(): End-Of-File Encountered\n"); */ retval = rfbSendFileTransferMessage(cl, rfbEndOfFile, 0, 0, 0, NULL); close(cl->fileTransfer.fd); cl->fileTransfer.fd = -1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; return retval; case -1: /* TODO : send an error msg to the client... */ #ifdef WIN32 errno=WSAGetLastError(); #endif rfbLog("rfbSendFileTransferChunk(): %s\n",strerror(errno)); retval = rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, 0, 0, NULL); close(cl->fileTransfer.fd); cl->fileTransfer.fd = -1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; return retval; default: /* rfbLog("rfbSendFileTransferChunk(): Read %d bytes\n", bytesRead); */ if (!cl->fileTransfer.compressionEnabled) return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); else { #ifdef LIBVNCSERVER_HAVE_LIBZ nRetC = compress(compBuf, &nMaxCompSize, readBuf, bytesRead); /* rfbLog("Compressed the packet from %d -> %d bytes\n", nMaxCompSize, bytesRead); */ if ((nRetC==0) && (nMaxCompSize<bytesRead)) return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 1, nMaxCompSize, (char *)compBuf); else return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); #else /* We do not support compression of the data stream */ return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); #endif } } } } return TRUE; } rfbBool rfbProcessFileTransfer(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length) { char *buffer=NULL, *p=NULL; int retval=0; char filename1[MAX_PATH]; char filename2[MAX_PATH]; char szFileTime[MAX_PATH]; struct stat statbuf; uint32_t sizeHtmp=0; int n=0; char timespec[64]; #ifdef LIBVNCSERVER_HAVE_LIBZ unsigned char compBuff[sz_rfbBlockSize]; unsigned long nRawBytes = sz_rfbBlockSize; int nRet = 0; #endif FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* rfbLog("rfbProcessFileTransfer(%dtype, %dparam, %dsize, %dlen)\n", contentType, contentParam, size, length); */ switch (contentType) { case rfbDirContentRequest: switch (contentParam) { case rfbRDrivesList: /* Client requests the List of Local Drives */ /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDrivesList:\n"); */ /* Format when filled : "C:\<NULL>D:\<NULL>....Z:\<NULL><NULL> * * We replace the "\" char following the drive letter and ":" * with a char corresponding to the type of drive * We obtain something like "C:l<NULL>D:c<NULL>....Z:n\<NULL><NULL>" * Isn't it ugly ? * DRIVE_FIXED = 'l' (local?) * DRIVE_REMOVABLE = 'f' (floppy?) * DRIVE_CDROM = 'c' * DRIVE_REMOTE = 'n' */ /* in unix, there are no 'drives' (We could list mount points though) * We fake the root as a "C:" for the Winblows users */ filename2[0]='C'; filename2[1]=':'; filename2[2]='l'; filename2[3]=0; filename2[4]=0; retval = rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADrivesList, 0, 5, filename2); if (buffer!=NULL) free(buffer); return retval; break; case rfbRDirContent: /* Client requests the content of a directory */ /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; retval = rfbSendDirContent(cl, length, buffer); if (buffer!=NULL) free(buffer); return retval; } break; case rfbDirPacket: rfbLog("rfbProcessFileTransfer() rfbDirPacket\n"); break; case rfbFileAcceptHeader: rfbLog("rfbProcessFileTransfer() rfbFileAcceptHeader\n"); break; case rfbCommandReturn: rfbLog("rfbProcessFileTransfer() rfbCommandReturn\n"); break; case rfbFileChecksums: /* Destination file already exists - the viewer sends the checksums */ rfbLog("rfbProcessFileTransfer() rfbFileChecksums\n"); break; case rfbFileTransferAccess: rfbLog("rfbProcessFileTransfer() rfbFileTransferAccess\n"); break; /* * sending from the server to the viewer */ case rfbFileTransferRequest: /* rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest:\n"); */ /* add some space to the end of the buffer as we will be adding a timespec to it */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; /* The client requests a File */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; cl->fileTransfer.fd=open(filename1, O_RDONLY, 0744); /* */ if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\") Open: %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), cl->fileTransfer.fd); if (cl->fileTransfer.fd!=-1) { if (fstat(cl->fileTransfer.fd, &statbuf)!=0) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; } else { /* Add the File Time Stamp to the filename */ strftime(timespec, sizeof(timespec), "%m/%d/%Y %H:%M",gmtime(&statbuf.st_ctime)); buffer=realloc(buffer, length + strlen(timespec) + 2); /* comma, and Null term */ if (buffer==NULL) { rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest: Failed to malloc %d bytes\n", length + strlen(timespec) + 2); return FALSE; } strcat(buffer,","); strcat(buffer, timespec); length = strlen(buffer); if (DB) rfbLog("rfbProcessFileTransfer() buffer is now: \"%s\"\n", buffer); } } /* The viewer supports compression if size==1 */ cl->fileTransfer.compressionEnabled = (size==1); /* rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\")%s\n", buffer, filename1, (size==1?" <Compression Enabled>":"")); */ /* File Size in bytes, 0xFFFFFFFF (-1) means error */ retval = rfbSendFileTransferMessage(cl, rfbFileHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : statbuf.st_size), length, buffer); if (cl->fileTransfer.fd==-1) { if (buffer!=NULL) free(buffer); return retval; } /* setup filetransfer stuff */ cl->fileTransfer.fileSize = statbuf.st_size; cl->fileTransfer.numPackets = statbuf.st_size / sz_rfbBlockSize; cl->fileTransfer.receiving = 0; cl->fileTransfer.sending = 0; /* set when we receive a rfbFileHeader: */ /* TODO: finish 64-bit file size support */ sizeHtmp = 0; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&sizeHtmp, 4) < 0) { rfbLogPerror("rfbProcessFileTransfer: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); if (buffer!=NULL) free(buffer); return FALSE; } UNLOCK(cl->sendMutex); break; case rfbFileHeader: /* Destination file (viewer side) is ready for reception (size > 0) or not (size = -1) */ if (size==-1) { rfbLog("rfbProcessFileTransfer() rfbFileHeader (error, aborting)\n"); close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; return TRUE; } /* rfbLog("rfbProcessFileTransfer() rfbFileHeader (%d bytes of a file)\n", size); */ /* Starts the transfer! */ cl->fileTransfer.sending=1; return rfbSendFileTransferChunk(cl); break; /* * sending from the viewer to the server */ case rfbFileTransferOffer: /* client is sending a file to us */ /* buffer contains full path name (plus FileTime) */ /* size contains size of the file */ /* rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; /* Parse the FileTime */ p = strrchr(buffer, ','); if (p!=NULL) { *p = '\0'; strncpy(szFileTime, p+1, sizeof(szFileTime)); szFileTime[sizeof(szFileTime)-1] = '\x00'; /* ensure NULL terminating byte is present, even if copy overflowed */ } else szFileTime[0]=0; /* Need to read in sizeHtmp */ if ((n = rfbReadExact(cl, (char *)&sizeHtmp, 4)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransfer: read sizeHtmp"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return FALSE; } sizeHtmp = Swap32IfLE(sizeHtmp); if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; /* If the file exists... We can send a rfbFileChecksums back to the client before we send an rfbFileAcceptHeader */ /* TODO: Delta Transfer */ cl->fileTransfer.fd=open(filename1, O_CREAT|O_WRONLY|O_TRUNC, 0744); if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer(\"%s\"->\"%s\") %s %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), (cl->fileTransfer.fd==-1?strerror(errno):""), cl->fileTransfer.fd); /* */ /* File Size in bytes, 0xFFFFFFFF (-1) means error */ retval = rfbSendFileTransferMessage(cl, rfbFileAcceptHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : 0), length, buffer); if (cl->fileTransfer.fd==-1) { free(buffer); return retval; } /* setup filetransfer stuff */ cl->fileTransfer.fileSize = size; cl->fileTransfer.numPackets = size / sz_rfbBlockSize; cl->fileTransfer.receiving = 1; cl->fileTransfer.sending = 0; break; case rfbFilePacket: /* rfbLog("rfbProcessFileTransfer() rfbFilePacket:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; if (cl->fileTransfer.fd!=-1) { /* buffer contains the contents of the file */ if (size==0) retval=write(cl->fileTransfer.fd, buffer, length); else { #ifdef LIBVNCSERVER_HAVE_LIBZ /* compressed packet */ nRet = uncompress(compBuff,&nRawBytes,(const unsigned char*)buffer, length); if(nRet == Z_OK) retval=write(cl->fileTransfer.fd, (char*)compBuff, nRawBytes); else retval = -1; #else /* Write the file out as received... */ retval=write(cl->fileTransfer.fd, buffer, length); #endif } if (retval==-1) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; } } break; case rfbEndOfFile: if (DB) rfbLog("rfbProcessFileTransfer() rfbEndOfFile\n"); /* */ if (cl->fileTransfer.fd!=-1) close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; break; case rfbAbortFileTransfer: if (DB) rfbLog("rfbProcessFileTransfer() rfbAbortFileTransfer\n"); /* */ if (cl->fileTransfer.fd!=-1) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; } else { /* We use this message for FileTransfer rights (<=RC18 versions) * The client asks for FileTransfer permission */ if (contentParam == 0) { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED! (Client Version <=RC18)\n"); /* Old method for FileTransfer handshake perimssion (<=RC18) (Deny it)*/ return rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, -1, 0, ""); } /* New method is allowed */ if (cl->screen->getFileTransferPermission!=NULL) { if (cl->screen->getFileTransferPermission(cl)==TRUE) { rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */ } else { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* Deny */ } } else { if (cl->screen->permitFileTransfer) { rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */ } else { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED by default!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* DEFAULT: DENY (for security) */ } } } break; case rfbCommand: /* rfbLog("rfbProcessFileTransfer() rfbCommand:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; switch (contentParam) { case rfbCDirCreate: /* Client requests the creation of a directory */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; retval = mkdir(filename1, 0755); if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCDirCreate(\"%s\"->\"%s\") %s\n", buffer, filename1, (retval==-1?"Failed":"Success")); /* */ retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbADirCreate, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; case rfbCFileDelete: /* Client requests the deletion of a file */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; if (stat(filename1,&statbuf)==0) { if (S_ISDIR(statbuf.st_mode)) retval = rmdir(filename1); else retval = unlink(filename1); } else retval=-1; retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileDelete, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; case rfbCFileRename: /* Client requests the Renaming of a file/directory */ p = strrchr(buffer, '*'); if (p != NULL) { /* Split into 2 filenames ('*' is a seperator) */ *p = '\0'; if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; if (!rfbFilenameTranslate2UNIX(cl, p+1, filename2, sizeof(filename2))) goto fail; retval = rename(filename1,filename2); if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCFileRename(\"%s\"->\"%s\" -->> \"%s\"->\"%s\") %s\n", buffer, filename1, p+1, filename2, (retval==-1?"Failed":"Success")); /* */ /* Restore the buffer so the reply is good */ *p = '*'; retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileRename, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; } break; } break; } /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return TRUE; fail: if (buffer!=NULL) free(buffer); return FALSE; } /* * rfbProcessClientNormalMessage is called when the client has sent a normal * protocol message. */ static void rfbProcessClientNormalMessage(rfbClientPtr cl) { int n=0; rfbClientToServerMsg msg; char *str; int i; uint32_t enc=0; uint32_t lastPreferredEncoding = -1; char encBuf[64]; char encBuf2[64]; rfbExtDesktopScreen *extDesktopScreens; rfbClientIteratorPtr iterator; rfbClientPtr clp; if ((n = rfbReadExact(cl, (char *)&msg, 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } switch (msg.type) { case rfbSetPixelFormat: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetPixelFormatMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } cl->format.bitsPerPixel = msg.spf.format.bitsPerPixel; cl->format.depth = msg.spf.format.depth; cl->format.bigEndian = (msg.spf.format.bigEndian ? TRUE : FALSE); cl->format.trueColour = (msg.spf.format.trueColour ? TRUE : FALSE); cl->format.redMax = Swap16IfLE(msg.spf.format.redMax); cl->format.greenMax = Swap16IfLE(msg.spf.format.greenMax); cl->format.blueMax = Swap16IfLE(msg.spf.format.blueMax); cl->format.redShift = msg.spf.format.redShift; cl->format.greenShift = msg.spf.format.greenShift; cl->format.blueShift = msg.spf.format.blueShift; cl->readyForSetColourMapEntries = TRUE; cl->screen->setTranslateFunction(cl); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg); return; case rfbFixColourMapEntries: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFixColourMapEntriesMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg); rfbLog("rfbProcessClientNormalMessage: %s", "FixColourMapEntries unsupported\n"); rfbCloseClient(cl); return; /* NOTE: Some clients send us a set of encodings (ie: PointerPos) designed to enable/disable features... * We may want to look into this... * Example: * case rfbEncodingXCursor: * cl->enableCursorShapeUpdates = TRUE; * * Currently: cl->enableCursorShapeUpdates can *never* be turned off... */ case rfbSetEncodings: { if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetEncodingsMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.se.nEncodings = Swap16IfLE(msg.se.nEncodings); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4),sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4)); /* * UltraVNC Client has the ability to adapt to changing network environments * So, let's give it a change to tell us what it wants now! */ if (cl->preferredEncoding!=-1) lastPreferredEncoding = cl->preferredEncoding; /* Reset all flags to defaults (allows us to switch between PointerPos and Server Drawn Cursors) */ cl->preferredEncoding=-1; cl->useCopyRect = FALSE; cl->useNewFBSize = FALSE; cl->useExtDesktopSize = FALSE; cl->cursorWasChanged = FALSE; cl->useRichCursorEncoding = FALSE; cl->enableCursorPosUpdates = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableLastRectEncoding = FALSE; cl->enableKeyboardLedState = FALSE; cl->enableSupportedMessages = FALSE; cl->enableSupportedEncodings = FALSE; cl->enableServerIdentity = FALSE; #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) cl->tightQualityLevel = -1; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP; cl->turboQualityLevel = -1; #endif #endif for (i = 0; i < msg.se.nEncodings; i++) { if ((n = rfbReadExact(cl, (char *)&enc, 4)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } enc = Swap32IfLE(enc); switch (enc) { case rfbEncodingCopyRect: cl->useCopyRect = TRUE; break; case rfbEncodingRaw: case rfbEncodingRRE: case rfbEncodingCoRRE: case rfbEncodingHextile: case rfbEncodingUltra: #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: case rfbEncodingZRLE: case rfbEncodingZYWRLE: #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG case rfbEncodingTightPng: #endif /* The first supported encoding is the 'preferred' encoding */ if (cl->preferredEncoding == -1) cl->preferredEncoding = enc; break; case rfbEncodingXCursor: if(!cl->screen->dontConvertRichCursorToXCursor) { rfbLog("Enabling X-style cursor updates for client %s\n", cl->host); /* if cursor was drawn, hide the cursor */ if(!cl->enableCursorShapeUpdates) rfbRedrawAfterHideCursor(cl,NULL); cl->enableCursorShapeUpdates = TRUE; cl->cursorWasChanged = TRUE; } break; case rfbEncodingRichCursor: rfbLog("Enabling full-color cursor updates for client %s\n", cl->host); /* if cursor was drawn, hide the cursor */ if(!cl->enableCursorShapeUpdates) rfbRedrawAfterHideCursor(cl,NULL); cl->enableCursorShapeUpdates = TRUE; cl->useRichCursorEncoding = TRUE; cl->cursorWasChanged = TRUE; break; case rfbEncodingPointerPos: if (!cl->enableCursorPosUpdates) { rfbLog("Enabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = TRUE; cl->cursorWasMoved = TRUE; } break; case rfbEncodingLastRect: if (!cl->enableLastRectEncoding) { rfbLog("Enabling LastRect protocol extension for client " "%s\n", cl->host); cl->enableLastRectEncoding = TRUE; } break; case rfbEncodingNewFBSize: if (!cl->useNewFBSize) { rfbLog("Enabling NewFBSize protocol extension for client " "%s\n", cl->host); cl->useNewFBSize = TRUE; } break; case rfbEncodingExtDesktopSize: if (!cl->useExtDesktopSize) { rfbLog("Enabling ExtDesktopSize protocol extension for client " "%s\n", cl->host); cl->useExtDesktopSize = TRUE; cl->useNewFBSize = TRUE; } break; case rfbEncodingKeyboardLedState: if (!cl->enableKeyboardLedState) { rfbLog("Enabling KeyboardLedState protocol extension for client " "%s\n", cl->host); cl->enableKeyboardLedState = TRUE; } break; case rfbEncodingSupportedMessages: if (!cl->enableSupportedMessages) { rfbLog("Enabling SupportedMessages protocol extension for client " "%s\n", cl->host); cl->enableSupportedMessages = TRUE; } break; case rfbEncodingSupportedEncodings: if (!cl->enableSupportedEncodings) { rfbLog("Enabling SupportedEncodings protocol extension for client " "%s\n", cl->host); cl->enableSupportedEncodings = TRUE; } break; case rfbEncodingServerIdentity: if (!cl->enableServerIdentity) { rfbLog("Enabling ServerIdentity protocol extension for client " "%s\n", cl->host); cl->enableServerIdentity = TRUE; } break; case rfbEncodingXvp: if (cl->screen->xvpHook) { rfbLog("Enabling Xvp protocol extension for client " "%s\n", cl->host); if (!rfbSendXvp(cl, 1, rfbXvp_Init)) { rfbCloseClient(cl); return; } } break; default: #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) if ( enc >= (uint32_t)rfbEncodingCompressLevel0 && enc <= (uint32_t)rfbEncodingCompressLevel9 ) { cl->zlibCompressLevel = enc & 0x0F; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = enc & 0x0F; rfbLog("Using compression level %d for client %s\n", cl->tightCompressLevel, cl->host); #endif } else if ( enc >= (uint32_t)rfbEncodingQualityLevel0 && enc <= (uint32_t)rfbEncodingQualityLevel9 ) { cl->tightQualityLevel = enc & 0x0F; rfbLog("Using image quality level %d for client %s\n", cl->tightQualityLevel, cl->host); #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->turboQualityLevel = tight2turbo_qual[enc & 0x0F]; cl->turboSubsampLevel = tight2turbo_subsamp[enc & 0x0F]; rfbLog("Using JPEG subsampling %d, Q%d for client %s\n", cl->turboSubsampLevel, cl->turboQualityLevel, cl->host); } else if ( enc >= (uint32_t)rfbEncodingFineQualityLevel0 + 1 && enc <= (uint32_t)rfbEncodingFineQualityLevel100 ) { cl->turboQualityLevel = enc & 0xFF; rfbLog("Using fine quality level %d for client %s\n", cl->turboQualityLevel, cl->host); } else if ( enc >= (uint32_t)rfbEncodingSubsamp1X && enc <= (uint32_t)rfbEncodingSubsampGray ) { cl->turboSubsampLevel = enc & 0xFF; rfbLog("Using subsampling level %d for client %s\n", cl->turboSubsampLevel, cl->host); #endif } else #endif { rfbExtensionData* e; for(e = cl->extensions; e;) { rfbExtensionData* next = e->next; if(e->extension->enablePseudoEncoding && e->extension->enablePseudoEncoding(cl, &e->data, (int)enc)) /* ext handles this encoding */ break; e = next; } if(e == NULL) { rfbBool handled = FALSE; /* if the pseudo encoding is not handled by the enabled extensions, search through all extensions. */ rfbProtocolExtension* e; for(e = rfbGetExtensionIterator(); e;) { int* encs = e->pseudoEncodings; while(encs && *encs!=0) { if(*encs==(int)enc) { void* data = NULL; if(!e->enablePseudoEncoding(cl, &data, (int)enc)) { rfbLog("Installed extension pretends to handle pseudo encoding 0x%x, but does not!\n",(int)enc); } else { rfbEnableExtension(cl, e, data); handled = TRUE; e = NULL; break; } } encs++; } if(e) e = e->next; } rfbReleaseExtensionIterator(); if(!handled) rfbLog("rfbProcessClientNormalMessage: " "ignoring unsupported encoding type %s\n", encodingName(enc,encBuf,sizeof(encBuf))); } } } } if (cl->preferredEncoding == -1) { if (lastPreferredEncoding==-1) { cl->preferredEncoding = rfbEncodingRaw; rfbLog("Defaulting to %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } else { cl->preferredEncoding = lastPreferredEncoding; rfbLog("Sticking with %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } } else { if (lastPreferredEncoding==-1) { rfbLog("Using %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } else { rfbLog("Switching from %s to %s Encoding for client %s\n", encodingName(lastPreferredEncoding,encBuf2,sizeof(encBuf2)), encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)), cl->host); } } if (cl->enableCursorPosUpdates && !cl->enableCursorShapeUpdates) { rfbLog("Disabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = FALSE; } return; } case rfbFramebufferUpdateRequest: { sraRegionPtr tmpRegion; if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFramebufferUpdateRequestMsg-1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbFramebufferUpdateRequestMsg,sz_rfbFramebufferUpdateRequestMsg); /* The values come in based on the scaled screen, we need to convert them to * values based on the main screen's coordinate system */ if(!rectSwapIfLEAndClip(&msg.fur.x,&msg.fur.y,&msg.fur.w,&msg.fur.h,cl)) { rfbLog("Warning, ignoring rfbFramebufferUpdateRequest: %dXx%dY-%dWx%dH\n",msg.fur.x, msg.fur.y, msg.fur.w, msg.fur.h); return; } if (cl->clientFramebufferUpdateRequestHook) cl->clientFramebufferUpdateRequestHook(cl, &msg.fur); tmpRegion = sraRgnCreateRect(msg.fur.x, msg.fur.y, msg.fur.x+msg.fur.w, msg.fur.y+msg.fur.h); LOCK(cl->updateMutex); sraRgnOr(cl->requestedRegion,tmpRegion); if (!cl->readyForSetColourMapEntries) { /* client hasn't sent a SetPixelFormat so is using server's */ cl->readyForSetColourMapEntries = TRUE; if (!cl->format.trueColour) { if (!rfbSetClientColourMap(cl, 0, 0)) { sraRgnDestroy(tmpRegion); TSIGNAL(cl->updateCond); UNLOCK(cl->updateMutex); return; } } } if (!msg.fur.incremental) { sraRgnOr(cl->modifiedRegion,tmpRegion); sraRgnSubtract(cl->copyRegion,tmpRegion); if (cl->useExtDesktopSize) cl->newFBSizePending = TRUE; } TSIGNAL(cl->updateCond); UNLOCK(cl->updateMutex); sraRgnDestroy(tmpRegion); return; } case rfbKeyEvent: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbKeyEventMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbKeyEventMsg, sz_rfbKeyEventMsg); if(!cl->viewOnly) { cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl); } return; case rfbPointerEvent: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbPointerEventMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbPointerEventMsg, sz_rfbPointerEventMsg); if (cl->screen->pointerClient && cl->screen->pointerClient != cl) return; if (msg.pe.buttonMask == 0) cl->screen->pointerClient = NULL; else cl->screen->pointerClient = cl; if(!cl->viewOnly) { if (msg.pe.buttonMask != cl->lastPtrButtons || cl->screen->deferPtrUpdateTime == 0) { cl->screen->ptrAddEvent(msg.pe.buttonMask, ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)), ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)), cl); cl->lastPtrButtons = msg.pe.buttonMask; } else { cl->lastPtrX = ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)); cl->lastPtrY = ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)); cl->lastPtrButtons = msg.pe.buttonMask; } } return; case rfbFileTransfer: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFileTransferMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.ft.size = Swap32IfLE(msg.ft.size); msg.ft.length = Swap32IfLE(msg.ft.length); /* record statistics in rfbProcessFileTransfer as length is filled with garbage when it is not valid */ rfbProcessFileTransfer(cl, msg.ft.contentType, msg.ft.contentParam, msg.ft.size, msg.ft.length); return; case rfbSetSW: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetSWMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.sw.x = Swap16IfLE(msg.sw.x); msg.sw.y = Swap16IfLE(msg.sw.y); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetSWMsg, sz_rfbSetSWMsg); /* msg.sw.status is not initialized in the ultraVNC viewer and contains random numbers (why???) */ rfbLog("Received a rfbSetSingleWindow(%d x, %d y)\n", msg.sw.x, msg.sw.y); if (cl->screen->setSingleWindow!=NULL) cl->screen->setSingleWindow(cl, msg.sw.x, msg.sw.y); return; case rfbSetServerInput: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetServerInputMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetServerInputMsg, sz_rfbSetServerInputMsg); /* msg.sim.pad is not initialized in the ultraVNC viewer and contains random numbers (why???) */ /* msg.sim.pad = Swap16IfLE(msg.sim.pad); */ rfbLog("Received a rfbSetServerInput(%d status)\n", msg.sim.status); if (cl->screen->setServerInput!=NULL) cl->screen->setServerInput(cl, msg.sim.status); return; case rfbTextChat: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbTextChatMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.tc.pad2 = Swap16IfLE(msg.tc.pad2); msg.tc.length = Swap32IfLE(msg.tc.length); switch (msg.tc.length) { case rfbTextChatOpen: case rfbTextChatClose: case rfbTextChatFinished: /* commands do not have text following */ /* Why couldn't they have used the pad byte??? */ str=NULL; rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg, sz_rfbTextChatMsg); break; default: if ((msg.tc.length>0) && (msg.tc.length<rfbTextMaxSize)) { str = (char *)malloc(msg.tc.length); if (str==NULL) { rfbLog("Unable to malloc %d bytes for a TextChat Message\n", msg.tc.length); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, str, msg.tc.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg+msg.tc.length, sz_rfbTextChatMsg+msg.tc.length); } else { /* This should never happen */ rfbLog("client sent us a Text Message that is too big %d>%d\n", msg.tc.length, rfbTextMaxSize); rfbCloseClient(cl); return; } } /* Note: length can be commands: rfbTextChatOpen, rfbTextChatClose, and rfbTextChatFinished * at which point, the str is NULL (as it is not sent) */ if (cl->screen->setTextChat!=NULL) cl->screen->setTextChat(cl, msg.tc.length, str); free(str); return; case rfbClientCutText: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbClientCutTextMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.cct.length = Swap32IfLE(msg.cct.length); /* uint32_t input is passed to malloc()'s size_t argument, * to rfbReadExact()'s int argument, to rfbStatRecordMessageRcvd()'s int * argument increased of sz_rfbClientCutTextMsg, and to setXCutText()'s int * argument. Here we impose a limit of 1 MB so that the value fits * into all of the types to prevent from misinterpretation and thus * from accessing uninitialized memory (CVE-2018-7225) and also to * prevent from a denial-of-service by allocating too much memory in * the server. */ if (msg.cct.length > 1<<20) { rfbLog("rfbClientCutText: too big cut text length requested: %u B > 1 MB\n", (unsigned int)msg.cct.length); rfbCloseClient(cl); return; } /* Allow zero-length client cut text. */ str = (char *)calloc(msg.cct.length ? msg.cct.length : 1, 1); if (str == NULL) { rfbLogPerror("rfbProcessClientNormalMessage: not enough memory"); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, str, msg.cct.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbClientCutTextMsg+msg.cct.length, sz_rfbClientCutTextMsg+msg.cct.length); if(!cl->viewOnly) { cl->screen->setXCutText(str, msg.cct.length, cl); } free(str); return; case rfbPalmVNCSetScaleFactor: cl->PalmVNC = TRUE; if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetScaleMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.ssc.scale == 0) { rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg); rfbLog("rfbSetScale(%d)\n", msg.ssc.scale); rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale); rfbSendNewScaleSize(cl); return; case rfbSetScale: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetScaleMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.ssc.scale == 0) { rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg); rfbLog("rfbSetScale(%d)\n", msg.ssc.scale); rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale); rfbSendNewScaleSize(cl); return; case rfbXvp: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbXvpMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbXvpMsg, sz_rfbXvpMsg); /* only version when is defined, so echo back a fail */ if(msg.xvp.version != 1) { rfbSendXvp(cl, msg.xvp.version, rfbXvp_Fail); } else { /* if the hook exists and fails, send a fail msg */ if(cl->screen->xvpHook && !cl->screen->xvpHook(cl, msg.xvp.version, msg.xvp.code)) rfbSendXvp(cl, 1, rfbXvp_Fail); } return; case rfbSetDesktopSize: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetDesktopSizeMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.sdm.numberOfScreens == 0) { rfbLog("Ignoring setDesktopSize message from client that defines zero screens\n"); return; } extDesktopScreens = (rfbExtDesktopScreen *) malloc(msg.sdm.numberOfScreens * sz_rfbExtDesktopScreen); if (extDesktopScreens == NULL) { rfbLogPerror("rfbProcessClientNormalMessage: not enough memory"); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, ((char *)extDesktopScreens), msg.sdm.numberOfScreens * sz_rfbExtDesktopScreen)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(extDesktopScreens); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetDesktopSizeMsg + msg.sdm.numberOfScreens * sz_rfbExtDesktopScreen, sz_rfbSetDesktopSizeMsg + msg.sdm.numberOfScreens * sz_rfbExtDesktopScreen); for (i=0; i < msg.sdm.numberOfScreens; i++) { extDesktopScreens[i].id = Swap32IfLE(extDesktopScreens[i].id); extDesktopScreens[i].x = Swap16IfLE(extDesktopScreens[i].x); extDesktopScreens[i].y = Swap16IfLE(extDesktopScreens[i].y); extDesktopScreens[i].width = Swap16IfLE(extDesktopScreens[i].width); extDesktopScreens[i].height = Swap16IfLE(extDesktopScreens[i].height); extDesktopScreens[i].flags = Swap32IfLE(extDesktopScreens[i].flags); } msg.sdm.width = Swap16IfLE(msg.sdm.width); msg.sdm.height = Swap16IfLE(msg.sdm.height); rfbLog("Client requested resolution change to (%dx%d)\n", msg.sdm.width, msg.sdm.height); cl->requestedDesktopSizeChange = rfbExtDesktopSize_ClientRequestedChange; cl->lastDesktopSizeChangeError = cl->screen->setDesktopSizeHook(msg.sdm.width, msg.sdm.height, msg.sdm.numberOfScreens, extDesktopScreens, cl); if (cl->lastDesktopSizeChangeError == 0) { /* Let other clients know it was this client that requested the change */ iterator = rfbGetClientIterator(cl->screen); while ((clp = rfbClientIteratorNext(iterator)) != NULL) { LOCK(clp->updateMutex); if (clp != cl) clp->requestedDesktopSizeChange = rfbExtDesktopSize_OtherClientRequestedChange; UNLOCK(clp->updateMutex); } } else { /* Force ExtendedDesktopSize message to be sent with result code in case of error. (In case of success, it is delayed until the new framebuffer is created) */ cl->newFBSizePending = TRUE; } free(extDesktopScreens); return; default: { rfbExtensionData *e,*next; for(e=cl->extensions; e;) { next = e->next; if(e->extension->handleMessage && e->extension->handleMessage(cl, e->data, &msg)) { rfbStatRecordMessageRcvd(cl, msg.type, 0, 0); /* Extension should handle this */ return; } e = next; } rfbLog("rfbProcessClientNormalMessage: unknown message type %d\n", msg.type); rfbLog(" ... closing connection\n"); rfbCloseClient(cl); return; } } } /* * rfbSendFramebufferUpdate - send the currently pending framebuffer update to * the RFB client. * givenUpdateRegion is not changed. */ rfbBool rfbSendFramebufferUpdate(rfbClientPtr cl, sraRegionPtr givenUpdateRegion) { sraRectangleIterator* i=NULL; sraRect rect; int nUpdateRegionRects; rfbFramebufferUpdateMsg *fu = (rfbFramebufferUpdateMsg *)cl->updateBuf; sraRegionPtr updateRegion,updateCopyRegion,tmpRegion; int dx, dy; rfbBool sendCursorShape = FALSE; rfbBool sendCursorPos = FALSE; rfbBool sendKeyboardLedState = FALSE; rfbBool sendSupportedMessages = FALSE; rfbBool sendSupportedEncodings = FALSE; rfbBool sendServerIdentity = FALSE; rfbBool result = TRUE; if(cl->screen->displayHook) cl->screen->displayHook(cl); /* * If framebuffer size was changed and the client supports NewFBSize * encoding, just send NewFBSize marker and return. */ if (cl->useNewFBSize && cl->newFBSizePending) { LOCK(cl->updateMutex); cl->newFBSizePending = FALSE; UNLOCK(cl->updateMutex); fu->type = rfbFramebufferUpdate; fu->nRects = Swap16IfLE(1); cl->ublen = sz_rfbFramebufferUpdateMsg; if (cl->useExtDesktopSize) { if (!rfbSendExtDesktopSize(cl, cl->scaledScreen->width, cl->scaledScreen->height)) { if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, FALSE); return FALSE; } } else if (!rfbSendNewFBSize(cl, cl->scaledScreen->width, cl->scaledScreen->height)) { if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, FALSE); return FALSE; } result = rfbSendUpdateBuf(cl); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, result); return result; } /* * If this client understands cursor shape updates, cursor should be * removed from the framebuffer. Otherwise, make sure it's put up. */ if (cl->enableCursorShapeUpdates) { if (cl->cursorWasChanged && cl->readyForSetColourMapEntries) sendCursorShape = TRUE; } /* * Do we plan to send cursor position update? */ if (cl->enableCursorPosUpdates && cl->cursorWasMoved) sendCursorPos = TRUE; /* * Do we plan to send a keyboard state update? */ if ((cl->enableKeyboardLedState) && (cl->screen->getKeyboardLedStateHook!=NULL)) { int x; x=cl->screen->getKeyboardLedStateHook(cl->screen); if (x!=cl->lastKeyboardLedState) { sendKeyboardLedState = TRUE; cl->lastKeyboardLedState=x; } } /* * Do we plan to send a rfbEncodingSupportedMessages? */ if (cl->enableSupportedMessages) { sendSupportedMessages = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableSupportedMessages = FALSE; } /* * Do we plan to send a rfbEncodingSupportedEncodings? */ if (cl->enableSupportedEncodings) { sendSupportedEncodings = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableSupportedEncodings = FALSE; } /* * Do we plan to send a rfbEncodingServerIdentity? */ if (cl->enableServerIdentity) { sendServerIdentity = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableServerIdentity = FALSE; } LOCK(cl->updateMutex); /* * The modifiedRegion may overlap the destination copyRegion. We remove * any overlapping bits from the copyRegion (since they'd only be * overwritten anyway). */ sraRgnSubtract(cl->copyRegion,cl->modifiedRegion); /* * The client is interested in the region requestedRegion. The region * which should be updated now is the intersection of requestedRegion * and the union of modifiedRegion and copyRegion. If it's empty then * no update is needed. */ updateRegion = sraRgnCreateRgn(givenUpdateRegion); if(cl->screen->progressiveSliceHeight>0) { int height=cl->screen->progressiveSliceHeight, y=cl->progressiveSliceY; sraRegionPtr bbox=sraRgnBBox(updateRegion); sraRect rect; if(sraRgnPopRect(bbox,&rect,0)) { sraRegionPtr slice; if(y<rect.y1 || y>=rect.y2) y=rect.y1; slice=sraRgnCreateRect(0,y,cl->screen->width,y+height); sraRgnAnd(updateRegion,slice); sraRgnDestroy(slice); } sraRgnDestroy(bbox); y+=height; if(y>=cl->screen->height) y=0; cl->progressiveSliceY=y; } sraRgnOr(updateRegion,cl->copyRegion); if(!sraRgnAnd(updateRegion,cl->requestedRegion) && sraRgnEmpty(updateRegion) && (cl->enableCursorShapeUpdates || (cl->cursorX == cl->screen->cursorX && cl->cursorY == cl->screen->cursorY)) && !sendCursorShape && !sendCursorPos && !sendKeyboardLedState && !sendSupportedMessages && !sendSupportedEncodings && !sendServerIdentity) { sraRgnDestroy(updateRegion); UNLOCK(cl->updateMutex); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, TRUE); return TRUE; } /* * We assume that the client doesn't have any pixel data outside the * requestedRegion. In other words, both the source and destination of a * copy must lie within requestedRegion. So the region we can send as a * copy is the intersection of the copyRegion with both the requestedRegion * and the requestedRegion translated by the amount of the copy. We set * updateCopyRegion to this. */ updateCopyRegion = sraRgnCreateRgn(cl->copyRegion); sraRgnAnd(updateCopyRegion,cl->requestedRegion); tmpRegion = sraRgnCreateRgn(cl->requestedRegion); sraRgnOffset(tmpRegion,cl->copyDX,cl->copyDY); sraRgnAnd(updateCopyRegion,tmpRegion); sraRgnDestroy(tmpRegion); dx = cl->copyDX; dy = cl->copyDY; /* * Next we remove updateCopyRegion from updateRegion so that updateRegion * is the part of this update which is sent as ordinary pixel data (i.e not * a copy). */ sraRgnSubtract(updateRegion,updateCopyRegion); /* * Finally we leave modifiedRegion to be the remainder (if any) of parts of * the screen which are modified but outside the requestedRegion. We also * empty both the requestedRegion and the copyRegion - note that we never * carry over a copyRegion for a future update. */ sraRgnOr(cl->modifiedRegion,cl->copyRegion); sraRgnSubtract(cl->modifiedRegion,updateRegion); sraRgnSubtract(cl->modifiedRegion,updateCopyRegion); sraRgnMakeEmpty(cl->requestedRegion); sraRgnMakeEmpty(cl->copyRegion); cl->copyDX = 0; cl->copyDY = 0; UNLOCK(cl->updateMutex); if (!cl->enableCursorShapeUpdates) { if(cl->cursorX != cl->screen->cursorX || cl->cursorY != cl->screen->cursorY) { rfbRedrawAfterHideCursor(cl,updateRegion); LOCK(cl->screen->cursorMutex); cl->cursorX = cl->screen->cursorX; cl->cursorY = cl->screen->cursorY; UNLOCK(cl->screen->cursorMutex); rfbRedrawAfterHideCursor(cl,updateRegion); } rfbShowCursor(cl); } /* * Now send the update. */ rfbStatRecordMessageSent(cl, rfbFramebufferUpdate, 0, 0); if (cl->preferredEncoding == rfbEncodingCoRRE) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int rectsPerRow, rows; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); rectsPerRow = (w-1)/cl->correMaxWidth+1; rows = (h-1)/cl->correMaxHeight+1; nUpdateRegionRects += rectsPerRow*rows; } sraRgnReleaseIterator(i); i=NULL; } else if (cl->preferredEncoding == rfbEncodingUltra) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); nUpdateRegionRects += (((h-1) / (ULTRA_MAX_SIZE( w ) / w)) + 1); } sraRgnReleaseIterator(i); i=NULL; #ifdef LIBVNCSERVER_HAVE_LIBZ } else if (cl->preferredEncoding == rfbEncodingZlib) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); nUpdateRegionRects += (((h-1) / (ZLIB_MAX_SIZE( w ) / w)) + 1); } sraRgnReleaseIterator(i); i=NULL; #ifdef LIBVNCSERVER_HAVE_LIBJPEG } else if (cl->preferredEncoding == rfbEncodingTight) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); i=NULL; #endif #endif #if defined(LIBVNCSERVER_HAVE_LIBJPEG) && defined(LIBVNCSERVER_HAVE_LIBPNG) } else if (cl->preferredEncoding == rfbEncodingTightPng) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); i=NULL; #endif } else { nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->type = rfbFramebufferUpdate; if (nUpdateRegionRects != 0xFFFF) { if(cl->screen->maxRectsPerUpdate>0 /* CoRRE splits the screen into smaller squares */ && cl->preferredEncoding != rfbEncodingCoRRE /* Ultra encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingUltra #ifdef LIBVNCSERVER_HAVE_LIBZ /* Zlib encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingZlib #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTight #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTightPng #endif && nUpdateRegionRects>cl->screen->maxRectsPerUpdate) { sraRegion* newUpdateRegion = sraRgnBBox(updateRegion); sraRgnDestroy(updateRegion); updateRegion = newUpdateRegion; nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->nRects = Swap16IfLE((uint16_t)(sraRgnCountRects(updateCopyRegion) + nUpdateRegionRects + !!sendCursorShape + !!sendCursorPos + !!sendKeyboardLedState + !!sendSupportedMessages + !!sendSupportedEncodings + !!sendServerIdentity)); } else { fu->nRects = 0xFFFF; } cl->ublen = sz_rfbFramebufferUpdateMsg; if (sendCursorShape) { cl->cursorWasChanged = FALSE; if (!rfbSendCursorShape(cl)) goto updateFailed; } if (sendCursorPos) { cl->cursorWasMoved = FALSE; if (!rfbSendCursorPos(cl)) goto updateFailed; } if (sendKeyboardLedState) { if (!rfbSendKeyboardLedState(cl)) goto updateFailed; } if (sendSupportedMessages) { if (!rfbSendSupportedMessages(cl)) goto updateFailed; } if (sendSupportedEncodings) { if (!rfbSendSupportedEncodings(cl)) goto updateFailed; } if (sendServerIdentity) { if (!rfbSendServerIdentity(cl)) goto updateFailed; } if (!sraRgnEmpty(updateCopyRegion)) { if (!rfbSendCopyRegion(cl,updateCopyRegion,dx,dy)) goto updateFailed; } for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); switch (cl->preferredEncoding) { case -1: case rfbEncodingRaw: if (!rfbSendRectEncodingRaw(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingRRE: if (!rfbSendRectEncodingRRE(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingCoRRE: if (!rfbSendRectEncodingCoRRE(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingHextile: if (!rfbSendRectEncodingHextile(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingUltra: if (!rfbSendRectEncodingUltra(cl, x, y, w, h)) goto updateFailed; break; #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: if (!rfbSendRectEncodingZlib(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingZRLE: case rfbEncodingZYWRLE: if (!rfbSendRectEncodingZRLE(cl, x, y, w, h)) goto updateFailed; break; #endif #if defined(LIBVNCSERVER_HAVE_LIBJPEG) && (defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)) case rfbEncodingTight: if (!rfbSendRectEncodingTight(cl, x, y, w, h)) goto updateFailed; break; #ifdef LIBVNCSERVER_HAVE_LIBPNG case rfbEncodingTightPng: if (!rfbSendRectEncodingTightPng(cl, x, y, w, h)) goto updateFailed; break; #endif #endif } } if (i) { sraRgnReleaseIterator(i); i = NULL; } if ( nUpdateRegionRects == 0xFFFF && !rfbSendLastRectMarker(cl) ) goto updateFailed; if (!rfbSendUpdateBuf(cl)) { updateFailed: result = FALSE; } if (!cl->enableCursorShapeUpdates) { rfbHideCursor(cl); } if(i) sraRgnReleaseIterator(i); sraRgnDestroy(updateRegion); sraRgnDestroy(updateCopyRegion); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, result); return result; } /* * Send the copy region as a string of CopyRect encoded rectangles. * The only slightly tricky thing is that we should send the messages in * the correct order so that an earlier CopyRect will not corrupt the source * of a later one. */ rfbBool rfbSendCopyRegion(rfbClientPtr cl, sraRegionPtr reg, int dx, int dy) { int x, y, w, h; rfbFramebufferUpdateRectHeader rect; rfbCopyRect cr; sraRectangleIterator* i; sraRect rect1; /* printf("copyrect: "); sraRgnPrint(reg); putchar('\n');fflush(stdout); */ i = sraRgnGetReverseIterator(reg,dx>0,dy>0); /* correct for the scale of the screen */ dx = ScaleX(cl->screen, cl->scaledScreen, dx); dy = ScaleX(cl->screen, cl->scaledScreen, dy); while(sraRgnIteratorNext(i,&rect1)) { x = rect1.x1; y = rect1.y1; w = rect1.x2 - x; h = rect1.y2 - y; /* correct for scaling (if necessary) */ rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "copyrect"); rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingCopyRect); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; cr.srcX = Swap16IfLE(x - dx); cr.srcY = Swap16IfLE(y - dy); memcpy(&cl->updateBuf[cl->ublen], (char *)&cr, sz_rfbCopyRect); cl->ublen += sz_rfbCopyRect; rfbStatRecordEncodingSent(cl, rfbEncodingCopyRect, sz_rfbFramebufferUpdateRectHeader + sz_rfbCopyRect, w * h * (cl->scaledScreen->bitsPerPixel / 8)); } sraRgnReleaseIterator(i); return TRUE; } /* * Send a given rectangle in raw encoding (rfbEncodingRaw). */ rfbBool rfbSendRectEncodingRaw(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; int nlines; int bytesPerLine = w * (cl->format.bitsPerPixel / 8); char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) + (x * (cl->scaledScreen->bitsPerPixel / 8))); /* Flush the buffer to guarantee correct alignment for translateFn(). */ if (cl->ublen > 0) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRaw); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingRaw, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h); nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine; while (TRUE) { if (nlines > h) nlines = h; (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), &cl->format, fbptr, &cl->updateBuf[cl->ublen], cl->scaledScreen->paddedWidthInBytes, w, nlines); cl->ublen += nlines * bytesPerLine; h -= nlines; if (h == 0) /* rect fitted in buffer, do next one */ return TRUE; /* buffer full - flush partial rect and do another nlines */ if (!rfbSendUpdateBuf(cl)) return FALSE; fbptr += (cl->scaledScreen->paddedWidthInBytes * nlines); nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine; if (nlines == 0) { rfbErr("rfbSendRectEncodingRaw: send buffer too small for %d " "bytes per line\n", bytesPerLine); rfbCloseClient(cl); return FALSE; } } } /* * Send an empty rectangle with encoding field set to value of * rfbEncodingLastRect to notify client that this is the last * rectangle in framebuffer update ("LastRect" extension of RFB * protocol). */ rfbBool rfbSendLastRectMarker(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingLastRect); rect.r.x = 0; rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingLastRect, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); return TRUE; } /* * Send NewFBSize pseudo-rectangle. This tells the client to change * its framebuffer size. */ rfbBool rfbSendNewFBSize(rfbClientPtr cl, int w, int h) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } if (cl->PalmVNC==TRUE) rfbLog("Sending rfbEncodingNewFBSize in response to a PalmVNC style framebuffer resize (%dx%d)\n", w, h); else rfbLog("Sending rfbEncodingNewFBSize for resize to (%dx%d)\n", w, h); rect.encoding = Swap32IfLE(rfbEncodingNewFBSize); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingNewFBSize, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); return TRUE; } /* * Send ExtDesktopSize pseudo-rectangle. This message is used: * - to tell the client to change its framebuffer size * - at the start of the session to inform the client we support size changes through setDesktopSize * - in response to setDesktopSize commands to indicate success or failure */ rfbBool rfbSendExtDesktopSize(rfbClientPtr cl, int w, int h) { rfbFramebufferUpdateRectHeader rect; rfbExtDesktopSizeMsg edsHdr; rfbExtDesktopScreen eds; int i; char *logmsg; int numScreens = cl->screen->numberOfExtDesktopScreensHook(cl); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbExtDesktopSizeMsg + sz_rfbExtDesktopScreen * numScreens > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingExtDesktopSize); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.r.x = Swap16IfLE(cl->requestedDesktopSizeChange); rect.r.y = Swap16IfLE(cl->lastDesktopSizeChangeError); logmsg = ""; if (cl->requestedDesktopSizeChange == rfbExtDesktopSize_ClientRequestedChange) { /* our client requested the resize through setDesktopSize */ switch (cl->lastDesktopSizeChangeError) { case rfbExtDesktopSize_Success: logmsg = "resize successful"; break; case rfbExtDesktopSize_ResizeProhibited: logmsg = "resize prohibited"; break; case rfbExtDesktopSize_OutOfResources: logmsg = "resize failed: out of resources"; break; case rfbExtDesktopSize_InvalidScreenLayout: logmsg = "resize failed: invalid screen layout"; break; default: break; } } cl->requestedDesktopSizeChange = 0; cl->lastDesktopSizeChangeError = 0; rfbLog("Sending rfbEncodingExtDesktopSize for size (%dx%d) %s\n", w, h, logmsg); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; edsHdr.numberOfScreens = numScreens; edsHdr.pad[0] = edsHdr.pad[1] = edsHdr.pad[2] = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&edsHdr, sz_rfbExtDesktopSizeMsg); cl->ublen += sz_rfbExtDesktopSizeMsg; for (i=0; i<numScreens; i++) { if (!cl->screen->getExtDesktopScreenHook(i, &eds, cl)) { rfbErr("Error getting ExtendedDesktopSize information for screen #%d\n", i); return FALSE; } eds.id = Swap32IfLE(eds.id); eds.x = Swap16IfLE(eds.x); eds.y = Swap16IfLE(eds.y); eds.width = Swap16IfLE(eds.width); eds.height = Swap16IfLE(eds.height); eds.flags = Swap32IfLE(eds.flags); memcpy(&cl->updateBuf[cl->ublen], (char *)&eds, sz_rfbExtDesktopScreen); cl->ublen += sz_rfbExtDesktopScreen; } rfbStatRecordEncodingSent(cl, rfbEncodingExtDesktopSize, sz_rfbFramebufferUpdateRectHeader + sz_rfbExtDesktopSizeMsg + sz_rfbExtDesktopScreen * numScreens, sz_rfbFramebufferUpdateRectHeader + sz_rfbExtDesktopSizeMsg + sz_rfbExtDesktopScreen * numScreens); return TRUE; } /* * Send the contents of cl->updateBuf. Returns 1 if successful, -1 if * not (errno should be set). */ rfbBool rfbSendUpdateBuf(rfbClientPtr cl) { if(cl->sock<0) return FALSE; if (rfbWriteExact(cl, cl->updateBuf, cl->ublen) < 0) { rfbLogPerror("rfbSendUpdateBuf: write"); rfbCloseClient(cl); return FALSE; } cl->ublen = 0; return TRUE; } /* * rfbSendSetColourMapEntries sends a SetColourMapEntries message to the * client, using values from the currently installed colormap. */ rfbBool rfbSendSetColourMapEntries(rfbClientPtr cl, int firstColour, int nColours) { char buf[sz_rfbSetColourMapEntriesMsg + 256 * 3 * 2]; char *wbuf = buf; rfbSetColourMapEntriesMsg *scme; uint16_t *rgb; rfbColourMap* cm = &cl->screen->colourMap; int i, len; if (nColours > 256) { /* some rare hardware has, e.g., 4096 colors cells: PseudoColor:12 */ wbuf = (char *) malloc(sz_rfbSetColourMapEntriesMsg + nColours * 3 * 2); } scme = (rfbSetColourMapEntriesMsg *)wbuf; rgb = (uint16_t *)(&wbuf[sz_rfbSetColourMapEntriesMsg]); scme->type = rfbSetColourMapEntries; scme->firstColour = Swap16IfLE(firstColour); scme->nColours = Swap16IfLE(nColours); len = sz_rfbSetColourMapEntriesMsg; for (i = 0; i < nColours; i++) { if(i<(int)cm->count) { if(cm->is16) { rgb[i*3] = Swap16IfLE(cm->data.shorts[i*3]); rgb[i*3+1] = Swap16IfLE(cm->data.shorts[i*3+1]); rgb[i*3+2] = Swap16IfLE(cm->data.shorts[i*3+2]); } else { rgb[i*3] = Swap16IfLE((unsigned short)cm->data.bytes[i*3]); rgb[i*3+1] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+1]); rgb[i*3+2] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+2]); } } } len += nColours * 3 * 2; LOCK(cl->sendMutex); if (rfbWriteExact(cl, wbuf, len) < 0) { rfbLogPerror("rfbSendSetColourMapEntries: write"); rfbCloseClient(cl); if (wbuf != buf) free(wbuf); UNLOCK(cl->sendMutex); return FALSE; } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbSetColourMapEntries, len, len); if (wbuf != buf) free(wbuf); return TRUE; } /* * rfbSendBell sends a Bell message to all the clients. */ void rfbSendBell(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i; rfbClientPtr cl; rfbBellMsg b; i = rfbGetClientIterator(rfbScreen); while((cl=rfbClientIteratorNext(i))) { b.type = rfbBell; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&b, sz_rfbBellMsg) < 0) { rfbLogPerror("rfbSendBell: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); } rfbStatRecordMessageSent(cl, rfbBell, sz_rfbBellMsg, sz_rfbBellMsg); rfbReleaseClientIterator(i); } /* * rfbSendServerCutText sends a ServerCutText message to all the clients. */ void rfbSendServerCutText(rfbScreenInfoPtr rfbScreen,char *str, int len) { rfbClientPtr cl; rfbServerCutTextMsg sct; rfbClientIteratorPtr iterator; memset((char *)&sct, 0, sizeof(sct)); iterator = rfbGetClientIterator(rfbScreen); while ((cl = rfbClientIteratorNext(iterator)) != NULL) { sct.type = rfbServerCutText; sct.length = Swap32IfLE(len); LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&sct, sz_rfbServerCutTextMsg) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); continue; } if (rfbWriteExact(cl, str, len) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbServerCutText, sz_rfbServerCutTextMsg+len, sz_rfbServerCutTextMsg+len); } rfbReleaseClientIterator(iterator); } /***************************************************************************** * * UDP can be used for keyboard and pointer events when the underlying * network is highly reliable. This is really here to support ORL's * videotile, whose TCP implementation doesn't like sending lots of small * packets (such as 100s of pen readings per second!). */ static unsigned char ptrAcceleration = 50; void rfbNewUDPConnection(rfbScreenInfoPtr rfbScreen, int sock) { if (write(sock, (char*) &ptrAcceleration, 1) < 0) { rfbLogPerror("rfbNewUDPConnection: write"); } } /* * Because UDP is a message based service, we can't read the first byte and * then the rest of the packet separately like we do with TCP. We will always * get a whole packet delivered in one go, so we ask read() for the maximum * number of bytes we can possibly get. */ void rfbProcessUDPInput(rfbScreenInfoPtr rfbScreen) { int n; rfbClientPtr cl=rfbScreen->udpClient; rfbClientToServerMsg msg; if((!cl) || cl->onHold) return; if ((n = read(rfbScreen->udpSock, (char *)&msg, sizeof(msg))) <= 0) { if (n < 0) { rfbLogPerror("rfbProcessUDPInput: read"); } rfbDisconnectUDPSock(rfbScreen); return; } switch (msg.type) { case rfbKeyEvent: if (n != sz_rfbKeyEventMsg) { rfbErr("rfbProcessUDPInput: key event incorrect length\n"); rfbDisconnectUDPSock(rfbScreen); return; } cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl); break; case rfbPointerEvent: if (n != sz_rfbPointerEventMsg) { rfbErr("rfbProcessUDPInput: ptr event incorrect length\n"); rfbDisconnectUDPSock(rfbScreen); return; } cl->screen->ptrAddEvent(msg.pe.buttonMask, Swap16IfLE(msg.pe.x), Swap16IfLE(msg.pe.y), cl); break; default: rfbErr("rfbProcessUDPInput: unknown message type %d\n", msg.type); rfbDisconnectUDPSock(rfbScreen); } }
./CrossVul/dataset_final_sorted/CWE-772/c/good_1039_0
crossvul-cpp_data_bad_2557_0
/* * Copyright (C) 2015 Red Hat, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "virtgpu_drv.h" static void virtio_gpu_ttm_bo_destroy(struct ttm_buffer_object *tbo) { struct virtio_gpu_object *bo; struct virtio_gpu_device *vgdev; bo = container_of(tbo, struct virtio_gpu_object, tbo); vgdev = (struct virtio_gpu_device *)bo->gem_base.dev->dev_private; if (bo->hw_res_handle) virtio_gpu_cmd_unref_resource(vgdev, bo->hw_res_handle); if (bo->pages) virtio_gpu_object_free_sg_table(bo); drm_gem_object_release(&bo->gem_base); kfree(bo); } static void virtio_gpu_init_ttm_placement(struct virtio_gpu_object *vgbo, bool pinned) { u32 c = 1; u32 pflag = pinned ? TTM_PL_FLAG_NO_EVICT : 0; vgbo->placement.placement = &vgbo->placement_code; vgbo->placement.busy_placement = &vgbo->placement_code; vgbo->placement_code.fpfn = 0; vgbo->placement_code.lpfn = 0; vgbo->placement_code.flags = TTM_PL_MASK_CACHING | TTM_PL_FLAG_TT | pflag; vgbo->placement.num_placement = c; vgbo->placement.num_busy_placement = c; } int virtio_gpu_object_create(struct virtio_gpu_device *vgdev, unsigned long size, bool kernel, bool pinned, struct virtio_gpu_object **bo_ptr) { struct virtio_gpu_object *bo; enum ttm_bo_type type; size_t acc_size; int ret; if (kernel) type = ttm_bo_type_kernel; else type = ttm_bo_type_device; *bo_ptr = NULL; acc_size = ttm_bo_dma_acc_size(&vgdev->mman.bdev, size, sizeof(struct virtio_gpu_object)); bo = kzalloc(sizeof(struct virtio_gpu_object), GFP_KERNEL); if (bo == NULL) return -ENOMEM; size = roundup(size, PAGE_SIZE); ret = drm_gem_object_init(vgdev->ddev, &bo->gem_base, size); if (ret != 0) return ret; bo->dumb = false; virtio_gpu_init_ttm_placement(bo, pinned); ret = ttm_bo_init(&vgdev->mman.bdev, &bo->tbo, size, type, &bo->placement, 0, !kernel, NULL, acc_size, NULL, NULL, &virtio_gpu_ttm_bo_destroy); /* ttm_bo_init failure will call the destroy */ if (ret != 0) return ret; *bo_ptr = bo; return 0; } int virtio_gpu_object_kmap(struct virtio_gpu_object *bo, void **ptr) { bool is_iomem; int r; if (bo->vmap) { if (ptr) *ptr = bo->vmap; return 0; } r = ttm_bo_kmap(&bo->tbo, 0, bo->tbo.num_pages, &bo->kmap); if (r) return r; bo->vmap = ttm_kmap_obj_virtual(&bo->kmap, &is_iomem); if (ptr) *ptr = bo->vmap; return 0; } int virtio_gpu_object_get_sg_table(struct virtio_gpu_device *qdev, struct virtio_gpu_object *bo) { int ret; struct page **pages = bo->tbo.ttm->pages; int nr_pages = bo->tbo.num_pages; /* wtf swapping */ if (bo->pages) return 0; if (bo->tbo.ttm->state == tt_unpopulated) bo->tbo.ttm->bdev->driver->ttm_tt_populate(bo->tbo.ttm); bo->pages = kmalloc(sizeof(struct sg_table), GFP_KERNEL); if (!bo->pages) goto out; ret = sg_alloc_table_from_pages(bo->pages, pages, nr_pages, 0, nr_pages << PAGE_SHIFT, GFP_KERNEL); if (ret) goto out; return 0; out: kfree(bo->pages); bo->pages = NULL; return -ENOMEM; } void virtio_gpu_object_free_sg_table(struct virtio_gpu_object *bo) { sg_free_table(bo->pages); kfree(bo->pages); bo->pages = NULL; } int virtio_gpu_object_wait(struct virtio_gpu_object *bo, bool no_wait) { int r; r = ttm_bo_reserve(&bo->tbo, true, no_wait, NULL); if (unlikely(r != 0)) return r; r = ttm_bo_wait(&bo->tbo, true, no_wait); ttm_bo_unreserve(&bo->tbo); return r; }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2557_0
crossvul-cpp_data_good_2574_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS CCCC RRRR EEEEE EEEEE N N SSSSS H H OOO TTTTT % % SS C R R E E NN N SS H H O O T % % SSS C RRRR EEE EEE N N N SSS HHHHH O O T % % SS C R R E E N NN SS H H O O T % % SSSSS CCCC R R EEEEE EEEEE N N SSSSS H H OOO T % % % % % % Takes a screenshot from the monitor(s). % % % % Software Design % % Dirk Lemstra % % April 2014 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #if defined(MAGICKCORE_WINGDI32_DELEGATE) # if defined(__CYGWIN__) # include <windows.h> # else /* All MinGW needs ... */ # include "magick/nt-base-private.h" # include <wingdi.h> # ifndef DISPLAY_DEVICE_ACTIVE # define DISPLAY_DEVICE_ACTIVE 0x00000001 # endif # endif #endif #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/nt-feature.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/token.h" #include "magick/utility.h" #include "magick/xwindow.h" #include "magick/xwindow-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d S C R E E N S H O T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadSCREENSHOTImage() Takes a screenshot from the monitor(s). % % The format of the ReadSCREENSHOTImage method is: % % Image *ReadXImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadSCREENSHOTImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=(Image *) NULL; #if defined(MAGICKCORE_WINGDI32_DELEGATE) { BITMAPINFO bmi; DISPLAY_DEVICE device; HBITMAP bitmap, bitmapOld; HDC bitmapDC, hDC; Image *screen; int i; MagickBooleanType status; register PixelPacket *q; register ssize_t x; RGBTRIPLE *p; ssize_t y; assert(image_info != (const ImageInfo *) NULL); i=0; device.cb = sizeof(device); image=(Image *) NULL; while(EnumDisplayDevices(NULL,i,&device,0) && ++i) { if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE) continue; hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL); if (hDC == (HDC) NULL) ThrowReaderException(CoderError,"UnableToCreateDC"); screen=AcquireImage(image_info); screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES); screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES); screen->storage_class=DirectClass; if (image == (Image *) NULL) image=screen; else AppendImageToList(&image,screen); status=SetImageExtent(screen,screen->columns,screen->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } bitmapDC=CreateCompatibleDC(hDC); if (bitmapDC == (HDC) NULL) { DeleteDC(hDC); ThrowReaderException(CoderError,"UnableToCreateDC"); } (void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO)); bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth=(LONG) screen->columns; bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows; bmi.bmiHeader.biPlanes=1; bmi.bmiHeader.biBitCount=24; bmi.bmiHeader.biCompression=BI_RGB; bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0); if (bitmap == (HBITMAP) NULL) { DeleteDC(hDC); DeleteDC(bitmapDC); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap); if (bitmapOld == (HBITMAP) NULL) { DeleteDC(hDC); DeleteDC(bitmapDC); DeleteObject(bitmap); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0, SRCCOPY); (void) SelectObject(bitmapDC,bitmapOld); for (y=0; y < (ssize_t) screen->rows; y++) { q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) screen->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(p->rgbtRed)); SetPixelGreen(q,ScaleCharToQuantum(p->rgbtGreen)); SetPixelBlue(q,ScaleCharToQuantum(p->rgbtBlue)); SetPixelOpacity(q,OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(screen,exception) == MagickFalse) break; } DeleteDC(hDC); DeleteDC(bitmapDC); DeleteObject(bitmap); } } #elif defined(MAGICKCORE_X11_DELEGATE) { const char *option; XImportInfo ximage_info; (void) exception; XGetImportInfo(&ximage_info); option=GetImageOption(image_info,"x:screen"); if (option != (const char *) NULL) ximage_info.screen=IsMagickTrue(option); option=GetImageOption(image_info,"x:silent"); if (option != (const char *) NULL) ximage_info.silent=IsMagickTrue(option); image=XImportImage(image_info,&ximage_info); } #endif return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r S C R E E N S H O T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterSCREENSHOTImage() adds attributes for the screen shot format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterScreenShotImage method is: % % size_t RegisterScreenShotImage(void) % */ ModuleExport size_t RegisterSCREENSHOTImage(void) { MagickInfo *entry; entry=SetMagickInfo("SCREENSHOT"); entry->decoder=(DecodeImageHandler *) ReadSCREENSHOTImage; entry->format_type=ImplicitFormatType; entry->description=ConstantString("Screen shot"); entry->module=ConstantString("SCREENSHOT"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r S C R E E N S H O T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterScreenShotImage() removes format registrations made by the % screen shot module from the list of supported formats. % % The format of the UnregisterSCREENSHOTImage method is: % % UnregisterSCREENSHOTImage(void) % */ ModuleExport void UnregisterSCREENSHOTImage(void) { (void) UnregisterMagickInfo("SCREENSHOT"); }
./CrossVul/dataset_final_sorted/CWE-772/c/good_2574_0
crossvul-cpp_data_good_2620_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % IIIII N N L IIIII N N EEEEE % % I NN N L I NN N E % % I N N N L I N N N EEE % % I N NN L I N NN E % % IIIII N N LLLLL IIIII N N EEEEE % % % % % % Read/Write Inline Images % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/client.h" #include "magick/display.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/utility.h" #include "magick/xwindow.h" #include "magick/xwindow-private.h" /* Forward declarations. */ static MagickBooleanType WriteINLINEImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d I N L I N E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadINLINEImage() reads base64-encoded inlines images. % % The format of the ReadINLINEImage method is: % % Image *ReadINLINEImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadINLINEImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType status; register size_t i; size_t quantum; ssize_t count; unsigned char *inline_image; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (LocaleNCompare(image_info->filename,"data:",5) == 0) { char *filename; Image *data_image; filename=AcquireString("data:"); (void) ConcatenateMagickString(filename,image_info->filename, MaxTextExtent); data_image=ReadInlineImage(image_info,filename,exception); filename=DestroyString(filename); return(data_image); } image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } quantum=MagickMin((size_t) GetBlobSize(image),MagickMaxBufferExtent); if (quantum == 0) quantum=MagickMaxBufferExtent; inline_image=(unsigned char *) AcquireQuantumMemory(quantum, sizeof(*inline_image)); count=0; for (i=0; inline_image != (unsigned char *) NULL; i+=count) { count=(ssize_t) ReadBlob(image,quantum,inline_image+i); if (count <= 0) { count=0; if (errno != EINTR) break; } if (~((size_t) i) < (quantum+1)) { inline_image=(unsigned char *) RelinquishMagickMemory(inline_image); break; } inline_image=(unsigned char *) ResizeQuantumMemory(inline_image,i+count+ quantum+1,sizeof(*inline_image)); } if (inline_image == (unsigned char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return((Image *) NULL); } inline_image[i+count]='\0'; image=DestroyImageList(image); image=ReadInlineImage(image_info,(char *) inline_image,exception); inline_image=(unsigned char *) RelinquishMagickMemory(inline_image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r I N L I N E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterINLINEImage() adds attributes for the INLINE image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterINLINEImage method is: % % size_t RegisterINLINEImage(void) % */ ModuleExport size_t RegisterINLINEImage(void) { MagickInfo *entry; entry=SetMagickInfo("DATA"); entry->decoder=(DecodeImageHandler *) ReadINLINEImage; entry->encoder=(EncodeImageHandler *) WriteINLINEImage; entry->format_type=ImplicitFormatType; entry->description=ConstantString("Base64-encoded inline images"); entry->module=ConstantString("INLINE"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("INLINE"); entry->decoder=(DecodeImageHandler *) ReadINLINEImage; entry->encoder=(EncodeImageHandler *) WriteINLINEImage; entry->format_type=ImplicitFormatType; entry->description=ConstantString("Base64-encoded inline images"); entry->module=ConstantString("INLINE"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r I N L I N E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterINLINEImage() removes format registrations made by the % INLINE module from the list of supported formats. % % The format of the UnregisterINLINEImage method is: % % UnregisterINLINEImage(void) % */ ModuleExport void UnregisterINLINEImage(void) { (void) UnregisterMagickInfo("INLINE"); (void) UnregisterMagickInfo("DATA"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e I N L I N E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteINLINEImage() writes an image to a file in INLINE format (Base64). % % The format of the WriteINLINEImage method is: % % MagickBooleanType WriteINLINEImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteINLINEImage(const ImageInfo *image_info, Image *image) { char *base64, message[MaxTextExtent]; const MagickInfo *magick_info; ExceptionInfo *exception; Image *write_image; ImageInfo *write_info; MagickBooleanType status; size_t blob_length, encode_length; unsigned char *blob; /* Convert image to base64-encoding. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=(&image->exception); write_info=CloneImageInfo(image_info); (void) SetImageInfo(write_info,1,exception); if (LocaleCompare(write_info->magick,"INLINE") == 0) (void) CopyMagickString(write_info->magick,image->magick,MaxTextExtent); magick_info=GetMagickInfo(write_info->magick,exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickMimeType(magick_info) == (const char *) NULL)) { write_info=DestroyImageInfo(write_info); ThrowWriterException(CorruptImageError,"ImageTypeNotSupported"); } (void) CopyMagickString(image->filename,write_info->filename,MaxTextExtent); blob_length=2048; write_image=CloneImage(image,0,0,MagickTrue,exception); if (write_image == (Image *) NULL) { write_info=DestroyImageInfo(write_info); return(MagickTrue); } blob=(unsigned char *) ImageToBlob(write_info,write_image,&blob_length, exception); write_image=DestroyImage(write_image); write_info=DestroyImageInfo(write_info); if (blob == (unsigned char *) NULL) return(MagickFalse); encode_length=0; base64=Base64Encode(blob,blob_length,&encode_length); blob=(unsigned char *) RelinquishMagickMemory(blob); if (base64 == (char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Write base64-encoded image. */ status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) { base64=DestroyString(base64); return(status); } (void) FormatLocaleString(message,MaxTextExtent,"data:%s;base64,", GetMagickMimeType(magick_info)); (void) WriteBlobString(image,message); (void) WriteBlobString(image,base64); base64=DestroyString(base64); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-772/c/good_2620_0
crossvul-cpp_data_bad_1194_0
// SPDX-License-Identifier: GPL-2.0-only /* * net/ipv6/fib6_rules.c IPv6 Routing Policy Rules * * Copyright (C)2003-2006 Helsinki University of Technology * Copyright (C)2003-2006 USAGI/WIDE Project * * Authors * Thomas Graf <tgraf@suug.ch> * Ville Nuorvala <vnuorval@tcs.hut.fi> */ #include <linux/netdevice.h> #include <linux/notifier.h> #include <linux/export.h> #include <net/fib_rules.h> #include <net/ipv6.h> #include <net/addrconf.h> #include <net/ip6_route.h> #include <net/netlink.h> struct fib6_rule { struct fib_rule common; struct rt6key src; struct rt6key dst; u8 tclass; }; static bool fib6_rule_matchall(const struct fib_rule *rule) { struct fib6_rule *r = container_of(rule, struct fib6_rule, common); if (r->dst.plen || r->src.plen || r->tclass) return false; return fib_rule_matchall(rule); } bool fib6_rule_default(const struct fib_rule *rule) { if (!fib6_rule_matchall(rule) || rule->action != FR_ACT_TO_TBL || rule->l3mdev) return false; if (rule->table != RT6_TABLE_LOCAL && rule->table != RT6_TABLE_MAIN) return false; return true; } EXPORT_SYMBOL_GPL(fib6_rule_default); int fib6_rules_dump(struct net *net, struct notifier_block *nb) { return fib_rules_dump(net, nb, AF_INET6); } unsigned int fib6_rules_seq_read(struct net *net) { return fib_rules_seq_read(net, AF_INET6); } /* called with rcu lock held; no reference taken on fib6_info */ int fib6_lookup(struct net *net, int oif, struct flowi6 *fl6, struct fib6_result *res, int flags) { int err; if (net->ipv6.fib6_has_custom_rules) { struct fib_lookup_arg arg = { .lookup_ptr = fib6_table_lookup, .lookup_data = &oif, .result = res, .flags = FIB_LOOKUP_NOREF, }; l3mdev_update_flow(net, flowi6_to_flowi(fl6)); err = fib_rules_lookup(net->ipv6.fib6_rules_ops, flowi6_to_flowi(fl6), flags, &arg); } else { err = fib6_table_lookup(net, net->ipv6.fib6_local_tbl, oif, fl6, res, flags); if (err || res->f6i == net->ipv6.fib6_null_entry) err = fib6_table_lookup(net, net->ipv6.fib6_main_tbl, oif, fl6, res, flags); } return err; } struct dst_entry *fib6_rule_lookup(struct net *net, struct flowi6 *fl6, const struct sk_buff *skb, int flags, pol_lookup_t lookup) { if (net->ipv6.fib6_has_custom_rules) { struct fib6_result res = {}; struct fib_lookup_arg arg = { .lookup_ptr = lookup, .lookup_data = skb, .result = &res, .flags = FIB_LOOKUP_NOREF, }; /* update flow if oif or iif point to device enslaved to l3mdev */ l3mdev_update_flow(net, flowi6_to_flowi(fl6)); fib_rules_lookup(net->ipv6.fib6_rules_ops, flowi6_to_flowi(fl6), flags, &arg); if (res.rt6) return &res.rt6->dst; } else { struct rt6_info *rt; rt = lookup(net, net->ipv6.fib6_local_tbl, fl6, skb, flags); if (rt != net->ipv6.ip6_null_entry && rt->dst.error != -EAGAIN) return &rt->dst; ip6_rt_put_flags(rt, flags); rt = lookup(net, net->ipv6.fib6_main_tbl, fl6, skb, flags); if (rt->dst.error != -EAGAIN) return &rt->dst; ip6_rt_put_flags(rt, flags); } if (!(flags & RT6_LOOKUP_F_DST_NOREF)) dst_hold(&net->ipv6.ip6_null_entry->dst); return &net->ipv6.ip6_null_entry->dst; } static int fib6_rule_saddr(struct net *net, struct fib_rule *rule, int flags, struct flowi6 *flp6, const struct net_device *dev) { struct fib6_rule *r = (struct fib6_rule *)rule; /* If we need to find a source address for this traffic, * we check the result if it meets requirement of the rule. */ if ((rule->flags & FIB_RULE_FIND_SADDR) && r->src.plen && !(flags & RT6_LOOKUP_F_HAS_SADDR)) { struct in6_addr saddr; if (ipv6_dev_get_saddr(net, dev, &flp6->daddr, rt6_flags2srcprefs(flags), &saddr)) return -EAGAIN; if (!ipv6_prefix_equal(&saddr, &r->src.addr, r->src.plen)) return -EAGAIN; flp6->saddr = saddr; } return 0; } static int fib6_rule_action_alt(struct fib_rule *rule, struct flowi *flp, int flags, struct fib_lookup_arg *arg) { struct fib6_result *res = arg->result; struct flowi6 *flp6 = &flp->u.ip6; struct net *net = rule->fr_net; struct fib6_table *table; int err, *oif; u32 tb_id; switch (rule->action) { case FR_ACT_TO_TBL: break; case FR_ACT_UNREACHABLE: return -ENETUNREACH; case FR_ACT_PROHIBIT: return -EACCES; case FR_ACT_BLACKHOLE: default: return -EINVAL; } tb_id = fib_rule_get_table(rule, arg); table = fib6_get_table(net, tb_id); if (!table) return -EAGAIN; oif = (int *)arg->lookup_data; err = fib6_table_lookup(net, table, *oif, flp6, res, flags); if (!err && res->f6i != net->ipv6.fib6_null_entry) err = fib6_rule_saddr(net, rule, flags, flp6, res->nh->fib_nh_dev); else err = -EAGAIN; return err; } static int __fib6_rule_action(struct fib_rule *rule, struct flowi *flp, int flags, struct fib_lookup_arg *arg) { struct fib6_result *res = arg->result; struct flowi6 *flp6 = &flp->u.ip6; struct rt6_info *rt = NULL; struct fib6_table *table; struct net *net = rule->fr_net; pol_lookup_t lookup = arg->lookup_ptr; int err = 0; u32 tb_id; switch (rule->action) { case FR_ACT_TO_TBL: break; case FR_ACT_UNREACHABLE: err = -ENETUNREACH; rt = net->ipv6.ip6_null_entry; goto discard_pkt; default: case FR_ACT_BLACKHOLE: err = -EINVAL; rt = net->ipv6.ip6_blk_hole_entry; goto discard_pkt; case FR_ACT_PROHIBIT: err = -EACCES; rt = net->ipv6.ip6_prohibit_entry; goto discard_pkt; } tb_id = fib_rule_get_table(rule, arg); table = fib6_get_table(net, tb_id); if (!table) { err = -EAGAIN; goto out; } rt = lookup(net, table, flp6, arg->lookup_data, flags); if (rt != net->ipv6.ip6_null_entry) { err = fib6_rule_saddr(net, rule, flags, flp6, ip6_dst_idev(&rt->dst)->dev); if (err == -EAGAIN) goto again; err = rt->dst.error; if (err != -EAGAIN) goto out; } again: ip6_rt_put_flags(rt, flags); err = -EAGAIN; rt = NULL; goto out; discard_pkt: if (!(flags & RT6_LOOKUP_F_DST_NOREF)) dst_hold(&rt->dst); out: res->rt6 = rt; return err; } static int fib6_rule_action(struct fib_rule *rule, struct flowi *flp, int flags, struct fib_lookup_arg *arg) { if (arg->lookup_ptr == fib6_table_lookup) return fib6_rule_action_alt(rule, flp, flags, arg); return __fib6_rule_action(rule, flp, flags, arg); } static bool fib6_rule_suppress(struct fib_rule *rule, struct fib_lookup_arg *arg) { struct fib6_result *res = arg->result; struct rt6_info *rt = res->rt6; struct net_device *dev = NULL; if (!rt) return false; if (rt->rt6i_idev) dev = rt->rt6i_idev->dev; /* do not accept result if the route does * not meet the required prefix length */ if (rt->rt6i_dst.plen <= rule->suppress_prefixlen) goto suppress_route; /* do not accept result if the route uses a device * belonging to a forbidden interface group */ if (rule->suppress_ifgroup != -1 && dev && dev->group == rule->suppress_ifgroup) goto suppress_route; return false; suppress_route: ip6_rt_put(rt); return true; } static int fib6_rule_match(struct fib_rule *rule, struct flowi *fl, int flags) { struct fib6_rule *r = (struct fib6_rule *) rule; struct flowi6 *fl6 = &fl->u.ip6; if (r->dst.plen && !ipv6_prefix_equal(&fl6->daddr, &r->dst.addr, r->dst.plen)) return 0; /* * If FIB_RULE_FIND_SADDR is set and we do not have a * source address for the traffic, we defer check for * source address. */ if (r->src.plen) { if (flags & RT6_LOOKUP_F_HAS_SADDR) { if (!ipv6_prefix_equal(&fl6->saddr, &r->src.addr, r->src.plen)) return 0; } else if (!(r->common.flags & FIB_RULE_FIND_SADDR)) return 0; } if (r->tclass && r->tclass != ip6_tclass(fl6->flowlabel)) return 0; if (rule->ip_proto && (rule->ip_proto != fl6->flowi6_proto)) return 0; if (fib_rule_port_range_set(&rule->sport_range) && !fib_rule_port_inrange(&rule->sport_range, fl6->fl6_sport)) return 0; if (fib_rule_port_range_set(&rule->dport_range) && !fib_rule_port_inrange(&rule->dport_range, fl6->fl6_dport)) return 0; return 1; } static const struct nla_policy fib6_rule_policy[FRA_MAX+1] = { FRA_GENERIC_POLICY, }; static int fib6_rule_configure(struct fib_rule *rule, struct sk_buff *skb, struct fib_rule_hdr *frh, struct nlattr **tb, struct netlink_ext_ack *extack) { int err = -EINVAL; struct net *net = sock_net(skb->sk); struct fib6_rule *rule6 = (struct fib6_rule *) rule; if (rule->action == FR_ACT_TO_TBL && !rule->l3mdev) { if (rule->table == RT6_TABLE_UNSPEC) { NL_SET_ERR_MSG(extack, "Invalid table"); goto errout; } if (fib6_new_table(net, rule->table) == NULL) { err = -ENOBUFS; goto errout; } } if (frh->src_len) rule6->src.addr = nla_get_in6_addr(tb[FRA_SRC]); if (frh->dst_len) rule6->dst.addr = nla_get_in6_addr(tb[FRA_DST]); rule6->src.plen = frh->src_len; rule6->dst.plen = frh->dst_len; rule6->tclass = frh->tos; if (fib_rule_requires_fldissect(rule)) net->ipv6.fib6_rules_require_fldissect++; net->ipv6.fib6_has_custom_rules = true; err = 0; errout: return err; } static int fib6_rule_delete(struct fib_rule *rule) { struct net *net = rule->fr_net; if (net->ipv6.fib6_rules_require_fldissect && fib_rule_requires_fldissect(rule)) net->ipv6.fib6_rules_require_fldissect--; return 0; } static int fib6_rule_compare(struct fib_rule *rule, struct fib_rule_hdr *frh, struct nlattr **tb) { struct fib6_rule *rule6 = (struct fib6_rule *) rule; if (frh->src_len && (rule6->src.plen != frh->src_len)) return 0; if (frh->dst_len && (rule6->dst.plen != frh->dst_len)) return 0; if (frh->tos && (rule6->tclass != frh->tos)) return 0; if (frh->src_len && nla_memcmp(tb[FRA_SRC], &rule6->src.addr, sizeof(struct in6_addr))) return 0; if (frh->dst_len && nla_memcmp(tb[FRA_DST], &rule6->dst.addr, sizeof(struct in6_addr))) return 0; return 1; } static int fib6_rule_fill(struct fib_rule *rule, struct sk_buff *skb, struct fib_rule_hdr *frh) { struct fib6_rule *rule6 = (struct fib6_rule *) rule; frh->dst_len = rule6->dst.plen; frh->src_len = rule6->src.plen; frh->tos = rule6->tclass; if ((rule6->dst.plen && nla_put_in6_addr(skb, FRA_DST, &rule6->dst.addr)) || (rule6->src.plen && nla_put_in6_addr(skb, FRA_SRC, &rule6->src.addr))) goto nla_put_failure; return 0; nla_put_failure: return -ENOBUFS; } static size_t fib6_rule_nlmsg_payload(struct fib_rule *rule) { return nla_total_size(16) /* dst */ + nla_total_size(16); /* src */ } static const struct fib_rules_ops __net_initconst fib6_rules_ops_template = { .family = AF_INET6, .rule_size = sizeof(struct fib6_rule), .addr_size = sizeof(struct in6_addr), .action = fib6_rule_action, .match = fib6_rule_match, .suppress = fib6_rule_suppress, .configure = fib6_rule_configure, .delete = fib6_rule_delete, .compare = fib6_rule_compare, .fill = fib6_rule_fill, .nlmsg_payload = fib6_rule_nlmsg_payload, .nlgroup = RTNLGRP_IPV6_RULE, .policy = fib6_rule_policy, .owner = THIS_MODULE, .fro_net = &init_net, }; static int __net_init fib6_rules_net_init(struct net *net) { struct fib_rules_ops *ops; int err = -ENOMEM; ops = fib_rules_register(&fib6_rules_ops_template, net); if (IS_ERR(ops)) return PTR_ERR(ops); err = fib_default_rule_add(ops, 0, RT6_TABLE_LOCAL, 0); if (err) goto out_fib6_rules_ops; err = fib_default_rule_add(ops, 0x7FFE, RT6_TABLE_MAIN, 0); if (err) goto out_fib6_rules_ops; net->ipv6.fib6_rules_ops = ops; net->ipv6.fib6_rules_require_fldissect = 0; out: return err; out_fib6_rules_ops: fib_rules_unregister(ops); goto out; } static void __net_exit fib6_rules_net_exit(struct net *net) { rtnl_lock(); fib_rules_unregister(net->ipv6.fib6_rules_ops); rtnl_unlock(); } static struct pernet_operations fib6_rules_net_ops = { .init = fib6_rules_net_init, .exit = fib6_rules_net_exit, }; int __init fib6_rules_init(void) { return register_pernet_subsys(&fib6_rules_net_ops); } void fib6_rules_cleanup(void) { unregister_pernet_subsys(&fib6_rules_net_ops); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_1194_0
crossvul-cpp_data_bad_362_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT IIIII FFFFF FFFFF % % T I F F % % T I FFF FFF % % T I F F % % T IIIII F F % % % % % % Read/Write TIFF Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ #ifdef __VMS #define JPEG_SUPPORT 1 #endif /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/profile.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread_.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_TIFF_DELEGATE) # if defined(MAGICKCORE_HAVE_TIFFCONF_H) # include "tiffconf.h" # endif # include "tiff.h" # include "tiffio.h" # if !defined(COMPRESSION_ADOBE_DEFLATE) # define COMPRESSION_ADOBE_DEFLATE 8 # endif # if !defined(PREDICTOR_HORIZONTAL) # define PREDICTOR_HORIZONTAL 2 # endif # if !defined(TIFFTAG_COPYRIGHT) # define TIFFTAG_COPYRIGHT 33432 # endif # if !defined(TIFFTAG_OPIIMAGEID) # define TIFFTAG_OPIIMAGEID 32781 # endif #include "psd-private.h" /* Typedef declarations. */ typedef enum { ReadSingleSampleMethod, ReadRGBAMethod, ReadCMYKAMethod, ReadYCCKMethod, ReadStripMethod, ReadTileMethod, ReadGenericMethod } TIFFMethodType; typedef struct _PhotoshopProfile { StringInfo *data; MagickOffsetType offset; size_t length, extent, quantum; } PhotoshopProfile; #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) typedef struct _ExifInfo { unsigned int tag, type, variable_length; const char *property; } ExifInfo; static const ExifInfo exif_info[] = { { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" }, { EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" }, { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" }, { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" }, { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" }, { EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" }, { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" }, { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" }, { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" }, { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" }, { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" }, { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" }, { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" }, { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" }, { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" }, { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" }, { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" }, { EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" }, { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" }, { EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" }, { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" }, { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" }, { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" }, { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" }, { EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" }, { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" }, { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" }, { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" }, { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" }, { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" }, { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" }, { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" }, { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" }, { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" }, { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" }, { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" }, { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" }, { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" }, { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" }, { EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" }, { EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" }, { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" }, { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" }, { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" }, { EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" }, { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" }, { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" }, { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" }, { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" }, { EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" }, { EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" }, { EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" }, { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" }, { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" }, { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" }, { 0, 0, 0, (char *) NULL } }; #endif #endif /* MAGICKCORE_TIFF_DELEGATE */ /* Global declarations. */ static MagickThreadKey tiff_exception; static SemaphoreInfo *tiff_semaphore = (SemaphoreInfo *) NULL; static TIFFErrorHandler error_handler, warning_handler; static volatile MagickBooleanType instantiate_key = MagickFalse; /* Forward declarations. */ #if defined(MAGICKCORE_TIFF_DELEGATE) static Image * ReadTIFFImage(const ImageInfo *,ExceptionInfo *); static MagickBooleanType WriteGROUP4Image(const ImageInfo *,Image *,ExceptionInfo *), WritePTIFImage(const ImageInfo *,Image *,ExceptionInfo *), WriteTIFFImage(const ImageInfo *,Image *,ExceptionInfo *); static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset, const int whence,void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; switch (whence) { case SEEK_SET: default: { if (offset < 0) return(-1); profile->offset=offset; break; } case SEEK_CUR: { if ((profile->offset+offset) < 0) return(-1); profile->offset+=offset; break; } case SEEK_END: { if (((MagickOffsetType) profile->length+offset) < 0) return(-1); profile->offset=profile->length+offset; break; } } return(profile->offset); } static MagickOffsetType TIFFTellCustomStream(void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; return(profile->offset); } static void InitPSDInfo(const Image *image, PSDInfo *info) { info->version=1; info->columns=image->columns; info->rows=image->rows; /* Setting the mode to a value that won't change the colorspace */ info->mode=10; info->channels=1U; if (image->storage_class == PseudoClass) info->mode=2; // indexed mode else { info->channels=(unsigned short) image->number_channels; info->min_channels=info->channels; if (image->alpha_trait == BlendPixelTrait) info->min_channels--; } } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T I F F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTIFF() returns MagickTrue if the image format type, identified by the % magick string, is TIFF. % % The format of the IsTIFF method is: % % MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\115\115\000\052",4) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\052\000",4) == 0) return(MagickTrue); #if defined(TIFF_VERSION_BIG) if (length < 8) return(MagickFalse); if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0) return(MagickTrue); #endif return(MagickFalse); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadGROUP4Image method is: % % Image *ReadGROUP4Image(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline size_t WriteLSBLong(FILE *file,const size_t value) { unsigned char buffer[4]; buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); return(fwrite(buffer,1,4,file)); } static Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file); if (length != 10) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\000\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite("\001\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file); length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\021\001\003\000\001\000\000\000",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite("\022\001\003\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\026\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite("\032\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\033\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file); length=fwrite("\000\000\000\000",1,4,file); length=WriteLSBLong(file,(long) image->resolution.x); length=WriteLSBLong(file,1); status=MagickTrue; for (length=0; (c=ReadBlobByte(image)) != EOF; length++) if (fputc(c,file) != c) status=MagickFalse; offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); if (ferror(file) != 0) { (void) fclose(file); ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); } (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent); } (void) RelinquishUniqueFileResource(filename); if (status == MagickFalse) image=DestroyImage(image); return(image); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTIFFImage() reads a Tagged image file and returns it. It allocates the % memory necessary for the new Image structure and returns a pointer to the % new image. % % The format of the ReadTIFFImage method is: % % Image *ReadTIFFImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline unsigned char ClampYCC(double value) { value=255.0-value; if (value < 0.0) return((unsigned char)0); if (value > 255.0) return((unsigned char)255); return((unsigned char)(value)); } static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(image,q)+0.5; if (a > 1.0) a-=1.0; b=QuantumScale*GetPixelb(image,q)+0.5; if (b > 1.0) b-=1.0; SetPixela(image,QuantumRange*a,q); SetPixelb(image,QuantumRange*b,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) { status=MagickFalse; break; } } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType ReadProfile(Image *image,const char *name, const unsigned char *datum,ssize_t length,ExceptionInfo *exception) { MagickBooleanType status; StringInfo *profile; if (length < 4) return(MagickFalse); profile=BlobToStringInfo(datum,(size_t) length); if (profile == (StringInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=SetImageProfile(image,name,profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); return(MagickTrue); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int TIFFCloseBlob(thandle_t image) { (void) CloseBlob((Image *) image); return(0); } static void TIFFErrors(const char *module,const char *format,va_list error) { char message[MagickPathExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MagickPathExtent,format,error); #else (void) vsprintf(message,format,error); #endif (void) ConcatenateMagickString(message,".",MagickPathExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message, "`%s'",module); } static toff_t TIFFGetBlobSize(thandle_t image) { return((toff_t) GetBlobSize((Image *) image)); } static void TIFFGetProfiles(TIFF *tiff,Image *image,ExceptionInfo *exception) { uint32 length; unsigned char *profile; length=0; #if defined(TIFFTAG_ICCPROFILE) if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"icc",profile,(ssize_t) length,exception); #endif #if defined(TIFFTAG_PHOTOSHOP) if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"8bim",profile,(ssize_t) length,exception); #endif #if defined(TIFFTAG_RICHTIFFIPTC) if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) { if (TIFFIsByteSwapped(tiff) != 0) TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length); (void) ReadProfile(image,"iptc",profile,4L*length,exception); } #endif #if defined(TIFFTAG_XMLPACKET) if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"xmp",profile,(ssize_t) length,exception); #endif if ((TIFFGetField(tiff,34118,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length, exception); if ((TIFFGetField(tiff,37724,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception); } static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception) { char message[MagickPathExtent], *text; uint32 count, length, type; unsigned long *tietz; if ((TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:artist",text,exception); if ((TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:copyright",text,exception); if ((TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:timestamp",text,exception); if ((TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:document",text,exception); if ((TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:hostcomputer",text,exception); if ((TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"comment",text,exception); if ((TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:make",text,exception); if ((TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:model",text,exception); if ((TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) && (text != (char *) NULL)) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message,exception); } if ((TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"label",text,exception); if ((TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:software",text,exception); if ((TIFFGetField(tiff,33423,&count,&text) == 1) && (text != (char *) NULL)) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message,exception); } if ((TIFFGetField(tiff,36867,&count,&text) == 1) && (text != (char *) NULL)) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message,exception); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE", exception); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK",exception); break; } default: break; } if ((TIFFGetField(tiff,37706,&length,&tietz) == 1) && (tietz != (unsigned long *) NULL)) { (void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]); (void) SetImageProperty(image,"tiff:tietz_offset",message,exception); } } static void TIFFGetEXIFProperties(TIFF *tiff,Image *image, ExceptionInfo *exception) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) char value[MagickPathExtent]; register ssize_t i; tdir_t directory; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif offset; void *sans[2] = { NULL, NULL }; /* Read EXIF properties. */ offset=0; if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1) return; directory=TIFFCurrentDirectory(tiff); if (TIFFReadEXIFDirectory(tiff,offset) != 1) { TIFFSetDirectory(tiff,directory); return; } for (i=0; exif_info[i].tag != 0; i++) { *value='\0'; switch (exif_info[i].type) { case TIFF_ASCII: { char *ascii; ascii=(char *) NULL; if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,sans) == 1) && (ascii != (char *) NULL) && (*ascii != '\0')) (void) CopyMagickString(value,ascii,MagickPathExtent); break; } case TIFF_SHORT: { if (exif_info[i].variable_length == 0) { uint16 shorty; shorty=0; if (TIFFGetField(tiff,exif_info[i].tag,&shorty,sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d",shorty); } else { int tiff_status; uint16 *shorty; uint16 shorty_num; tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty, sans); if (tiff_status == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d", shorty_num != 0 ? shorty[0] : 0); } break; } case TIFF_LONG: { uint32 longy; longy=0; if (TIFFGetField(tiff,exif_info[i].tag,&longy,sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%d",longy); break; } #if defined(TIFF_VERSION_BIG) case TIFF_LONG8: { uint64 long8y; long8y=0; if (TIFFGetField(tiff,exif_info[i].tag,&long8y,sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) ((MagickOffsetType) long8y)); break; } #endif case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float floaty; floaty=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&floaty,sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%g",(double) floaty); break; } case TIFF_DOUBLE: { double doubley; doubley=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&doubley,sans) == 1) (void) FormatLocaleString(value,MagickPathExtent,"%g",doubley); break; } default: break; } if (*value != '\0') (void) SetImageProperty(image,exif_info[i].property,value,exception); } TIFFSetDirectory(tiff,directory); #else (void) tiff; (void) image; #endif } static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size) { *base=(tdata_t *) GetBlobStreamData((Image *) image); if (*base != (tdata_t *) NULL) *size=(toff_t) GetBlobSize((Image *) image); if (*base != (tdata_t *) NULL) return(1); return(0); } static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) ReadBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static int32 TIFFReadPixels(TIFF *tiff,const tsample_t sample,const ssize_t row, tdata_t scanline) { int32 status; status=TIFFReadScanline(tiff,scanline,(uint32) row,sample); return(status); } static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence) { return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence)); } static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size) { (void) image; (void) base; (void) size; } static void TIFFWarnings(const char *module,const char *format,va_list warning) { char message[MagickPathExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MagickPathExtent,format,warning); #else (void) vsprintf(message,format,warning); #endif (void) ConcatenateMagickString(message,".",MagickPathExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'",module); } static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) WriteBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric, uint16 bits_per_sample,uint16 samples_per_pixel) { #define BUFFER_SIZE 2048 MagickOffsetType position, offset; register size_t i; TIFFMethodType method; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif *value; unsigned char buffer[BUFFER_SIZE+32]; unsigned short length; /* Only support 8 bit for now. */ if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) || (samples_per_pixel != 4)) return(ReadGenericMethod); /* Search for Adobe APP14 JPEG marker. */ value=NULL; if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value) || (value == NULL)) return(ReadRGBAMethod); position=TellBlob(image); offset=(MagickOffsetType) (value[0]); if (SeekBlob(image,offset,SEEK_SET) != offset) return(ReadRGBAMethod); method=ReadRGBAMethod; if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE) { for (i=0; i < BUFFER_SIZE; i++) { while (i < BUFFER_SIZE) { if (buffer[i++] == 255) break; } while (i < BUFFER_SIZE) { if (buffer[++i] != 255) break; } if (buffer[i++] == 216) /* JPEG_MARKER_SOI */ continue; length=(unsigned short) (((unsigned int) (buffer[i] << 8) | (unsigned int) buffer[i+1]) & 0xffff); if (i+(size_t) length >= BUFFER_SIZE) break; if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */ { if (length != 14) break; /* 0 == CMYK, 1 == YCbCr, 2 = YCCK */ if (buffer[i+13] == 2) method=ReadYCCKMethod; break; } i+=(size_t) length; } } (void) SeekBlob(image,position,SEEK_SET); return(method); } static ssize_t TIFFReadCustomStream(unsigned char *data,const size_t count, void *user_data) { PhotoshopProfile *profile; size_t total; ssize_t remaining; if (count == 0) return(0); profile=(PhotoshopProfile *) user_data; remaining=(MagickOffsetType) profile->length-profile->offset; if (remaining <= 0) return(-1); total=MagickMin(count, (size_t) remaining); (void) memcpy(data,profile->data->datum+profile->offset,total); profile->offset+=total; return(total); } static CustomStreamInfo *TIFFAcquireCustomStreamForReading( PhotoshopProfile *profile,ExceptionInfo *exception) { CustomStreamInfo *custom_stream; custom_stream=AcquireCustomStreamInfo(exception); if (custom_stream == (CustomStreamInfo *) NULL) return(custom_stream); SetCustomStreamData(custom_stream,(void *) profile); SetCustomStreamReader(custom_stream,TIFFReadCustomStream); SetCustomStreamSeeker(custom_stream,TIFFSeekCustomStream); SetCustomStreamTeller(custom_stream,TIFFTellCustomStream); return(custom_stream); } static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; const StringInfo *profile; CustomStreamInfo *custom_stream; Image *layers; PhotoshopProfile photoshop_profile; PSDInfo info; register ssize_t i; if (GetImageListLength(image) != 1) return; if ((image_info->number_scenes == 1) && (image_info->scene == 0)) return; option=GetImageOption(image_info,"tiff:ignore-layers"); if (option != (const char * ) NULL) return; profile=GetImageProfile(image,"tiff:37724"); if (profile == (const StringInfo *) NULL) return; for (i=0; i < (ssize_t) profile->length-8; i++) { if (LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0) continue; i+=4; if ((LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) || (LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) || (LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) || (LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0)) break; } i+=4; if (i >= (ssize_t) (profile->length-8)) return; photoshop_profile.data=(StringInfo *) profile; photoshop_profile.length=profile->length; custom_stream=TIFFAcquireCustomStreamForReading(&photoshop_profile,exception); if (custom_stream == (CustomStreamInfo *) NULL) return; layers=CloneImage(image,0,0,MagickTrue,exception); if (layers == (Image *) NULL) { custom_stream=DestroyCustomStreamInfo(custom_stream); return; } (void) DeleteImageProfile(layers,"tiff:37724"); AttachCustomStream(layers->blob,custom_stream); SeekBlob(layers,(MagickOffsetType) i,SEEK_SET); InitPSDInfo(layers,&info); (void) ReadPSDLayers(layers,image_info,&info,exception); DeleteImageFromList(&layers); if (layers != (Image *) NULL) { SetImageArtifact(image,"tiff:has-layers","true"); AppendImageToList(&image,layers); while (layers != (Image *) NULL) { SetImageArtifact(layers,"tiff:has-layers","true"); DetachBlob(layers->blob); layers=GetNextImageInList(layers); } } custom_stream=DestroyCustomStreamInfo(custom_stream); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define ThrowTIFFException(severity,message) \ { \ if (tiff_pixels != (unsigned char *) NULL) \ tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); \ if (quantum_info != (QuantumInfo *) NULL) \ quantum_info=DestroyQuantumInfo(quantum_info); \ TIFFClose(tiff); \ ThrowReaderException(severity,message); \ } const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType more_frames, status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *tiff_pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } more_frames=MagickTrue; do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning photometric=PHOTOMETRIC_RGB; if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point", exception); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black", exception); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white", exception); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette",exception); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB",exception); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB",exception); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)", exception); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV",exception); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK",exception); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated",exception); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR",exception); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown",exception); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric", exception)); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb",exception); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb",exception); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace,exception); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace,exception); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace,exception); TIFFGetProfiles(tiff,image,exception); TIFFGetProperties(tiff,image,exception); option=GetImageOption(image_info,"tiff:exif-properties"); if (IsStringFalse(option) == MagickFalse) /* enabled by default */ TIFFGetEXIFProperties(tiff,image,exception); (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->resolution.x=x_resolution; image->resolution.y=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5); image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MagickPathExtent]; uint16 horizontal, vertical; tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal, &vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MagickPathExtent, "%dx%d",horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor,exception); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } quantum_info=(QuantumInfo *) NULL; if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors,exception) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } value=(unsigned short) image->scene; if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { TIFFClose(tiff); return(DestroyImageList(image)); } status=ResetImagePixels(image,exception); if (status == MagickFalse) { TIFFClose(tiff); return(DestroyImageList(image)); } /* Allocate memory for the image and pixel buffer. */ tiff_pixels=(unsigned char *) NULL; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified",exception); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->alpha_trait=BlendPixelTrait; } else for (i=0; i < extra_samples; i++) { image->alpha_trait=BlendPixelTrait; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated", exception); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated", exception); } } if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); method=ReadGenericMethod; rows_per_strip=(uint32) image->rows; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char buffer[MagickPathExtent]; method=ReadStripMethod; (void) FormatLocaleString(buffer,MagickPathExtent,"%u", (unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",buffer,exception); } if (rows_per_strip > (uint32) image->rows) rows_per_strip=(uint32) image->rows; if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG)) if ((image->alpha_trait == UndefinedPixelTrait) || (samples_per_pixel >= 4)) method=ReadRGBAMethod; if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE)) if ((image->alpha_trait == UndefinedPixelTrait) || (samples_per_pixel >= 5)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; if (TIFFScanlineSize(tiff) <= 0) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (((MagickSizeType) TIFFScanlineSize(tiff)) > GetBlobSize(image)) ThrowTIFFException(CorruptImageError,"InsufficientImageDataInFile"); number_pixels=MagickMax(TIFFScanlineSize(tiff),MagickMax((ssize_t) image->columns*samples_per_pixel*pow(2.0,ceil(log(bits_per_sample)/ log(2.0))),image->columns*rows_per_strip)*sizeof(uint32)); tiff_pixels=(unsigned char *) AcquireMagickMemory(number_pixels); if (tiff_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(tiff_pixels,0,number_pixels); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); if (image->alpha_trait != UndefinedPixelTrait) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; tiff_status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels); if (tiff_status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; tiff_status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels); if (tiff_status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; tiff_status=TIFFReadPixels(tiff,(tsample_t) i,y,(char *) tiff_pixels); if (tiff_status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; unsigned char *p; tiff_status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels); if (tiff_status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=tiff_pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456)),q); SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984)),q); SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816)),q); SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q); q+=GetPixelChannels(image); p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) tiff_pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) tiff_pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p))),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p))),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p))),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) ThrowTIFFException(CoderError,"ImageIsNotTiled"); if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) || (AcquireMagickResource(HeightResource,rows) == MagickFalse)) ThrowTIFFException(ImageError,"WidthOrHeightExceedsLimit"); (void) SetImageStorageClass(image,DirectClass,exception); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows* sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y+=rows) { register ssize_t x; register Quantum *magick_restrict q, *magick_restrict tile; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+ x); for (row=rows_remaining; row > 0; row--) { if (image->alpha_trait != UndefinedPixelTrait) for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p++; q+=GetPixelChannels(image); } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); p++; q+=GetPixelChannels(image); } p+=columns-columns_remaining; q-=GetPixelChannels(image)*(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; q+=GetPixelChannels(image)*(image->columns-1); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p--; q-=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (more_frames != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while ((status != MagickFalse) && (more_frames != MagickFalse)); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if ((image_info->number_scenes != 0) && (image_info->scene >= GetImageListLength(image))) status=MagickFalse; if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterTIFFImage() adds properties for the TIFF image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterTIFFImage method is: % % size_t RegisterTIFFImage(void) % */ #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) static TIFFExtendProc tag_extender = (TIFFExtendProc) NULL; static void TIFFIgnoreTags(TIFF *tiff) { char *q; const char *p, *tags; Image *image; register ssize_t i; size_t count; TIFFFieldInfo *ignore; if (TIFFGetReadProc(tiff) != TIFFReadBlob) return; image=(Image *)TIFFClientdata(tiff); tags=GetImageArtifact(image,"tiff:ignore-tags"); if (tags == (const char *) NULL) return; count=0; p=tags; while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; (void) strtol(p,&q,10); if (p == q) return; p=q; count++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (count == 0) return; i=0; p=tags; ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore)); if (ignore == (TIFFFieldInfo *) NULL) return; /* This also sets field_bit to 0 (FIELD_IGNORE) */ memset(ignore,0,count*sizeof(*ignore)); while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; ignore[i].field_tag=(ttag_t) strtol(p,&q,10); p=q; i++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } (void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count); ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore); } static void TIFFTagExtender(TIFF *tiff) { static const TIFFFieldInfo TIFFExtensions[] = { { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "PhotoshopLayerData" }, { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "Microscope" } }; TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/ sizeof(*TIFFExtensions)); if (tag_extender != (TIFFExtendProc) NULL) (*tag_extender)(tiff); TIFFIgnoreTags(tiff); } #endif ModuleExport size_t RegisterTIFFImage(void) { #define TIFFDescription "Tagged Image File Format" char version[MagickPathExtent]; MagickInfo *entry; if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key == MagickFalse) { if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); error_handler=TIFFSetErrorHandler(TIFFErrors); warning_handler=TIFFSetWarningHandler(TIFFWarnings); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) tag_extender=TIFFSetTagExtender(TIFFTagExtender); #endif instantiate_key=MagickTrue; } UnlockSemaphoreInfo(tiff_semaphore); *version='\0'; #if defined(TIFF_VERSION) (void) FormatLocaleString(version,MagickPathExtent,"%d",TIFF_VERSION); #endif #if defined(MAGICKCORE_TIFF_DELEGATE) { const char *p; register ssize_t i; p=TIFFGetVersion(); for (i=0; (i < (MagickPathExtent-1)) && (*p != 0) && (*p != '\n'); i++) version[i]=(*p++); version[i]='\0'; } #endif entry=AcquireMagickInfo("TIFF","GROUP4","Raw CCITT Group4"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadGROUP4Image; entry->encoder=(EncodeImageHandler *) WriteGROUP4Image; #endif entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderUseExtensionFlag; entry->format_type=ImplicitFormatType; entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","PTIF","Pyramid encoded TIFF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WritePTIFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags^=CoderUseExtensionFlag; entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIF",TIFFDescription); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags|=CoderStealthFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIFF",TIFFDescription); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->magick=(IsImageFormatHandler *) IsTIFF; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIFF64","Tagged Image File Format (64-bit)"); #if defined(TIFF_VERSION_BIG) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterTIFFImage() removes format registrations made by the TIFF module % from the list of supported formats. % % The format of the UnregisterTIFFImage method is: % % UnregisterTIFFImage(void) % */ ModuleExport void UnregisterTIFFImage(void) { (void) UnregisterMagickInfo("TIFF64"); (void) UnregisterMagickInfo("TIFF"); (void) UnregisterMagickInfo("TIF"); (void) UnregisterMagickInfo("PTIF"); if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key != MagickFalse) { #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) (void) TIFFSetTagExtender(tag_extender); #endif if (DeleteMagickThreadKey(tiff_exception) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); instantiate_key=MagickFalse; } UnlockSemaphoreInfo(tiff_semaphore); RelinquishSemaphoreInfo(&tiff_semaphore); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format. % % The format of the WriteGROUP4Image method is: % % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, % Image *image,ExceptionInfo *) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *huffman_image; ImageInfo *write_info; int unique_file; MagickBooleanType status; register ssize_t i; ssize_t count; TIFF *tiff; toff_t *byte_count, strip_size; unsigned char *buffer; /* Write image as CCITT Group4 TIFF image to a temporary file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); huffman_image=CloneImage(image,0,0,MagickTrue,exception); if (huffman_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } huffman_image->endian=MSBEndian; file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MagickPathExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType,exception); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageDepth(image,1,exception); (void) SetImageType(image,BilevelType,exception); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image,exception); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } tiff=TIFFOpen(filename,"rb"); if (tiff == (TIFF *) NULL) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError,"UnableToOpenFile", image_info->filename); return(MagickFalse); } /* Allocate raw strip buffer. */ if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } strip_size=byte_count[0]; for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) if (byte_count[i] > strip_size) strip_size=byte_count[i]; buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image_info->filename); } /* Compress runlength encoded to 2D Huffman pixels. */ for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) { count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size); if (WriteBlob(image,(size_t) count,buffer) != count) status=MagickFalse; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); (void) CloseBlob(image); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P T I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file % format. % % The format of the WritePTIFImage method is: % % MagickBooleanType WritePTIFImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePTIFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { Image *images, *next, *pyramid_image; ImageInfo *write_info; MagickBooleanType status; PointInfo resolution; size_t columns, rows; /* Create pyramid-encoded TIFF image. */ images=NewImageList(); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { Image *clone_image; clone_image=CloneImage(next,0,0,MagickFalse,exception); if (clone_image == (Image *) NULL) break; clone_image->previous=NewImageList(); clone_image->next=NewImageList(); (void) SetImageProperty(clone_image,"tiff:subfiletype","none",exception); AppendImageToList(&images,clone_image); columns=next->columns; rows=next->rows; resolution=next->resolution; while ((columns > 64) && (rows > 64)) { columns/=2; rows/=2; resolution.x/=2; resolution.y/=2; pyramid_image=ResizeImage(next,columns,rows,image->filter,exception); if (pyramid_image == (Image *) NULL) break; pyramid_image->resolution=resolution; (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE", exception); AppendImageToList(&images,pyramid_image); } } status=MagickFalse; if (images != (Image *) NULL) { /* Write pyramid-encoded TIFF image. */ images=GetFirstImageInList(images); write_info=CloneImageInfo(image_info); write_info->adjoin=MagickTrue; (void) CopyMagickString(write_info->magick,"TIFF",MagickPathExtent); (void) CopyMagickString(images->magick,"TIFF",MagickPathExtent); status=WriteTIFFImage(write_info,images,exception); images=DestroyImageList(images); write_info=DestroyImageInfo(write_info); } return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W r i t e T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteTIFFImage() writes an image in the Tagged image file format. % % The format of the WriteTIFFImage method is: % % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ typedef struct _TIFFInfo { RectangleInfo tile_geometry; unsigned char *scanline, *scanlines, *pixels; } TIFFInfo; static void DestroyTIFFInfo(TIFFInfo *tiff_info) { assert(tiff_info != (TIFFInfo *) NULL); if (tiff_info->scanlines != (unsigned char *) NULL) tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory( tiff_info->scanlines); if (tiff_info->pixels != (unsigned char *) NULL) tiff_info->pixels=(unsigned char *) RelinquishMagickMemory( tiff_info->pixels); } static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(image,q)-0.5; if (a < 0.0) a+=1.0; b=QuantumScale*GetPixelb(image,q)-0.5; if (b < 0.0) b+=1.0; SetPixela(image,QuantumRange*a,q); SetPixelb(image,QuantumRange*b,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) { status=MagickFalse; break; } } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info, TIFF *tiff,TIFFInfo *tiff_info) { const char *option; MagickStatusType flags; uint32 tile_columns, tile_rows; assert(tiff_info != (TIFFInfo *) NULL); (void) memset(tiff_info,0,sizeof(*tiff_info)); option=GetImageOption(image_info,"tiff:tile-geometry"); if (option == (const char *) NULL) { uint32 rows_per_strip; option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(size_t) strtol(option,(char **) NULL,10); else if (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows_per_strip) == 0) rows_per_strip=0; /* use default */ rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); return(MagickTrue); } /* Create tiled TIFF, ignore "tiff:rows-per-strip". */ flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry); if ((flags & HeightValue) == 0) tiff_info->tile_geometry.height=tiff_info->tile_geometry.width; tile_columns=(uint32) tiff_info->tile_geometry.width; tile_rows=(uint32) tiff_info->tile_geometry.height; TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows); (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns); (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows); tiff_info->tile_geometry.width=tile_columns; tiff_info->tile_geometry.height=tile_rows; if ((TIFFScanlineSize(tiff) <= 0) || (TIFFTileSize(tiff) <= 0)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines)); tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines)); if ((tiff_info->scanlines == (unsigned char *) NULL) || (tiff_info->pixels == (unsigned char *) NULL)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } return(MagickTrue); } static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row, tsample_t sample,Image *image) { int32 status; register ssize_t i; register unsigned char *p, *q; size_t number_tiles, tile_width; ssize_t bytes_per_pixel, j, k, l; if (TIFFIsTiled(tiff) == 0) return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample)); /* Fill scanlines to tile height. */ i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff); (void) memcpy(tiff_info->scanlines+i,(char *) tiff_info->scanline, (size_t) TIFFScanlineSize(tiff)); if (((size_t) (row % tiff_info->tile_geometry.height) != (tiff_info->tile_geometry.height-1)) && (row != (ssize_t) (image->rows-1))) return(0); /* Write tile to TIFF image. */ status=0; bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) ( tiff_info->tile_geometry.height*tiff_info->tile_geometry.width); number_tiles=(image->columns+tiff_info->tile_geometry.width)/ tiff_info->tile_geometry.width; for (i=0; i < (ssize_t) number_tiles; i++) { tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i* tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width; for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++) for (k=0; k < (ssize_t) tile_width; k++) { if (bytes_per_pixel == 0) { p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)/8); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8); *q++=(*p++); continue; } p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)*bytes_per_pixel); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel); for (l=0; l < bytes_per_pixel; l++) *q++=(*p++); } if ((i*tiff_info->tile_geometry.width) != image->columns) status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i* tiff_info->tile_geometry.width),(uint32) ((row/ tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0, sample); if (status < 0) break; } return(status); } static ssize_t TIFFWriteCustomStream(unsigned char *data,const size_t count, void *user_data) { PhotoshopProfile *profile; if (count == 0) return(0); profile=(PhotoshopProfile *) user_data; if ((profile->offset+(MagickOffsetType) count) >= (MagickOffsetType) profile->extent) { profile->extent+=count+profile->quantum; profile->quantum<<=1; SetStringInfoLength(profile->data,profile->extent); } (void) memcpy(profile->data->datum+profile->offset,data,count); profile->offset+=count; return(count); } static CustomStreamInfo *TIFFAcquireCustomStreamForWriting( PhotoshopProfile *profile,ExceptionInfo *exception) { CustomStreamInfo *custom_stream; custom_stream=AcquireCustomStreamInfo(exception); if (custom_stream == (CustomStreamInfo *) NULL) return(custom_stream); SetCustomStreamData(custom_stream,(void *) profile); SetCustomStreamWriter(custom_stream,TIFFWriteCustomStream); SetCustomStreamSeeker(custom_stream,TIFFSeekCustomStream); SetCustomStreamTeller(custom_stream,TIFFTellCustomStream); return(custom_stream); } static MagickBooleanType TIFFWritePhotoshopLayers(Image* image, const ImageInfo *image_info,EndianType endian,ExceptionInfo *exception) { BlobInfo *blob; CustomStreamInfo *custom_stream; Image *base_image, *next; ImageInfo *clone_info; MagickBooleanType status; PhotoshopProfile profile; PSDInfo info; StringInfo *layers; base_image=CloneImage(image,0,0,MagickFalse,exception); if (base_image == (Image *) NULL) return(MagickTrue); clone_info=CloneImageInfo(image_info); if (clone_info == (ImageInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); profile.offset=0; profile.quantum=MagickMinBlobExtent; layers=AcquireStringInfo(profile.quantum); if (layers == (StringInfo *) NULL) { clone_info=DestroyImageInfo(clone_info); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } profile.data=layers; profile.extent=layers->length; custom_stream=TIFFAcquireCustomStreamForWriting(&profile,exception); if (custom_stream == (CustomStreamInfo *) NULL) { clone_info=DestroyImageInfo(clone_info); layers=DestroyStringInfo(layers); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } blob=CloneBlobInfo((BlobInfo *) NULL); if (blob == (BlobInfo *) NULL) { clone_info=DestroyImageInfo(clone_info); layers=DestroyStringInfo(layers); custom_stream=DestroyCustomStreamInfo(custom_stream); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } DestroyBlob(base_image); base_image->blob=blob; next=base_image; while (next != (Image *) NULL) next=SyncNextImageInList(next); AttachCustomStream(base_image->blob,custom_stream); InitPSDInfo(image,&info); base_image->endian=endian; WriteBlobString(base_image,"Adobe Photoshop Document Data Block"); WriteBlobByte(base_image,0); WriteBlobString(base_image,base_image->endian == LSBEndian ? "MIB8ryaL" : "8BIMLayr"); status=WritePSDLayers(base_image,clone_info,&info,exception); if (status != MagickFalse) { SetStringInfoLength(layers,(size_t) profile.offset); status=SetImageProfile(image,"tiff:37724",layers,exception); } next=base_image; while (next != (Image *) NULL) { CloseBlob(next); next=next->next; } layers=DestroyStringInfo(layers); clone_info=DestroyImageInfo(clone_info); custom_stream=DestroyCustomStreamInfo(custom_stream); return(status); } static void TIFFSetProfiles(TIFF *tiff,Image *image) { const char *name; const StringInfo *profile; if (image->profiles == (void *) NULL) return; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (GetStringInfoLength(profile) == 0) { name=GetNextImageProfile(image); continue; } #if defined(TIFFTAG_XMLPACKET) if (LocaleCompare(name,"xmp") == 0) (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif #if defined(TIFFTAG_ICCPROFILE) if (LocaleCompare(name,"icc") == 0) (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"iptc") == 0) { size_t length; StringInfo *iptc_profile; iptc_profile=CloneStringInfo(profile); length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) & 0x03); SetStringInfoLength(iptc_profile,length); if (TIFFIsByteSwapped(tiff)) TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile), (unsigned long) (length/4)); (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32) GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile)); iptc_profile=DestroyStringInfo(iptc_profile); } #if defined(TIFFTAG_PHOTOSHOP) if (LocaleCompare(name,"8bim") == 0) (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32) GetStringInfoLength(profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"tiff:37724") == 0) (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); if (LocaleCompare(name,"tiff:34118") == 0) (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); name=GetNextImageProfile(image); } } static void TIFFSetProperties(TIFF *tiff,const MagickBooleanType adjoin, Image *image,ExceptionInfo *exception) { const char *value; value=GetImageArtifact(image,"tiff:document"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value); value=GetImageArtifact(image,"tiff:hostcomputer"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value); value=GetImageArtifact(image,"tiff:artist"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value); value=GetImageArtifact(image,"tiff:timestamp"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value); value=GetImageArtifact(image,"tiff:make"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MAKE,value); value=GetImageArtifact(image,"tiff:model"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MODEL,value); value=GetImageArtifact(image,"tiff:software"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value); value=GetImageArtifact(image,"tiff:copyright"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value); value=GetImageArtifact(image,"kodak-33423"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,33423,value); value=GetImageArtifact(image,"kodak-36867"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,36867,value); value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value); value=GetImageArtifact(image,"tiff:subfiletype"); if (value != (const char *) NULL) { if (LocaleCompare(value,"REDUCEDIMAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); else if (LocaleCompare(value,"PAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); else if (LocaleCompare(value,"MASK") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK); } else { uint16 page, pages; page=(uint16) image->scene; pages=(uint16) GetImageListLength(image); if ((adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } } static void TIFFSetEXIFProperties(TIFF *tiff,Image *image, ExceptionInfo *exception) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) const char *value; register ssize_t i; uint32 offset; /* Write EXIF properties. */ offset=0; (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset); for (i=0; exif_info[i].tag != 0; i++) { value=GetImageProperty(image,exif_info[i].property,exception); if (value == (const char *) NULL) continue; switch (exif_info[i].type) { case TIFF_ASCII: { (void) TIFFSetField(tiff,exif_info[i].tag,value); break; } case TIFF_SHORT: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_LONG: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_RATIONAL: case TIFF_SRATIONAL: { float field; field=StringToDouble(value,(char **) NULL); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } default: break; } } /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */ #else (void) tiff; (void) image; #endif } static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType adjoin, debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t imageListLength, length; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric, predictor; unsigned char *pixels; /* Open TIFF file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) SetMagickThreadValue(tiff_exception,exception); endian_type=(HOST_FILLORDER == FILLORDER_LSB2MSB) ? LSBEndian : MSBEndian; option=GetImageOption(image_info,"tiff:endian"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,"lsb",3) == 0) endian_type=LSBEndian; } mode=endian_type == LSBEndian ? "wl" : "wb"; #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) mode=endian_type == LSBEndian ? "wl8" : "wb8"; #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); scene=0; debug=IsEventLogging(); (void) debug; adjoin=image_info->adjoin; imageListLength=GetImageListLength(image); do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type,exception); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType,exception); (void) SetImageDepth(image,1,exception); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { quantum_info=DestroyQuantumInfo(quantum_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } } if ((LocaleCompare(image_info->magick,"PTIF") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->alpha_trait == UndefinedPixelTrait)) SetImageMonochrome(image,exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } else if ((compress_tag == COMPRESSION_CCITTFAX4) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } option=GetImageOption(image_info,"tiff:fill-order"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,"lsb",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->alpha_trait != UndefinedPixelTrait) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,"tiff:alpha"); if (option != (const char *) NULL) { if (LocaleCompare(option,"associated") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,"unspecified") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); predictor=0; switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); if (image->colorspace == YCbCrColorspace) { const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor",exception); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: break; #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; break; } default: break; } option=GetImageOption(image_info,"tiff:predictor"); if (option != (const char * ) NULL) predictor=(size_t) strtol(option,(char **) NULL,10); if (predictor != 0) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor); if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "TIFF: negative image positions unsupported","%s",image->filename); if ((image->page.x > 0) && (image->resolution.x > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->resolution.x); } if ((image->page.y > 0) && (image->resolution.y > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->resolution.y); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } option=GetImageOption(image_info,"tiff:write-layers"); if (IsStringTrue(option) != MagickFalse) { (void) TIFFWritePhotoshopLayers(image,image_info,endian_type,exception); adjoin=MagickFalse; } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (adjoin != MagickFalse) && (imageListLength > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, imageListLength); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) imageListLength; if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,adjoin,image,exception); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image,exception); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=(unsigned char *) GetQuantumPixels(quantum_info); tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) length; if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->alpha_trait != UndefinedPixelTrait) for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) { if (red != (uint16 *) NULL) red=(uint16 *) RelinquishMagickMemory(red); if (green != (uint16 *) NULL) green=(uint16 *) RelinquishMagickMemory(green); if (blue != (uint16 *) NULL) blue=(uint16 *) RelinquishMagickMemory(blue); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialize TIFF colormap. */ (void) memset(red,0,65536*sizeof(*red)); (void) memset(green,0,65536*sizeof(*green)); (void) memset(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->alpha_trait != UndefinedPixelTrait) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,exception); DestroyTIFFInfo(&tiff_info); DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-772/c/bad_362_0
crossvul-cpp_data_bad_2567_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N GGGG % % P P NN N G % % PPPP N N N G GG % % P N NN G G % % P N N GGG % % % % % % Read/Write Portable Network Graphics Image Format % % % % Software Design % % Cristy % % Glenn Randers-Pehrson % % November 1997 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ #define IM /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/MagickCore.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_PNG_DELEGATE) /* Suppress libpng pedantic warnings that were added in * libpng-1.2.41 and libpng-1.4.0. If you are working on * migration to libpng-1.5, remove these defines and then * fix any code that generates warnings. */ /* #define PNG_DEPRECATED Use of this function is deprecated */ /* #define PNG_USE_RESULT The result of this function must be checked */ /* #define PNG_NORETURN This function does not return */ /* #define PNG_ALLOCATED The result of the function is new memory */ /* #define PNG_DEPSTRUCT Access to this struct member is deprecated */ /* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */ #define PNG_PTR_NORETURN #include "png.h" #include "zlib.h" /* ImageMagick differences */ #define first_scene scene #if PNG_LIBPNG_VER > 10011 /* Optional declarations. Define or undefine them as you like. */ /* #define PNG_DEBUG -- turning this on breaks VisualC compiling */ /* After eXIf chunk has been approved: #define eXIf_SUPPORTED */ /* Experimental; define one or both of these: #define exIf_SUPPORTED */ /* Features under construction. Define these to work on them. */ #undef MNG_OBJECT_BUFFERS #undef MNG_BASI_SUPPORTED #define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */ #define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */ #if defined(MAGICKCORE_JPEG_DELEGATE) # define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */ #endif #if !defined(RGBColorMatchExact) #define IsPNGColorEqual(color,target) \ (((color).red == (target).red) && \ ((color).green == (target).green) && \ ((color).blue == (target).blue)) #endif /* Table of recognized sRGB ICC profiles */ struct sRGB_info_struct { png_uint_32 len; png_uint_32 crc; png_byte intent; }; const struct sRGB_info_struct sRGB_info[] = { /* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */ { 3048, 0x3b8772b9UL, 0}, /* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */ { 3052, 0x427ebb21UL, 1}, /* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */ {60988, 0x306fd8aeUL, 0}, /* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */ {60960, 0xbbef7812UL, 0}, /* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */ { 3024, 0x5d5129ceUL, 1}, /* HP-Microsoft sRGB v2 perceptual */ { 3144, 0x182ea552UL, 0}, /* HP-Microsoft sRGB v2 media-relative */ { 3144, 0xf29e526dUL, 1}, /* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */ { 524, 0xd4938c39UL, 0}, /* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */ { 3212, 0x034af5a1UL, 0}, /* Not recognized */ { 0, 0x00000000UL, 0}, }; /* Macros for left-bit-replication to ensure that pixels * and PixelInfos all have the same image->depth, and for use * in PNG8 quantization. */ /* LBR01: Replicate top bit */ #define LBR01PacketRed(pixelpacket) \ (pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketGreen(pixelpacket) \ (pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketBlue(pixelpacket) \ (pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketAlpha(pixelpacket) \ (pixelpacket).alpha=(ScaleQuantumToChar((pixelpacket).alpha) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketRGB(pixelpacket) \ { \ LBR01PacketRed((pixelpacket)); \ LBR01PacketGreen((pixelpacket)); \ LBR01PacketBlue((pixelpacket)); \ } #define LBR01PacketRGBO(pixelpacket) \ { \ LBR01PacketRGB((pixelpacket)); \ LBR01PacketAlpha((pixelpacket)); \ } #define LBR01PixelRed(pixel) \ (SetPixelRed(image, \ ScaleQuantumToChar(GetPixelRed(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelGreen(pixel) \ (SetPixelGreen(image, \ ScaleQuantumToChar(GetPixelGreen(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelBlue(pixel) \ (SetPixelBlue(image, \ ScaleQuantumToChar(GetPixelBlue(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelAlpha(pixel) \ (SetPixelAlpha(image, \ ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) < 0x10 ? \ 0 : QuantumRange,(pixel))); #define LBR01PixelRGB(pixel) \ { \ LBR01PixelRed((pixel)); \ LBR01PixelGreen((pixel)); \ LBR01PixelBlue((pixel)); \ } #define LBR01PixelRGBA(pixel) \ { \ LBR01PixelRGB((pixel)); \ LBR01PixelAlpha((pixel)); \ } /* LBR02: Replicate top 2 bits */ #define LBR02PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketAlpha(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).alpha) & 0xc0; \ (pixelpacket).alpha=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketRGB(pixelpacket) \ { \ LBR02PacketRed((pixelpacket)); \ LBR02PacketGreen((pixelpacket)); \ LBR02PacketBlue((pixelpacket)); \ } #define LBR02PacketRGBO(pixelpacket) \ { \ LBR02PacketRGB((pixelpacket)); \ LBR02PacketAlpha((pixelpacket)); \ } #define LBR02PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \ & 0xc0; \ SetPixelRed(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel)); \ } #define LBR02PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\ & 0xc0; \ SetPixelGreen(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel)); \ } #define LBR02PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue(image,(pixel))) & 0xc0; \ SetPixelBlue(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel)); \ } #define LBR02PixelAlpha(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) & 0xc0; \ SetPixelAlpha(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))), \ (pixel) ); \ } #define LBR02PixelRGB(pixel) \ { \ LBR02PixelRed((pixel)); \ LBR02PixelGreen((pixel)); \ LBR02PixelBlue((pixel)); \ } #define LBR02PixelRGBA(pixel) \ { \ LBR02PixelRGB((pixel)); \ LBR02PixelAlpha((pixel)); \ } /* LBR03: Replicate top 3 bits (only used with opaque pixels during PNG8 quantization) */ #define LBR03PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketRGB(pixelpacket) \ { \ LBR03PacketRed((pixelpacket)); \ LBR03PacketGreen((pixelpacket)); \ LBR03PacketBlue((pixelpacket)); \ } #define LBR03PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \ & 0xe0; \ SetPixelRed(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \ } #define LBR03Green(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\ & 0xe0; \ SetPixelGreen(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \ } #define LBR03Blue(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue(image,(pixel))) \ & 0xe0; \ SetPixelBlue(image, ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))), (pixel)); \ } #define LBR03RGB(pixel) \ { \ LBR03PixelRed((pixel)); \ LBR03Green((pixel)); \ LBR03Blue((pixel)); \ } /* LBR04: Replicate top 4 bits */ #define LBR04PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \ (pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \ (pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \ (pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketAlpha(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).alpha) & 0xf0; \ (pixelpacket).alpha=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketRGB(pixelpacket) \ { \ LBR04PacketRed((pixelpacket)); \ LBR04PacketGreen((pixelpacket)); \ LBR04PacketBlue((pixelpacket)); \ } #define LBR04PacketRGBO(pixelpacket) \ { \ LBR04PacketRGB((pixelpacket)); \ LBR04PacketAlpha((pixelpacket)); \ } #define LBR04PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed(image,(pixel))) \ & 0xf0; \ SetPixelRed(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen(image,(pixel)))\ & 0xf0; \ SetPixelGreen(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue(image,(pixel))) & 0xf0; \ SetPixelBlue(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelAlpha(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelAlpha(image,(pixel))) & 0xf0; \ SetPixelAlpha(image,\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))), (pixel)); \ } #define LBR04PixelRGB(pixel) \ { \ LBR04PixelRed((pixel)); \ LBR04PixelGreen((pixel)); \ LBR04PixelBlue((pixel)); \ } #define LBR04PixelRGBA(pixel) \ { \ LBR04PixelRGB((pixel)); \ LBR04PixelAlpha((pixel)); \ } /* Establish thread safety. setjmp/longjmp is claimed to be safe on these platforms: setjmp/longjmp is alleged to be unsafe on these platforms: */ #ifdef PNG_SETJMP_SUPPORTED # ifndef IMPNG_SETJMP_IS_THREAD_SAFE # define IMPNG_SETJMP_NOT_THREAD_SAFE # endif # ifdef IMPNG_SETJMP_NOT_THREAD_SAFE static SemaphoreInfo *ping_semaphore = (SemaphoreInfo *) NULL; # endif #endif /* This temporary until I set up malloc'ed object attributes array. Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but waste more memory. */ #define MNG_MAX_OBJECTS 256 /* If this not defined, spec is interpreted strictly. If it is defined, an attempt will be made to recover from some errors, including o global PLTE too short */ #undef MNG_LOOSE /* Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8, PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here. PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and will be enabled by default in libpng-1.2.0. */ #ifdef PNG_MNG_FEATURES_SUPPORTED # ifndef PNG_READ_EMPTY_PLTE_SUPPORTED # define PNG_READ_EMPTY_PLTE_SUPPORTED # endif # ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED # define PNG_WRITE_EMPTY_PLTE_SUPPORTED # endif #endif /* Maximum valid size_t in PNG/MNG chunks is (2^31)-1 This macro is only defined in libpng-1.0.3 and later. Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6 */ #ifndef PNG_UINT_31_MAX #define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL #endif /* Constant strings for known chunk types. If you need to add a chunk, add a string holding the name here. To make the code more portable, we use ASCII numbers like this, not characters. */ /* until registration of eXIf use exIf */ static const png_byte mng_exIf[5]={101, 120, 73, 102, (png_byte) '\0'}; /* after registration of eXIf */ static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'}; static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'}; static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'}; static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'}; static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'}; static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'}; static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'}; static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'}; static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'}; static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'}; static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'}; static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'}; static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'}; static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'}; static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'}; static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'}; static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'}; static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'}; static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'}; static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'}; static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'}; static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'}; static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'}; static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'}; static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'}; static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'}; static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'}; static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'}; static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'}; static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'}; #if defined(JNG_SUPPORTED) static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'}; static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'}; static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'}; static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'}; #endif #if 0 /* Other known chunks that are not yet supported by ImageMagick: */ static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'}; static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'}; static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'}; static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'}; static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'}; static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'}; static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'}; #endif typedef struct _MngBox { long left, right, top, bottom; } MngBox; typedef struct _MngPair { volatile long a, b; } MngPair; #ifdef MNG_OBJECT_BUFFERS typedef struct _MngBuffer { size_t height, width; Image *image; png_color plte[256]; int reference_count; unsigned char alpha_sample_depth, compression_method, color_type, concrete, filter_method, frozen, image_type, interlace_method, pixel_sample_depth, plte_length, sample_depth, viewable; } MngBuffer; #endif typedef struct _MngInfo { #ifdef MNG_OBJECT_BUFFERS MngBuffer *ob[MNG_MAX_OBJECTS]; #endif Image * image; RectangleInfo page; int adjoin, #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED bytes_in_read_buffer, found_empty_plte, #endif equal_backgrounds, equal_chrms, equal_gammas, #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) equal_palettes, #endif equal_physs, equal_srgbs, framing_mode, have_global_bkgd, have_global_chrm, have_global_gama, have_global_phys, have_global_sbit, have_global_srgb, have_saved_bkgd_index, have_write_global_chrm, have_write_global_gama, have_write_global_plte, have_write_global_srgb, need_fram, object_id, old_framing_mode, saved_bkgd_index; int new_number_colors; ssize_t image_found, loop_count[256], loop_iteration[256], scenes_found, x_off[MNG_MAX_OBJECTS], y_off[MNG_MAX_OBJECTS]; MngBox clip, frame, image_box, object_clip[MNG_MAX_OBJECTS]; unsigned char /* These flags could be combined into one byte */ exists[MNG_MAX_OBJECTS], frozen[MNG_MAX_OBJECTS], loop_active[256], invisible[MNG_MAX_OBJECTS], viewable[MNG_MAX_OBJECTS]; MagickOffsetType loop_jump[256]; png_colorp global_plte; png_color_8 global_sbit; png_byte #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED read_buffer[8], #endif global_trns[256]; float global_gamma; ChromaticityInfo global_chrm; RenderingIntent global_srgb_intent; unsigned int delay, global_plte_length, global_trns_length, global_x_pixels_per_unit, global_y_pixels_per_unit, mng_width, mng_height, ticks_per_second; MagickBooleanType need_blob; unsigned int IsPalette, global_phys_unit_type, basi_warning, clon_warning, dhdr_warning, jhdr_warning, magn_warning, past_warning, phyg_warning, phys_warning, sbit_warning, show_warning, mng_type, write_mng, write_png_colortype, write_png_depth, write_png_compression_level, write_png_compression_strategy, write_png_compression_filter, write_png8, write_png24, write_png32, write_png48, write_png64; #ifdef MNG_BASI_SUPPORTED size_t basi_width, basi_height; unsigned int basi_depth, basi_color_type, basi_compression_method, basi_filter_type, basi_interlace_method, basi_red, basi_green, basi_blue, basi_alpha, basi_viewable; #endif png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; PixelInfo mng_global_bkgd; /* Added at version 6.6.6-7 */ MagickBooleanType ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, ping_exclude_eXIf, ping_exclude_EXIF, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tRNS, ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, /* Added at version 6.8.5-7 */ ping_preserve_iCCP, /* Added at version 6.8.9-9 */ ping_exclude_tIME; } MngInfo; #endif /* VER */ /* Forward declarations. */ static MagickBooleanType WritePNGImage(const ImageInfo *,Image *,ExceptionInfo *); static MagickBooleanType WriteMNGImage(const ImageInfo *,Image *,ExceptionInfo *); #if defined(JNG_SUPPORTED) static MagickBooleanType WriteJNGImage(const ImageInfo *,Image *,ExceptionInfo *); #endif #if PNG_LIBPNG_VER > 10011 #if (MAGICKCORE_QUANTUM_DEPTH >= 16) static MagickBooleanType LosslessReduceDepthOK(Image *image,ExceptionInfo *exception) { /* Reduce bit depth if it can be reduced losslessly from 16+ to 8. * * This is true if the high byte and the next highest byte of * each sample of the image, the colormap, and the background color * are equal to each other. We check this by seeing if the samples * are unchanged when we scale them down to 8 and back up to Quantum. * * We don't use the method GetImageDepth() because it doesn't check * background and doesn't handle PseudoClass specially. */ #define QuantumToCharToQuantumEqQuantum(quantum) \ ((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum) MagickBooleanType ok_to_reduce=MagickFalse; if (image->depth >= 16) { const Quantum *p; ok_to_reduce= QuantumToCharToQuantumEqQuantum(image->background_color.red) && QuantumToCharToQuantumEqQuantum(image->background_color.green) && QuantumToCharToQuantumEqQuantum(image->background_color.blue) ? MagickTrue : MagickFalse; if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass) { int indx; for (indx=0; indx < (ssize_t) image->colors; indx++) { ok_to_reduce=( QuantumToCharToQuantumEqQuantum( image->colormap[indx].red) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].green) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].blue)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; } } if ((ok_to_reduce != MagickFalse) && (image->storage_class != PseudoClass)) { ssize_t y; register ssize_t x; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { ok_to_reduce = MagickFalse; break; } for (x=(ssize_t) image->columns-1; x >= 0; x--) { ok_to_reduce= QuantumToCharToQuantumEqQuantum(GetPixelRed(image,p)) && QuantumToCharToQuantumEqQuantum(GetPixelGreen(image,p)) && QuantumToCharToQuantumEqQuantum(GetPixelBlue(image,p)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; p+=GetPixelChannels(image); } if (x >= 0) break; } } if (ok_to_reduce != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " OK to reduce PNG bit depth to 8 without loss of info"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Not OK to reduce PNG bit depth to 8 without losing info"); } } return ok_to_reduce; } #endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */ static const char* PngColorTypeToString(const unsigned int color_type) { const char *result = "Unknown"; switch (color_type) { case PNG_COLOR_TYPE_GRAY: result = "Gray"; break; case PNG_COLOR_TYPE_GRAY_ALPHA: result = "Gray+Alpha"; break; case PNG_COLOR_TYPE_PALETTE: result = "Palette"; break; case PNG_COLOR_TYPE_RGB: result = "RGB"; break; case PNG_COLOR_TYPE_RGB_ALPHA: result = "RGB+Alpha"; break; } return result; } static int Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent) { switch (intent) { case PerceptualIntent: return 0; case RelativeIntent: return 1; case SaturationIntent: return 2; case AbsoluteIntent: return 3; default: return -1; } } static RenderingIntent Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return PerceptualIntent; case 1: return RelativeIntent; case 2: return SaturationIntent; case 3: return AbsoluteIntent; default: return UndefinedIntent; } } static const char * Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return "Perceptual Intent"; case 1: return "Relative Intent"; case 2: return "Saturation Intent"; case 3: return "Absolute Intent"; default: return "Undefined Intent"; } } static const char * Magick_ColorType_from_PNG_ColorType(const int ping_colortype) { switch (ping_colortype) { case 0: return "Grayscale"; case 2: return "Truecolor"; case 3: return "Indexed"; case 4: return "GrayAlpha"; case 6: return "RGBA"; default: return "UndefinedColorType"; } } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* MAGICKCORE_PNG_DELEGATE */ /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMNG() returns MagickTrue if the image format type, identified by the % magick string, is MNG. % % The format of the IsMNG method is: % % MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsMNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJNG() returns MagickTrue if the image format type, identified by the % magick string, is JNG. % % The format of the IsJNG method is: % % MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % % */ static MagickBooleanType IsJNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNG() returns MagickTrue if the image format type, identified by the % magick string, is PNG. % % The format of the IsPNG method is: % % MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_PNG_DELEGATE) #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if (PNG_LIBPNG_VER > 10011) static size_t WriteBlobMSBULong(Image *image,const size_t value) { unsigned char buffer[4]; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; return((size_t) WriteBlob(image,4,buffer)); } static void PNGLong(png_bytep p,png_uint_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGsLong(png_bytep p,png_int_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGShort(png_bytep p,png_uint_16 value) { *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGType(png_bytep p,const png_byte *type) { (void) CopyMagickMemory(p,type,4*sizeof(png_byte)); } static void LogPNGChunk(MagickBooleanType logging, const png_byte *type, size_t length) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing %c%c%c%c chunk, length: %.20g", type[0],type[1],type[2],type[3],(double) length); } #endif /* PNG_LIBPNG_VER > 10011 */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNGImage() reads a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image or set of images. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadPNGImage method is: % % Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % % To do, more or less in chronological order (as of version 5.5.2, % November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage): % % Get 16-bit cheap transparency working. % % (At this point, PNG decoding is supposed to be in full MNG-LC compliance) % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % (At this point, PNG encoding should be in full MNG compliance) % % Provide options for choice of background to use when the MNG BACK % chunk is not present or is not mandatory (i.e., leave transparent, % user specified, MNG BACK, PNG bKGD) % % Implement LOOP/ENDL [done, but could do discretionary loops more % efficiently by linking in the duplicate frames.]. % % Decode and act on the MHDR simplicity profile (offer option to reject % files or attempt to process them anyway when the profile isn't LC or VLC). % % Upgrade to full MNG without Delta-PNG. % % o BACK [done a while ago except for background image ID] % o MOVE [done 15 May 1999] % o CLIP [done 15 May 1999] % o DISC [done 19 May 1999] % o SAVE [partially done 19 May 1999 (marks objects frozen)] % o SEEK [partially done 19 May 1999 (discard function only)] % o SHOW % o PAST % o BASI % o MNG-level tEXt/iTXt/zTXt % o pHYg % o pHYs % o sBIT % o bKGD % o iTXt (wait for libpng implementation). % % Use the scene signature to discover when an identical scene is % being reused, and just point to the original image->exception instead % of storing another set of pixels. This not specific to MNG % but could be applied generally. % % Upgrade to full MNG with Delta-PNG. % % JNG tEXt/iTXt/zTXt % % We will not attempt to read files containing the CgBI chunk. % They are really Xcode files meant for display on the iPhone. % These are not valid PNG files and it is impossible to recover % the original PNG from files that have been converted to Xcode-PNG, % since irretrievable loss of color data has occurred due to the % use of premultiplied alpha. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* This the function that does the actual reading of data. It is the same as the one supplied in libpng, except that it receives the datastream from the ReadBlob() function instead of standard input. */ static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) ReadBlob(image,(size_t) length,data); if (check != length) { char msg[MagickPathExtent]; (void) FormatLocaleString(msg,MagickPathExtent, "Expected %.20g bytes; found %.20g bytes",(double) length, (double) check); png_warning(png_ptr,msg); png_error(png_ptr,"Read Exception"); } } } #if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \ !defined(PNG_MNG_FEATURES_SUPPORTED) /* We use mng_get_data() instead of png_get_data() if we have a libpng * older than libpng-1.0.3a, which was the first to allow the empty * PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was * ifdef'ed out. Earlier versions would crash if the bKGD chunk was * encountered after an empty PLTE, so we have to look ahead for bKGD * chunks and remove them from the datastream that is passed to libpng, * and store their contents for later use. */ static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { MngInfo *mng_info; Image *image; png_size_t check; register ssize_t i; i=0; mng_info=(MngInfo *) png_get_io_ptr(png_ptr); image=(Image *) mng_info->image; while (mng_info->bytes_in_read_buffer && length) { data[i]=mng_info->read_buffer[i]; mng_info->bytes_in_read_buffer--; length--; i++; } if (length != 0) { check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data); if (check != length) png_error(png_ptr,"Read Exception"); if (length == 4) { if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 0)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0) mng_info->found_empty_plte=MagickTrue; if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0) { mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; } } if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 1)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0) if (mng_info->found_empty_plte) { /* Skip the bKGD data byte and CRC. */ check=(png_size_t) ReadBlob(image,5,(char *) mng_info->read_buffer); check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->saved_bkgd_index=mng_info->read_buffer[0]; mng_info->have_saved_bkgd_index=MagickTrue; mng_info->bytes_in_read_buffer=0; } } } } } #endif static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) WriteBlob(image,(size_t) length,data); if (check != length) png_error(png_ptr,"WriteBlob Failed"); } } static void png_flush_data(png_structp png_ptr) { (void) png_ptr; } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED static int PalettesAreEqual(Image *a,Image *b) { ssize_t i; if ((a == (Image *) NULL) || (b == (Image *) NULL)) return((int) MagickFalse); if (a->storage_class != PseudoClass || b->storage_class != PseudoClass) return((int) MagickFalse); if (a->colors != b->colors) return((int) MagickFalse); for (i=0; i < (ssize_t) a->colors; i++) { if ((a->colormap[i].red != b->colormap[i].red) || (a->colormap[i].green != b->colormap[i].green) || (a->colormap[i].blue != b->colormap[i].blue)) return((int) MagickFalse); } return((int) MagickTrue); } #endif static void MngInfoDiscardObject(MngInfo *mng_info,int i) { if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) && mng_info->exists[i] && !mng_info->frozen[i]) { #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) { if (mng_info->ob[i]->reference_count > 0) mng_info->ob[i]->reference_count--; if (mng_info->ob[i]->reference_count == 0) { if (mng_info->ob[i]->image != (Image *) NULL) mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image); mng_info->ob[i]=DestroyString(mng_info->ob[i]); } } mng_info->ob[i]=(MngBuffer *) NULL; #endif mng_info->exists[i]=MagickFalse; mng_info->invisible[i]=MagickFalse; mng_info->viewable[i]=MagickFalse; mng_info->frozen[i]=MagickFalse; mng_info->x_off[i]=0; mng_info->y_off[i]=0; mng_info->object_clip[i].left=0; mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].top=0; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } } static MngInfo *MngInfoFreeStruct(MngInfo *mng_info) { register ssize_t i; if (mng_info == (MngInfo *) NULL) return((MngInfo *) NULL); for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); if (mng_info->global_plte != (png_colorp) NULL) mng_info->global_plte=(png_colorp) RelinquishMagickMemory(mng_info->global_plte); return((MngInfo *) RelinquishMagickMemory(mng_info)); } static MngBox mng_minimum_box(MngBox box1,MngBox box2) { MngBox box; box=box1; if (box.left < box2.left) box.left=box2.left; if (box.top < box2.top) box.top=box2.top; if (box.right > box2.right) box.right=box2.right; if (box.bottom > box2.bottom) box.bottom=box2.bottom; return box; } static MngBox mng_read_box(MngBox previous_box,char delta_type, unsigned char *p) { MngBox box; /* Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk. */ box.left=(ssize_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); box.right=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); box.top=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); box.bottom=(ssize_t) ((p[12] << 24) | (p[13] << 16) | (p[14] << 8) | p[15]); if (delta_type != 0) { box.left+=previous_box.left; box.right+=previous_box.right; box.top+=previous_box.top; box.bottom+=previous_box.bottom; } return(box); } static MngPair mng_read_pair(MngPair previous_pair,int delta_type, unsigned char *p) { MngPair pair; /* Read two ssize_ts from CLON, MOVE or PAST chunk */ pair.a=(long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); pair.b=(long) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (delta_type != 0) { pair.a+=previous_pair.a; pair.b+=previous_pair.b; } return(pair); } static long mng_get_long(unsigned char *p) { return((long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3])); } typedef struct _PNGErrorInfo { Image *image; ExceptionInfo *exception; } PNGErrorInfo; static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message) { ExceptionInfo *exception; Image *image; PNGErrorInfo *error_info; error_info=(PNGErrorInfo *) png_get_error_ptr(ping); image=error_info->image; exception=error_info->exception; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s error: %s", png_get_libpng_ver(NULL),message); (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message, "`%s'",image->filename); #if (PNG_LIBPNG_VER < 10500) /* A warning about deprecated use of jmpbuf here is unavoidable if you * are building with libpng-1.4.x and can be ignored. */ longjmp(ping->jmpbuf,1); #else png_longjmp(ping,1); #endif } static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message) { ExceptionInfo *exception; Image *image; PNGErrorInfo *error_info; if (LocaleCompare(message, "Missing PLTE before tRNS") == 0) png_error(ping, message); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); image=error_info->image; exception=error_info->exception; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s warning: %s", png_get_libpng_ver(NULL),message); (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'",image->filename); } #ifdef PNG_USER_MEM_SUPPORTED #if PNG_LIBPNG_VER >= 10400 static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size) #else static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size) #endif { (void) png_ptr; return((png_voidp) AcquireMagickMemory((size_t) size)); } /* Free a pointer. It is removed from the list at the same time. */ static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr) { (void) png_ptr; ptr=RelinquishMagickMemory(ptr); return((png_free_ptr) NULL); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static int Magick_png_read_raw_profile(png_struct *ping,Image *image, const ImageInfo *image_info, png_textp text,int ii,ExceptionInfo *exception) { register ssize_t i; register unsigned char *dp; register png_charp sp; png_uint_32 length, nibbles; StringInfo *profile; const unsigned char unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12, 13,14,15}; sp=text[ii].text+1; /* look for newline */ while (*sp != '\n') sp++; /* look for length */ while (*sp == '\0' || *sp == ' ' || *sp == '\n') sp++; length=(png_uint_32) StringToLong(sp); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu",(unsigned long) length); while (*sp != ' ' && *sp != '\n') sp++; /* allocate space */ if (length == 0) { png_warning(ping,"invalid profile length"); return(MagickFalse); } profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { png_warning(ping, "unable to copy profile"); return(MagickFalse); } /* copy profile, skipping white space and column 1 "=" signs */ dp=GetStringInfoDatum(profile); nibbles=length*2; for (i=0; i < (ssize_t) nibbles; i++) { while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f') { if (*sp == '\0') { png_warning(ping, "ran out of profile data"); profile=DestroyStringInfo(profile); return(MagickFalse); } sp++; } if (i%2 == 0) *dp=(unsigned char) (16*unhex[(int) *sp++]); else (*dp++)+=unhex[(int) *sp++]; } /* We have already read "Raw profile type. */ (void) SetImageProfile(image,&text[ii].key[17],profile,exception); profile=DestroyStringInfo(profile); if (image_info->verbose) (void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]); return MagickTrue; } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk) { Image *image; /* The unknown chunk structure contains the chunk data: png_byte name[5]; png_byte *data; png_size_t size; Note that libpng has already taken care of the CRC handling. Returns one of the following: return(-n); chunk had an error return(0); did not recognize return(n); success */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read_user_chunk: found %c%c%c%c chunk", chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]); if (chunk->name[0] == 101 && (chunk->name[1] == 88 || chunk->name[1] == 120 ) && chunk->name[2] == 73 && chunk-> name[3] == 102) { /* process eXIf or exIf chunk */ PNGErrorInfo *error_info; StringInfo *profile; unsigned char *p; png_byte *s; size_t i; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " recognized eXIf|exIf chunk"); image=(Image *) png_get_user_chunk_ptr(ping); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); profile=BlobToStringInfo((const void *) NULL,chunk->size+6); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(error_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); return(-1); } p=GetStringInfoDatum(profile); if (*p != 'E') { /* Initialize profile with "Exif\0\0" if it is not already present by accident */ *p++ ='E'; *p++ ='x'; *p++ ='i'; *p++ ='f'; *p++ ='\0'; *p++ ='\0'; } else { if (p[1] != 'x' || p[2] != 'i' || p[3] != 'f' || p[4] != '\0' || p[5] != '\0') { /* Chunk is malformed */ return(-1); } } /* copy chunk->data to profile */ s=chunk->data; for (i=0; i<chunk->size; i++) *p++ = *s++; error_info=(PNGErrorInfo *) png_get_error_ptr(ping); (void) SetImageProfile(image,"exif",profile, error_info->exception); return(1); } /* vpAg (deprecated, replaced by caNv) */ if (chunk->name[0] == 118 && chunk->name[1] == 112 && chunk->name[2] == 65 && chunk->name[3] == 103) { /* recognized vpAg */ if (chunk->size != 9) return(-1); /* Error return */ if (chunk->data[8] != 0) return(0); /* ImageMagick requires pixel units */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); return(1); } /* caNv */ if (chunk->name[0] == 99 && chunk->name[1] == 97 && chunk->name[2] == 78 && chunk->name[3] == 118) { /* recognized caNv */ if (chunk->size != 16) return(-1); /* Error return */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); image->page.x=(size_t) ((chunk->data[8] << 24) | (chunk->data[9] << 16) | (chunk->data[10] << 8) | chunk->data[11]); image->page.y=(size_t) ((chunk->data[12] << 24) | (chunk->data[13] << 16) | (chunk->data[14] << 8) | chunk->data[15]); return(1); } return(0); /* Did not recognize */ } #endif /* PNG_UNKNOWN_CHUNKS_SUPPORTED */ #if defined(PNG_tIME_SUPPORTED) static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info, ExceptionInfo *exception) { png_timep time; if (png_get_tIME(ping,info,&time)) { char timestamp[21]; FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ", time->year,time->month,time->day,time->hour,time->minute,time->second); SetImageProperty(image,"png:tIME",timestamp,exception); } } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the ReadOnePNGImage method is: % % Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { /* Read one PNG image */ /* To do: Read the tEXt/Creation Time chunk into the date:create property */ Image *image; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; int intent, /* "PNG Rendering intent", which is ICC intent + 1 */ num_raw_profiles, num_text, num_text_total, num_passes, number_colors, pass, ping_bit_depth, ping_color_type, ping_file_depth, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans, unit_type; double file_gamma; MagickBooleanType logging, ping_found_cHRM, ping_found_gAMA, ping_found_iCCP, ping_found_sRGB, ping_found_sRGB_cHRM, ping_preserve_iCCP, status; MemoryInfo *volatile pixel_info; PixelInfo transparent_color; PNGErrorInfo error_info; png_bytep ping_trans_alpha; png_color_16p ping_background, ping_trans_color; png_info *end_info, *ping_info; png_struct *ping; png_textp text; png_uint_32 ping_height, ping_width, x_resolution, y_resolution; QuantumInfo *quantum_info; ssize_t ping_rowbytes, y; register unsigned char *p; register ssize_t i, x; register Quantum *q; size_t length, row_offset; ssize_t j; unsigned char *ping_pixels; #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED png_byte unused_chunks[]= { 104, 73, 83, 84, (png_byte) '\0', /* hIST */ 105, 84, 88, 116, (png_byte) '\0', /* iTXt */ 112, 67, 65, 76, (png_byte) '\0', /* pCAL */ 115, 67, 65, 76, (png_byte) '\0', /* sCAL */ 115, 80, 76, 84, (png_byte) '\0', /* sPLT */ #if !defined(PNG_tIME_SUPPORTED) 116, 73, 77, 69, (png_byte) '\0', /* tIME */ #endif #ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */ /* ignore the APNG chunks */ 97, 99, 84, 76, (png_byte) '\0', /* acTL */ 102, 99, 84, 76, (png_byte) '\0', /* fcTL */ 102, 100, 65, 84, (png_byte) '\0', /* fdAT */ #endif }; #endif /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,32); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,32); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOnePNGImage()\n" " IM version = %s\n" " Libpng version = %s", im_vers, libpng_vers); if (logging != MagickFalse) { if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif #if (PNG_LIBPNG_VER >= 10400) # ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */ if (image_info->verbose) { printf("Your PNG library (libpng-%s) is an old beta version.\n", PNG_LIBPNG_VER_STRING); printf("Please update it.\n"); } # endif #endif quantum_info = (QuantumInfo *) NULL; image=mng_info->image; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before reading:\n" " image->alpha_trait=%d" " image->rendering_intent=%d\n" " image->colorspace=%d\n" " image->gamma=%f", (int) image->alpha_trait, (int) image->rendering_intent, (int) image->colorspace, image->gamma); } intent= Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent); /* Set to an out-of-range color unless tRNS chunk is present */ transparent_color.red=65537; transparent_color.green=65537; transparent_color.blue=65537; transparent_color.alpha=65537; number_colors=0; num_text = 0; num_text_total = 0; num_raw_profiles = 0; ping_found_cHRM = MagickFalse; ping_found_gAMA = MagickFalse; ping_found_iCCP = MagickFalse; ping_found_sRGB = MagickFalse; ping_found_sRGB_cHRM = MagickFalse; ping_preserve_iCCP = MagickFalse; /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler, NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } end_info=png_create_info_struct(ping); if (end_info == (png_info *) NULL) { png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG image is corrupt. */ png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() with error."); return(GetFirstImageInList(image)); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for reading. */ mng_info->image_found++; png_set_sig_bytes(ping,8); if (LocaleCompare(image_info->magick,"MNG") == 0) { #if defined(PNG_MNG_FEATURES_SUPPORTED) (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); png_set_read_fn(ping,image,png_get_data); #else #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) png_permit_empty_plte(ping,MagickTrue); png_set_read_fn(ping,image,png_get_data); #else mng_info->image=image; mng_info->bytes_in_read_buffer=0; mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; png_set_read_fn(ping,mng_info,mng_get_data); #endif #endif } else png_set_read_fn(ping,image,png_get_data); { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",value) == MagickFalse) { value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) ping_preserve_iCCP=MagickTrue; #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) /* Don't let libpng check for ICC/sRGB profile because we're going * to do that anyway. This feature was added at libpng-1.6.12. * If logging, go ahead and check and issue a warning as appropriate. */ if (logging == MagickFalse) png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) else { png_set_keep_unknown_chunks(ping, 1, (png_bytep) mng_iCCP, 1); } #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* Ignore unused chunks and all unknown chunks except for eXIf, caNv, and vpAg */ # if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */ png_set_keep_unknown_chunks(ping, 2, NULL, 0); # else png_set_keep_unknown_chunks(ping, 1, NULL, 0); # endif png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_eXIf, 1); png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_caNv, 1); png_set_keep_unknown_chunks(ping, 2, (png_bytep) mng_vpAg, 1); png_set_keep_unknown_chunks(ping, 1, unused_chunks, (int)sizeof(unused_chunks)/5); /* Callback for other unknown chunks */ png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED # if (PNG_LIBPNG_VER >= 10400) /* Limit the size of the chunk storage cache used for sPLT, text, * and unknown chunks. */ png_set_chunk_cache_max(ping, 32767); # endif #endif #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature */ png_set_check_for_invalid_index (ping, 0); #endif #if (PNG_LIBPNG_VER < 10400) # if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \ (PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__) /* Disable thread-unsafe features of pnggccrd */ if (png_access_version_number() >= 10200) { png_uint_32 mmx_disable_mask=0; png_uint_32 asm_flags; mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \ | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \ | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \ | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ); asm_flags=png_get_asm_flags(ping); png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask); } # endif #endif png_read_info(ping,ping_info); png_get_IHDR(ping,ping_info,&ping_width,&ping_height, &ping_bit_depth,&ping_color_type, &ping_interlace_method,&ping_compression_method, &ping_filter_method); ping_file_depth = ping_bit_depth; /* Swap bytes if requested */ if (ping_file_depth == 16) { const char *value; value=GetImageOption(image_info,"png:swap-bytes"); if (value == NULL) value=GetImageArtifact(image,"png:swap-bytes"); if (value != NULL) png_set_swap(ping); } /* Save bit-depth and color-type in case we later want to write a PNG00 */ { char msg[MagickPathExtent]; (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) ping_color_type); (void) SetImageProperty(image,"png:IHDR.color-type-orig",msg,exception); (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) ping_bit_depth); (void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg,exception); } (void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans, &ping_trans_color); (void) png_get_bKGD(ping, ping_info, &ping_background); if (ping_bit_depth < 8) { png_set_packing(ping); ping_bit_depth = 8; } image->depth=ping_bit_depth; image->depth=GetImageQuantumDepth(image,MagickFalse); image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { image->rendering_intent=UndefinedIntent; intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent); (void) ResetMagickMemory(&image->chromaticity,0, sizeof(image->chromaticity)); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG width: %.20g, height: %.20g\n" " PNG color_type: %d, bit_depth: %d\n" " PNG compression_method: %d\n" " PNG interlace_method: %d, filter_method: %d", (double) ping_width, (double) ping_height, ping_color_type, ping_bit_depth, ping_compression_method, ping_interlace_method,ping_filter_method); } if (png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_gAMA)) { ping_found_gAMA=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG gAMA chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { ping_found_cHRM=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG cHRM chunk."); } if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { ping_found_sRGB=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG sRGB chunk."); } #ifdef PNG_READ_iCCP_SUPPORTED if (ping_found_iCCP !=MagickTrue && ping_found_sRGB != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_iCCP)) { int compression; #if (PNG_LIBPNG_VER < 10500) png_charp info; #else png_bytep info; #endif png_charp name; png_uint_32 profile_length; (void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info, &profile_length); if (profile_length != 0) { StringInfo *profile; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG iCCP chunk."); profile=BlobToStringInfo(info,profile_length); if (profile == (StringInfo *) NULL) { png_warning(ping, "ICC profile is NULL"); profile=DestroyStringInfo(profile); } else { if (ping_preserve_iCCP == MagickFalse) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } break; } } } if (sRGB_info[icheck].len == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); (void) SetImageProfile(image,"icc",profile,exception); } } else /* Preserve-iCCP */ { (void) SetImageProfile(image,"icc",profile,exception); } profile=DestroyStringInfo(profile); } } } #endif #if defined(PNG_READ_sRGB_SUPPORTED) { if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { if (png_get_sRGB(ping,ping_info,&intent)) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (intent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG sRGB chunk: rendering_intent: %d",intent); } } else if (mng_info->have_global_srgb) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (mng_info->global_srgb_intent); } } #endif { if (!png_get_gAMA(ping,ping_info,&file_gamma)) if (mng_info->have_global_gama) png_set_gAMA(ping,ping_info,mng_info->global_gamma); if (png_get_gAMA(ping,ping_info,&file_gamma)) { image->gamma=(float) file_gamma; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG gAMA chunk: gamma: %f",file_gamma); } } if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { if (mng_info->have_global_chrm != MagickFalse) { (void) png_set_cHRM(ping,ping_info, mng_info->global_chrm.white_point.x, mng_info->global_chrm.white_point.y, mng_info->global_chrm.red_primary.x, mng_info->global_chrm.red_primary.y, mng_info->global_chrm.green_primary.x, mng_info->global_chrm.green_primary.y, mng_info->global_chrm.blue_primary.x, mng_info->global_chrm.blue_primary.y); } } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { (void) png_get_cHRM(ping,ping_info, &image->chromaticity.white_point.x, &image->chromaticity.white_point.y, &image->chromaticity.red_primary.x, &image->chromaticity.red_primary.y, &image->chromaticity.green_primary.x, &image->chromaticity.green_primary.y, &image->chromaticity.blue_primary.x, &image->chromaticity.blue_primary.y); ping_found_cHRM=MagickTrue; if (image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f) ping_found_sRGB_cHRM=MagickTrue; } if (image->rendering_intent != UndefinedIntent) { if (ping_found_sRGB != MagickTrue && (ping_found_gAMA != MagickTrue || (image->gamma > .45 && image->gamma < .46)) && (ping_found_cHRM != MagickTrue || ping_found_sRGB_cHRM != MagickFalse) && ping_found_iCCP != MagickTrue) { png_set_sRGB(ping,ping_info, Magick_RenderingIntent_to_PNG_RenderingIntent (image->rendering_intent)); file_gamma=1.000f/2.200f; ping_found_sRGB=MagickTrue; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting sRGB as if in input"); } } #if defined(PNG_oFFs_SUPPORTED) if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info); image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info); if (logging != MagickFalse) if (image->page.x || image->page.y) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double) image->page.x,(double) image->page.y); } #endif #if defined(PNG_pHYs_SUPPORTED) if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { if (mng_info->have_global_phys) { png_set_pHYs(ping,ping_info, mng_info->global_x_pixels_per_unit, mng_info->global_y_pixels_per_unit, mng_info->global_phys_unit_type); } } x_resolution=0; y_resolution=0; unit_type=0; if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { /* Set image resolution. */ (void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution, &unit_type); image->resolution.x=(double) x_resolution; image->resolution.y=(double) y_resolution; if (unit_type == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->resolution.x=(double) x_resolution/100.0; image->resolution.y=(double) y_resolution/100.0; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) x_resolution,(double) y_resolution,unit_type); } #endif if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); if ((number_colors == 0) && ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)) { if (mng_info->global_plte_length) { png_set_PLTE(ping,ping_info,mng_info->global_plte, (int) mng_info->global_plte_length); if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { if (mng_info->global_trns_length) { png_warning(ping, "global tRNS has more entries than global PLTE"); } else { png_set_tRNS(ping,ping_info,mng_info->global_trns, (int) mng_info->global_trns_length,NULL); } } #ifdef PNG_READ_bKGD_SUPPORTED if ( #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED mng_info->have_saved_bkgd_index || #endif png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { png_color_16 background; #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED if (mng_info->have_saved_bkgd_index) background.index=mng_info->saved_bkgd_index; #endif if (png_get_valid(ping, ping_info, PNG_INFO_bKGD)) background.index=ping_background->index; background.red=(png_uint_16) mng_info->global_plte[background.index].red; background.green=(png_uint_16) mng_info->global_plte[background.index].green; background.blue=(png_uint_16) mng_info->global_plte[background.index].blue; background.gray=(png_uint_16) mng_info->global_plte[background.index].green; png_set_bKGD(ping,ping_info,&background); } #endif } else png_error(ping,"No global PLTE in file"); } } #ifdef PNG_READ_bKGD_SUPPORTED if (mng_info->have_global_bkgd && (!png_get_valid(ping,ping_info,PNG_INFO_bKGD))) image->background_color=mng_info->mng_global_bkgd; if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { unsigned int bkgd_scale; /* Set image background color. * Scale background components to 16-bit, then scale * to quantum depth */ bkgd_scale = 1; if (ping_file_depth == 1) bkgd_scale = 255; else if (ping_file_depth == 2) bkgd_scale = 85; else if (ping_file_depth == 4) bkgd_scale = 17; if (ping_file_depth <= 8) bkgd_scale *= 257; ping_background->red *= bkgd_scale; ping_background->green *= bkgd_scale; ping_background->blue *= bkgd_scale; if (logging != MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d)\n" " bkgd_scale=%d. ping_background=(%d,%d,%d)", ping_background->red,ping_background->green, ping_background->blue, bkgd_scale,ping_background->red, ping_background->green,ping_background->blue); } image->background_color.red= ScaleShortToQuantum(ping_background->red); image->background_color.green= ScaleShortToQuantum(ping_background->green); image->background_color.blue= ScaleShortToQuantum(ping_background->blue); image->background_color.alpha=OpaqueAlpha; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->background_color=(%.20g,%.20g,%.20g).", (double) image->background_color.red, (double) image->background_color.green, (double) image->background_color.blue); } #endif /* PNG_READ_bKGD_SUPPORTED */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { /* Image has a tRNS chunk. */ int max_sample; size_t one=1; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG tRNS chunk."); max_sample = (int) ((one << ping_file_depth) - 1); if ((ping_color_type == PNG_COLOR_TYPE_GRAY && (int)ping_trans_color->gray > max_sample) || (ping_color_type == PNG_COLOR_TYPE_RGB && ((int)ping_trans_color->red > max_sample || (int)ping_trans_color->green > max_sample || (int)ping_trans_color->blue > max_sample))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Ignoring PNG tRNS chunk with out-of-range sample."); png_free_data(ping, ping_info, PNG_FREE_TRNS, 0); png_set_invalid(ping,ping_info,PNG_INFO_tRNS); image->alpha_trait=UndefinedPixelTrait; } else { int scale_to_short; scale_to_short = 65535L/((1UL << ping_file_depth)-1); /* Scale transparent_color to short */ transparent_color.red= scale_to_short*ping_trans_color->red; transparent_color.green= scale_to_short*ping_trans_color->green; transparent_color.blue= scale_to_short*ping_trans_color->blue; transparent_color.alpha= scale_to_short*ping_trans_color->gray; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Raw tRNS graylevel = %d, scaled graylevel = %d.", (int) ping_trans_color->gray,(int) transparent_color.alpha); } transparent_color.red=transparent_color.alpha; transparent_color.green=transparent_color.alpha; transparent_color.blue=transparent_color.alpha; } } } #if defined(PNG_READ_sBIT_SUPPORTED) if (mng_info->have_global_sbit) { if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT)) png_set_sBIT(ping,ping_info,&mng_info->global_sbit); } #endif num_passes=png_set_interlace_handling(ping); png_read_update_info(ping,ping_info); ping_rowbytes=png_get_rowbytes(ping,ping_info); /* Initialize image structure. */ mng_info->image_box.left=0; mng_info->image_box.right=(ssize_t) ping_width; mng_info->image_box.top=0; mng_info->image_box.bottom=(ssize_t) ping_height; if (mng_info->mng_type == 0) { mng_info->mng_width=ping_width; mng_info->mng_height=ping_height; mng_info->frame=mng_info->image_box; mng_info->clip=mng_info->image_box; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } image->compression=ZipCompression; image->columns=ping_width; image->rows=ping_height; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { double image_gamma = image->gamma; (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%f",(float) image_gamma); if (image_gamma > 0.75) { /* Set image->rendering_intent to Undefined, * image->colorspace to GRAY, and reset image->chromaticity. */ image->intensity = Rec709LuminancePixelIntensityMethod; SetImageColorspace(image,GRAYColorspace,exception); } else { RenderingIntent save_rendering_intent = image->rendering_intent; ChromaticityInfo save_chromaticity = image->chromaticity; SetImageColorspace(image,GRAYColorspace,exception); image->rendering_intent = save_rendering_intent; image->chromaticity = save_chromaticity; } image->gamma = image_gamma; } (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace=%d",(int) image->colorspace); if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || ((int) ping_bit_depth < 16 && (int) ping_color_type == PNG_COLOR_TYPE_GRAY)) { size_t one; image->storage_class=PseudoClass; one=1; image->colors=one << ping_file_depth; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->colors > 256) image->colors=256; #else if (image->colors > 65536L) image->colors=65536L; #endif if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); image->colors=(size_t) number_colors; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG PLTE chunk: number_colors: %d.",number_colors); } } if (image->storage_class == PseudoClass) { /* Initialize image colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) png_error(ping,"Memory allocation failed"); if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); for (i=0; i < (ssize_t) number_colors; i++) { image->colormap[i].red=ScaleCharToQuantum(palette[i].red); image->colormap[i].green=ScaleCharToQuantum(palette[i].green); image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue); } for ( ; i < (ssize_t) image->colors; i++) { image->colormap[i].red=0; image->colormap[i].green=0; image->colormap[i].blue=0; } } else { Quantum scale; scale = (Quantum) (65535.0/((1UL << ping_file_depth)-1.0)); #if (MAGICKCORE_QUANTUM_DEPTH > 16) scale = ScaleShortToQuantum(scale); #endif for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(Quantum) (i*scale); image->colormap[i].green=(Quantum) (i*scale); image->colormap[i].blue=(Quantum) (i*scale); } } } /* Set some properties for reporting by "identify" */ { char msg[MagickPathExtent]; /* encode ping_width, ping_height, ping_file_depth, ping_color_type, ping_interlace_method in value */ (void) FormatLocaleString(msg,MagickPathExtent, "%d, %d",(int) ping_width, (int) ping_height); (void) SetImageProperty(image,"png:IHDR.width,height",msg,exception); (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) ping_file_depth); (void) SetImageProperty(image,"png:IHDR.bit_depth",msg,exception); (void) FormatLocaleString(msg,MagickPathExtent,"%d (%s)", (int) ping_color_type, Magick_ColorType_from_PNG_ColorType((int)ping_color_type)); (void) SetImageProperty(image,"png:IHDR.color_type",msg,exception); if (ping_interlace_method == 0) { (void) FormatLocaleString(msg,MagickPathExtent,"%d (Not interlaced)", (int) ping_interlace_method); } else if (ping_interlace_method == 1) { (void) FormatLocaleString(msg,MagickPathExtent,"%d (Adam7 method)", (int) ping_interlace_method); } else { (void) FormatLocaleString(msg,MagickPathExtent,"%d (Unknown method)", (int) ping_interlace_method); } (void) SetImageProperty(image,"png:IHDR.interlace_method", msg,exception); if (number_colors != 0) { (void) FormatLocaleString(msg,MagickPathExtent,"%d", (int) number_colors); (void) SetImageProperty(image,"png:PLTE.number_colors",msg, exception); } } #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,ping_info,exception); #endif /* Read image scanlines. */ if (image->delay != 0) mng_info->scenes_found++; if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || ( (image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)))) { /* This happens later in non-ping decodes */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) image->storage_class=DirectClass; image->alpha_trait= (((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? BlendPixelTrait : UndefinedPixelTrait; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping PNG image data for scene %.20g",(double) mng_info->scenes_found-1); png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()."); return(image); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG IDAT chunk(s)"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (num_passes > 1) pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes* sizeof(*ping_pixels)); else pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Memory allocation failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting PNG pixels to pixel packets"); /* Convert PNG pixels to pixel packets. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Failed to allocate quantum_info"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); { MagickBooleanType found_transparent_pixel; found_transparent_pixel=MagickFalse; if (image->storage_class == DirectClass) { for (pass=0; pass < num_passes; pass++) { /* Convert image to DirectClass pixel packets. */ image->alpha_trait= (((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? BlendPixelTrait : UndefinedPixelTrait; for (y=0; y < (ssize_t) image->rows; y++) { if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayAlphaQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBAQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, IndexQuantum,ping_pixels+row_offset,exception); else /* ping_color_type == PNG_COLOR_TYPE_RGB */ (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBQuantum,ping_pixels+row_offset,exception); if (found_transparent_pixel == MagickFalse) { /* Is there a transparent pixel in the row? */ if (y== 0 && logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Looking for cheap transparent pixel"); for (x=(ssize_t) image->columns-1; x >= 0; x--) { if ((ping_color_type == PNG_COLOR_TYPE_RGBA || ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) && (GetPixelAlpha(image,q) != OpaqueAlpha)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } if ((ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_GRAY) && (ScaleQuantumToShort(GetPixelRed(image,q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(image,q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(image,q)) == transparent_color.blue)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } q+=GetPixelChannels(image); } } if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag, (MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } } } else /* image->storage_class != DirectClass */ for (pass=0; pass < num_passes; pass++) { Quantum *quantum_scanline; register Quantum *r; /* Convert grayscale image to PseudoClass pixel packets. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting grayscale pixels to pixel packets"); image->alpha_trait=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ? BlendPixelTrait : UndefinedPixelTrait; quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns, (image->alpha_trait == BlendPixelTrait? 2 : 1)* sizeof(*quantum_scanline)); if (quantum_scanline == (Quantum *) NULL) png_error(ping,"Memory allocation failed"); for (y=0; y < (ssize_t) image->rows; y++) { Quantum alpha; if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=ping_pixels+row_offset; r=quantum_scanline; switch (ping_bit_depth) { case 8: { if (ping_color_type == 4) for (x=(ssize_t) image->columns-1; x >= 0; x--) { *r++=*p++; alpha=ScaleCharToQuantum((unsigned char)*p++); SetPixelAlpha(image,alpha,q); if (alpha != OpaqueAlpha) found_transparent_pixel = MagickTrue; q+=GetPixelChannels(image); } else for (x=(ssize_t) image->columns-1; x >= 0; x--) *r++=*p++; break; } case 16: { for (x=(ssize_t) image->columns-1; x >= 0; x--) { #if (MAGICKCORE_QUANTUM_DEPTH >= 16) unsigned short quantum; if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); *r=ScaleShortToQuantum(quantum); r++; if (ping_color_type == 4) { if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); alpha=ScaleShortToQuantum(quantum); SetPixelAlpha(image,alpha,q); if (alpha != OpaqueAlpha) found_transparent_pixel = MagickTrue; q+=GetPixelChannels(image); } #else /* MAGICKCORE_QUANTUM_DEPTH == 8 */ *r++=(*p++); p++; /* strip low byte */ if (ping_color_type == 4) { SetPixelAlpha(image,*p++,q); if (GetPixelAlpha(image,q) != OpaqueAlpha) found_transparent_pixel = MagickTrue; p++; q+=GetPixelChannels(image); } #endif } break; } default: break; } /* Transfer image scanline. */ r=quantum_scanline; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*r++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline); } image->alpha_trait=found_transparent_pixel ? BlendPixelTrait : UndefinedPixelTrait; if (logging != MagickFalse) { if (found_transparent_pixel != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found transparent pixel"); else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No transparent pixel was found"); ping_color_type&=0x03; } } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->storage_class == PseudoClass) { PixelTrait alpha_trait; alpha_trait=image->alpha_trait; image->alpha_trait=UndefinedPixelTrait; (void) SyncImage(image,exception); image->alpha_trait=alpha_trait; } png_read_end(ping,end_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=%d\n",(int) image->storage_class); } if (image_info->number_scenes != 0 && mng_info->scenes_found-1 < (ssize_t) image_info->first_scene && image->delay != 0) { png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); image->colors=2; (void) SetImageBackgroundColor(image,exception); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() early."); return(image); } if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { ClassType storage_class; /* Image has a transparent background. */ storage_class=image->storage_class; image->alpha_trait=BlendPixelTrait; /* Balfour fix from imagemagick discourse server, 5 Feb 2010 */ if (storage_class == PseudoClass) { if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { for (x=0; x < ping_num_trans; x++) { image->colormap[x].alpha_trait=BlendPixelTrait; image->colormap[x].alpha = ScaleCharToQuantum((unsigned char)ping_trans_alpha[x]); } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY) { for (x=0; x < (int) image->colors; x++) { if (ScaleQuantumToShort(image->colormap[x].red) == transparent_color.alpha) { image->colormap[x].alpha_trait=BlendPixelTrait; image->colormap[x].alpha = (Quantum) TransparentAlpha; } } } (void) SyncImage(image,exception); } #if 1 /* Should have already been done above, but glennrp problem P10 * needs this. */ else { for (y=0; y < (ssize_t) image->rows; y++) { image->storage_class=storage_class; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; /* Caution: on a Q8 build, this does not distinguish between * 16-bit colors that differ only in the low byte */ for (x=(ssize_t) image->columns-1; x >= 0; x--) { if (ScaleQuantumToShort(GetPixelRed(image,q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(image,q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(image,q)) == transparent_color.blue) { SetPixelAlpha(image,TransparentAlpha,q); } #if 0 /* I have not found a case where this is needed. */ else { SetPixelAlpha(image,q)=(Quantum) OpaqueAlpha; } #endif q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif image->storage_class=DirectClass; } for (j = 0; j < 2; j++) { if (j == 0) status = png_get_text(ping,ping_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; else status = png_get_text(ping,end_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) for (i=0; i < (ssize_t) num_text; i++) { /* Check for a profile */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG text chunk"); if (strlen(text[i].key) > 16 && memcmp(text[i].key, "Raw profile type ",17) == 0) { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember(text[i].key+17,value) == MagickFalse) { (void) Magick_png_read_raw_profile(ping,image,image_info,text, (int) i,exception); num_raw_profiles++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Read raw profile %s",text[i].key+17); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping raw profile %s",text[i].key+17); } } else { char *value; length=text[i].text_length; value=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*value)); if (value == (char *) NULL) { png_error(ping,"Memory allocation failed"); break; } *value='\0'; (void) ConcatenateMagickString(value,text[i].text,length+2); /* Don't save "density" or "units" property if we have a pHYs * chunk */ if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) || (LocaleCompare(text[i].key,"density") != 0 && LocaleCompare(text[i].key,"units") != 0)) (void) SetImageProperty(image,text[i].key,value,exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu\n" " Keyword: %s", (unsigned long) length, text[i].key); } value=DestroyString(value); } } num_text_total += num_text; } #ifdef MNG_OBJECT_BUFFERS /* Store the object if necessary. */ if (object_id && !mng_info->frozen[object_id]) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) { /* create a new object buffer. */ mng_info->ob[object_id]=(MngBuffer *) AcquireMagickMemory(sizeof(MngBuffer)); if (mng_info->ob[object_id] != (MngBuffer *) NULL) { mng_info->ob[object_id]->image=(Image *) NULL; mng_info->ob[object_id]->reference_count=1; } } if ((mng_info->ob[object_id] == (MngBuffer *) NULL) || mng_info->ob[object_id]->frozen) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) png_error(ping,"Memory allocation failed"); if (mng_info->ob[object_id]->frozen) png_error(ping,"Cannot overwrite frozen MNG object buffer"); } else { if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image=DestroyImage (mng_info->ob[object_id]->image); mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue, exception); if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image->file=(FILE *) NULL; else png_error(ping, "Cloning image for object buffer failed"); if (ping_width > 250000L || ping_height > 250000L) png_error(ping,"PNG Image dimensions are too large."); mng_info->ob[object_id]->width=ping_width; mng_info->ob[object_id]->height=ping_height; mng_info->ob[object_id]->color_type=ping_color_type; mng_info->ob[object_id]->sample_depth=ping_bit_depth; mng_info->ob[object_id]->interlace_method=ping_interlace_method; mng_info->ob[object_id]->compression_method= ping_compression_method; mng_info->ob[object_id]->filter_method=ping_filter_method; if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp plte; /* Copy the PLTE to the object buffer. */ png_get_PLTE(ping,ping_info,&plte,&number_colors); mng_info->ob[object_id]->plte_length=number_colors; for (i=0; i < number_colors; i++) { mng_info->ob[object_id]->plte[i]=plte[i]; } } else mng_info->ob[object_id]->plte_length=0; } } #endif /* Set image->alpha_trait to MagickTrue if the input colortype supports * alpha or if a valid tRNS chunk is present, no matter whether there * is actual transparency present. */ image->alpha_trait=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? BlendPixelTrait : UndefinedPixelTrait; #if 0 /* I'm not sure what's wrong here but it does not work. */ if (image->alpha_trait != UndefinedPixelTrait) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) SetImageType(image,GrayscaleAlphaType,exception); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteAlphaType,exception); else (void) SetImageType(image,TrueColorAlphaType,exception); } else { if (ping_color_type == PNG_COLOR_TYPE_GRAY) (void) SetImageType(image,GrayscaleType,exception); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteType,exception); else (void) SetImageType(image,TrueColorType,exception); } #endif /* Set more properties for identify to retrieve */ { char msg[MagickPathExtent]; if (num_text_total != 0) { /* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */ (void) FormatLocaleString(msg,MagickPathExtent, "%d tEXt/zTXt/iTXt chunks were found", num_text_total); (void) SetImageProperty(image,"png:text",msg, exception); } if (num_raw_profiles != 0) { (void) FormatLocaleString(msg,MagickPathExtent, "%d were found", num_raw_profiles); (void) SetImageProperty(image,"png:text-encoded profiles",msg, exception); } /* cHRM chunk: */ if (ping_found_cHRM != MagickFalse) { (void) FormatLocaleString(msg,MagickPathExtent,"%s", "chunk was found (see Chromaticity, above)"); (void) SetImageProperty(image,"png:cHRM",msg, exception); } /* bKGD chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { (void) FormatLocaleString(msg,MagickPathExtent,"%s", "chunk was found (see Background color, above)"); (void) SetImageProperty(image,"png:bKGD",msg, exception); } (void) FormatLocaleString(msg,MagickPathExtent,"%s", "chunk was found"); #if defined(PNG_iCCP_SUPPORTED) /* iCCP chunk: */ if (ping_found_iCCP != MagickFalse) (void) SetImageProperty(image,"png:iCCP",msg, exception); #endif if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) (void) SetImageProperty(image,"png:tRNS",msg, exception); #if defined(PNG_sRGB_SUPPORTED) /* sRGB chunk: */ if (ping_found_sRGB != MagickFalse) { (void) FormatLocaleString(msg,MagickPathExtent, "intent=%d (%s)", (int) intent, Magick_RenderingIntentString_from_PNG_RenderingIntent(intent)); (void) SetImageProperty(image,"png:sRGB",msg, exception); } #endif /* gAMA chunk: */ if (ping_found_gAMA != MagickFalse) { (void) FormatLocaleString(msg,MagickPathExtent, "gamma=%.8g (See Gamma, above)", file_gamma); (void) SetImageProperty(image,"png:gAMA",msg, exception); } #if defined(PNG_pHYs_SUPPORTED) /* pHYs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { (void) FormatLocaleString(msg,MagickPathExtent, "x_res=%.10g, y_res=%.10g, units=%d", (double) x_resolution,(double) y_resolution, unit_type); (void) SetImageProperty(image,"png:pHYs",msg, exception); } #endif #if defined(PNG_oFFs_SUPPORTED) /* oFFs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { (void) FormatLocaleString(msg,MagickPathExtent, "x_off=%.20g, y_off=%.20g", (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:oFFs",msg, exception); } #endif #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,end_info,exception); #endif /* caNv chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || (image->page.x != 0 || image->page.y != 0)) { (void) FormatLocaleString(msg,MagickPathExtent, "width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:caNv",msg, exception); } /* vpAg chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { (void) FormatLocaleString(msg,MagickPathExtent, "width=%.20g, height=%.20g", (double) image->page.width,(double) image->page.height); (void) SetImageProperty(image,"png:vpAg",msg, exception); } } /* Relinquish resources. */ png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block, revert to * Throwing an Exception when an error occurs. */ return(image); /* end of reading one PNG image */ } static Image *ReadPNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MagickPathExtent]; ssize_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()"); image=AcquireImage(image_info,exception); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) ThrowReaderException(FileOpenError,"UnableToOpenFile"); /* Verify PNG signature. */ count=ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOnePNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if ((image->columns == 0) || (image->rows == 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if ((IssRGBColorspace(image->colorspace) != MagickFalse) && ((image->gamma < .45) || (image->gamma > .46)) && !(image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f)) { SetImageColorspace(image,RGBColorspace,exception); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace: %d", (int) image->colorspace); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()"); return(image); } #if defined(JNG_SUPPORTED) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadOneJNGImage method is: % % Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const Quantum *s; register ssize_t i, x; register Quantum *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MagickPathExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MagickPathExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) chunk[i]=(unsigned char) ReadBlobByte(image); p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError, "NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info,exception); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); (void) AcquireUniqueFilename(color_image->filename); status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info,exception); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->resolution.x=(double) mng_get_long(p); image->resolution.y=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->resolution.x=image->resolution.x/100.0f; image->resolution.y=image->resolution.y/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into alpha samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MagickPathExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->rows=jng_height; image->columns=jng_width; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelRed(image,GetPixelRed(jng_image,s),q); SetPixelGreen(image,GetPixelGreen(jng_image,s),q); SetPixelBlue(image,GetPixelBlue(jng_image,s),q); q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) CloseBlob(alpha_image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading alpha from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MagickPathExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->alpha_trait != UndefinedPixelTrait) for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelAlpha(image,GetPixelRed(jng_image,s),q); q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } else for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelAlpha(image,GetPixelRed(jng_image,s),q); if (GetPixelAlpha(image,q) != OpaqueAlpha) image->alpha_trait=BlendPixelTrait; q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage()"); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJNGImage() reads a JPEG Network Graphics (JNG) image file % (including the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadJNGImage method is: % % Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo % *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MagickPathExtent]; size_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()"); image=AcquireImage(image_info,exception); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); if (LocaleCompare(image_info->magick,"JNG") != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify JNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneJNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (image->columns == 0 || image->rows == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); ThrowReaderException(CorruptImageError,"CorruptImage"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()"); return(image); } #endif static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MagickPathExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False during convert or mogrify */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MagickPathExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) chunk[i]=(unsigned char) ReadBlobByte(image); p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length < 2) { if (chunk) chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream","`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 13) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 15) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 17) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { /* Interpolate */ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelChannel() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } /* To do: Rewrite using Get/Set***PixelChannel() */ else { /* Interpolate */ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { /* Interpolate */ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneMNGImage();"); return(image); } static Image *ReadMNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()"); image=AcquireImage(image_info,exception); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneMNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadMNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()"); return(GetFirstImageInList(image)); } #else /* PNG_LIBPNG_VER > 10011 */ static Image *ReadPNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "PNG library is too old","`%s'",image_info->filename); return(Image *) NULL; } static Image *ReadMNGImage(const ImageInfo *image_info, ExceptionInfo *exception) { return(ReadPNGImage(image_info,exception)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNGImage() adds properties for the PNG image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNGImage method is: % % size_t RegisterPNGImage(void) % */ ModuleExport size_t RegisterPNGImage(void) { char version[MagickPathExtent]; MagickInfo *entry; static const char *PNGNote= { "See http://www.libpng.org/ for details about the PNG format." }, *JNGNote= { "See http://www.libpng.org/pub/mng/ for details about the JNG\n" "format." }, *MNGNote= { "See http://www.libpng.org/pub/mng/ for details about the MNG\n" "format." }; *version='\0'; #if defined(PNG_LIBPNG_VER_STRING) (void) ConcatenateMagickString(version,"libpng ",MagickPathExtent); (void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING, MagickPathExtent); if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0) { (void) ConcatenateMagickString(version,",",MagickPathExtent); (void) ConcatenateMagickString(version,png_get_libpng_ver(NULL), MagickPathExtent); } #endif entry=AcquireMagickInfo("PNG","MNG","Multiple-image Network Graphics"); entry->flags|=CoderSeekableStreamFlag; /* To do: eliminate this. */ #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMNGImage; entry->encoder=(EncodeImageHandler *) WriteMNGImage; #endif entry->magick=(IsImageFormatHandler *) IsMNG; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("video/x-mng"); entry->note=ConstantString(MNGNote); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG","Portable Network Graphics"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); if (*version != '\0') entry->version=ConstantString(version); entry->note=ConstantString(PNGNote); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG8", "8-bit indexed with optional binary transparency"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG24", "opaque or binary transparent 24-bit RGB"); *version='\0'; #if defined(ZLIB_VERSION) (void) ConcatenateMagickString(version,"zlib ",MagickPathExtent); (void) ConcatenateMagickString(version,ZLIB_VERSION,MagickPathExtent); if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0) { (void) ConcatenateMagickString(version,",",MagickPathExtent); (void) ConcatenateMagickString(version,zlib_version,MagickPathExtent); } #endif if (*version != '\0') entry->version=ConstantString(version); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG32","opaque or transparent 32-bit RGBA"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG48", "opaque or binary transparent 48-bit RGB"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG64","opaque or transparent 64-bit RGBA"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","PNG00", "PNG inheriting bit-depth, color-type from original, if possible"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/png"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNG","JNG","JPEG Network Graphics"); #if defined(JNG_SUPPORTED) #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJNGImage; entry->encoder=(EncodeImageHandler *) WriteJNGImage; #endif #endif entry->magick=(IsImageFormatHandler *) IsJNG; entry->flags^=CoderAdjoinFlag; entry->mime_type=ConstantString("image/x-jng"); entry->note=ConstantString(JNGNote); (void) RegisterMagickInfo(entry); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE ping_semaphore=AcquireSemaphoreInfo(); #endif return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNGImage() removes format registrations made by the % PNG module from the list of supported formats. % % The format of the UnregisterPNGImage method is: % % UnregisterPNGImage(void) % */ ModuleExport void UnregisterPNGImage(void) { (void) UnregisterMagickInfo("MNG"); (void) UnregisterMagickInfo("PNG"); (void) UnregisterMagickInfo("PNG8"); (void) UnregisterMagickInfo("PNG24"); (void) UnregisterMagickInfo("PNG32"); (void) UnregisterMagickInfo("PNG48"); (void) UnregisterMagickInfo("PNG64"); (void) UnregisterMagickInfo("PNG00"); (void) UnregisterMagickInfo("JNG"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE if (ping_semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&ping_semaphore); #endif } #if defined(MAGICKCORE_PNG_DELEGATE) #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMNGImage() writes an image in the Portable Network Graphics % Group's "Multiple-image Network Graphics" encoded image format. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteMNGImage method is: % % MagickBooleanType WriteMNGImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % % To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also % "To do" under ReadPNGImage): % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % Write the iCCP chunk at MNG level when (icc profile length > 0) % % Improve selection of color type (use indexed-colour or indexed-colour % with tRNS when 256 or fewer unique RGBA values are present). % % Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3) % This will be complicated if we limit ourselves to generating MNG-LC % files. For now we ignore disposal method 3 and simply overlay the next % image on it. % % Check for identical PLTE's or PLTE/tRNS combinations and use a % global MNG PLTE or PLTE/tRNS combination when appropriate. % [mostly done 15 June 1999 but still need to take care of tRNS] % % Check for identical sRGB and replace with a global sRGB (and remove % gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and % replace with global gAMA/cHRM (or with sRGB if appropriate; replace % local gAMA/cHRM with local sRGB if appropriate). % % Check for identical sBIT chunks and write global ones. % % Provide option to skip writing the signature tEXt chunks. % % Use signatures to detect identical objects and reuse the first % instance of such objects instead of writing duplicate objects. % % Use a smaller-than-32k value of compression window size when % appropriate. % % Encode JNG datastreams. Mostly done as of 5.5.2; need to write % ancillary text chunks and save profiles. % % Provide an option to force LC files (to ensure exact framing rate) % instead of VLC. % % Provide an option to force VLC files instead of LC, even when offsets % are present. This will involve expanding the embedded images with a % transparent region at the top and/or left. */ static void Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping, png_info *ping_info, unsigned char *profile_type, unsigned char *profile_description, unsigned char *profile_data, png_uint_32 length) { png_textp text; register ssize_t i; unsigned char *sp; png_charp dp; png_uint_32 allocated_length, description_length; unsigned char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0) return; if (image_info->verbose) { (void) printf("writing raw profile: type=%s, length=%.20g\n", (char *) profile_type, (double) length); } #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif description_length=(png_uint_32) strlen((const char *) profile_description); allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20 + description_length); #if PNG_LIBPNG_VER >= 10400 text[0].text=(png_charp) png_malloc(ping, (png_alloc_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80); #else text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80); #endif text[0].key[0]='\0'; (void) ConcatenateMagickString(text[0].key, "Raw profile type ",MagickPathExtent); (void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62); sp=profile_data; dp=text[0].text; *dp++='\n'; (void) CopyMagickString(dp,(const char *) profile_description, allocated_length); dp+=description_length; *dp++='\n'; (void) FormatLocaleString(dp,allocated_length- (png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length); dp+=8; for (i=0; i < (ssize_t) length; i++) { if (i%36 == 0) *dp++='\n'; *(dp++)=(char) hex[((*sp >> 4) & 0x0f)]; *(dp++)=(char) hex[((*sp++ ) & 0x0f)]; } *dp++='\n'; *dp='\0'; text[0].text_length=(png_size_t) (dp-text[0].text); text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? -1 : 0; if (text[0].text_length <= allocated_length) png_set_text(ping,ping_info,text,1); png_free(ping,text[0].text); png_free(ping,text[0].key); png_free(ping,text); } static MagickBooleanType Magick_png_write_chunk_from_profile(Image *image, const char *string, MagickBooleanType logging) { char *name; const StringInfo *profile; unsigned char *data; png_uint_32 length; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (const StringInfo *) NULL) { StringInfo *ping_profile; if (LocaleNCompare(name,string,11) == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found %s profile",name); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); data[4]=data[3]; data[3]=data[2]; data[2]=data[1]; data[1]=data[0]; (void) WriteBlobMSBULong(image,length-5); /* data length */ (void) WriteBlob(image,length-1,data+1); (void) WriteBlobMSBULong(image,crc32(0,data+1,(uInt) length-1)); ping_profile=DestroyStringInfo(ping_profile); } } name=GetNextImageProfile(image); } return(MagickTrue); } static inline MagickBooleanType Magick_png_color_equal(const Image *image, const Quantum *p, const PixelInfo *q) { MagickRealType value; value=(MagickRealType) p[image->channel_map[RedPixelChannel].offset]; if (AbsolutePixelValue(value-q->red) >= MagickEpsilon) return(MagickFalse); value=(MagickRealType) p[image->channel_map[GreenPixelChannel].offset]; if (AbsolutePixelValue(value-q->green) >= MagickEpsilon) return(MagickFalse); value=(MagickRealType) p[image->channel_map[BluePixelChannel].offset]; if (AbsolutePixelValue(value-q->blue) >= MagickEpsilon) return(MagickFalse); return(MagickTrue); } #if defined(PNG_tIME_SUPPORTED) static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info, const char *date,ExceptionInfo *exception) { unsigned int day, hour, minute, month, second, year; png_time ptime; time_t ttime; if (date != (const char *) NULL) { if (sscanf(date,"%d-%d-%dT%d:%d:%dZ",&year,&month,&day,&hour,&minute, &second) != 6) { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "Invalid date format specified for png:tIME","`%s'", image->filename); return; } ptime.year=(png_uint_16) year; ptime.month=(png_byte) month; ptime.day=(png_byte) day; ptime.hour=(png_byte) hour; ptime.minute=(png_byte) minute; ptime.second=(png_byte) second; } else { time(&ttime); png_convert_from_time_t(&ptime,ttime); } png_set_tIME(ping,info,&ptime); } #endif /* Write one PNG image */ static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char s[2]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, #ifdef exIf_SUPPORTED ping_have_eXIf, #endif ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ #ifdef exIf_SUPPORTED ping_exclude_eXIf, #endif ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); image = CloneImage(IMimage,0,0,MagickFalse,exception); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); if (image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; #ifdef exIf_SUPPORTED ping_have_eXIf=MagickTrue; #endif ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; #ifdef exIf_SUPPORTED /* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; */ ping_exclude_eXIf=mng_info->ping_exclude_eXIf; #endif ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_vpAg=mng_info->ping_exclude_vpAg; ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *s; register Quantum *q, *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->alpha_trait=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,q) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image, q, opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (Magick_png_color_equal(image,q,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image, q, opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,q) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image, q, transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,q); ping_trans_color.green=(unsigned short) GetPixelGreen(image,q); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,q); ping_trans_color.gray=(unsigned short) GetPixelGray(image,q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (Magick_png_color_equal(image,q,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,q,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,q,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (Magick_png_color_equal(image,q,semitransparent+i) && GetPixelAlpha(image,q) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image, q, semitransparent+i); } } } q+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != GetPixelGreen(image,s) || GetPixelRed(image,s) != GetPixelBlue(image,s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != 0 && GetPixelRed(image,s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) < OpaqueAlpha/2) { SetPixelViaPixelInfo(image,&image->background_color,r); SetPixelAlpha(image,TransparentAlpha,r); } else SetPixelAlpha(image,OpaqueAlpha,r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha/2 ? TransparentAlpha : OpaqueAlpha); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR04PixelRGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR03RGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR02PixelBlue(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 && GetPixelAlpha(image,r) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),r); } r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",IMimage->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates "-define png:compression-strategy", etc. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { /* Add an opaque matte channel */ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { /* Do not write hex-encoded ICC chunk */ name=GetNextImageProfile(image); continue; } } #endif /* WRITE_iCCP */ #if defined(eXIf_SUPPORTED) || defined(exIf_SUPPORTED) if (LocaleCompare(name,"exif") == 0) { /* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk */ name=GetNextImageProfile(image); continue; } #endif (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXt chunk with uuencoded %s profile", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } /* write any png-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging); png_write_info(ping,ping_info); /* write any PNG-chunk-m profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging); ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif /* write vpAg chunk (deprecated, replaced by caNv) */ if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { unsigned char chunk[14]; (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } } #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const Quantum *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write any PNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging); #ifdef exIf_SUPPORTED /* write exIf profile */ #ifdef IM if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) #endif { #ifdef GM ImageProfileIterator *profile_iterator; profile_iterator=AllocateImageProfileIterator(image); if (profile_iterator) { const char *profile_name; const unsigned char *profile_info; size_t profile_length; while (NextImageProfile(profile_iterator,&profile_name,&profile_info, &profile_length) != MagickFail) { if (LocaleCompare(profile_name,"exif") == 0) { #else /* IM */ char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #endif /* GM */ png_uint_32 length; unsigned char chunk[4], *data; #ifdef IM StringInfo *ping_profile; #endif (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); #ifdef GM data=profile_info; length=(png_uint_32) profile_length; #else /* IM */ ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); #endif /* GM */ #if 0 /* eXIf chunk is registered */ PNGType(chunk,mng_eXIf); #else /* eXIf chunk not yet registered; write exIf instead */ PNGType(chunk,mng_exIf); #endif if (length < 7) break; /* othewise crashes */ /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data+6); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data+6, (uInt) length)); break; #ifdef IM name=GetNextImageProfile(image); #endif } } } } #endif /* exIf_SUPPORTED */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNGImage() writes a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WritePNGImage method is: % % MagickBooleanType WritePNGImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % % Returns MagickTrue on success, MagickFalse on failure. % % Communicating with the PNG encoder: % % While the datastream written is always in PNG format and normally would % be given the "png" file extension, this method also writes the following % pseudo-formats which are subsets of png: % % o PNG8: An 8-bit indexed PNG datastream is written. If the image has % a depth greater than 8, the depth is reduced. If transparency % is present, the tRNS chunk must only have values 0 and 255 % (i.e., transparency is binary: fully opaque or fully % transparent). If other values are present they will be % 50%-thresholded to binary transparency. If more than 256 % colors are present, they will be quantized to the 4-4-4-1, % 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color % of any resulting fully-transparent pixels is changed to % the image's background color. % % If you want better quantization or dithering of the colors % or alpha than that, you need to do it before calling the % PNG encoder. The pixels contain 8-bit indices even if % they could be represented with 1, 2, or 4 bits. Grayscale % images will be written as indexed PNG files even though the % PNG grayscale type might be slightly more efficient. Please % note that writing to the PNG8 format may result in loss % of color and alpha data. % % o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. The only loss incurred % is reduction of sample depth to 8. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG32: An 8-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 255. The alpha % channel is present even if the image is fully opaque. % The only loss in data is the reduction of the sample depth % to 8. % % o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG64: A 16-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 65535. The alpha % channel is present even if the image is fully opaque. % % o PNG00: A PNG that inherits its colortype and bit-depth from the input % image, if the input was a PNG, is written. If these values % cannot be found, or if the pixels have been changed in a way % that makes this impossible, then "PNG00" falls back to the % regular "PNG" format. % % o -define: For more precise control of the PNG output, you can use the % Image options "png:bit-depth" and "png:color-type". These % can be set from the commandline with "-define" and also % from the application programming interfaces. The options % are case-independent and are converted to lowercase before % being passed to this encoder. % % png:color-type can be 0, 2, 3, 4, or 6. % % When png:color-type is 0 (Grayscale), png:bit-depth can % be 1, 2, 4, 8, or 16. % % When png:color-type is 2 (RGB), png:bit-depth can % be 8 or 16. % % When png:color-type is 3 (Indexed), png:bit-depth can % be 1, 2, 4, or 8. This refers to the number of bits % used to store the index. The color samples always have % bit-depth 8 in indexed PNG files. % % When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte), % png:bit-depth can be 8 or 16. % % If the image cannot be written without loss with the % requested bit-depth and color-type, a PNG file will not % be written, a warning will be issued, and the encoder will % return MagickFalse. % % Since image encoders should not be responsible for the "heavy lifting", % the user should make sure that ImageMagick has already reduced the % image depth and number of colors and limit transparency to binary % transparency prior to attempting to write the image with depth, color, % or transparency limitations. % % Note that another definition, "png:bit-depth-written" exists, but it % is not intended for external use. It is only used internally by the % PNG encoder to inform the JNG encoder of the depth of the alpha channel. % % It is possible to request that the PNG encoder write previously-formatted % ancillary chunks in the output PNG file, using the "-profile" commandline % option as shown below or by setting the profile via a programming % interface: % % -profile PNG-chunk-x:<file> % % where x is a location flag and <file> is a file containing the chunk % name in the first 4 bytes, then a colon (":"), followed by the chunk data. % This encoder will compute the chunk length and CRC, so those must not % be included in the file. % % "x" can be "b" (before PLTE), "m" (middle, i.e., between PLTE and IDAT), % or "e" (end, i.e., after IDAT). If you want to write multiple chunks % of the same type, then add a short unique string after the "x" to prevent % subsequent profiles from overwriting the preceding ones, e.g., % % -profile PNG-chunk-b01:file01 -profile PNG-chunk-b02:file02 % % As of version 6.6.6 the following optimizations are always done: % % o 32-bit depth is reduced to 16. % o 16-bit depth is reduced to 8 if all pixels contain samples whose % high byte and low byte are identical. % o Palette is sorted to remove unused entries and to put a % transparent color first, if BUILD_PNG_PALETTE is defined. % o Opaque matte channel is removed when writing an indexed PNG. % o Grayscale images are reduced to 1, 2, or 4 bit depth if % this can be done without loss and a larger bit depth N was not % requested via the "-define png:bit-depth=N" option. % o If matte channel is present but only one transparent color is % present, RGB+tRNS is written instead of RGBA % o Opaque matte channel is removed (or added, if color-type 4 or 6 % was requested when converting an opaque image). % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { MagickBooleanType excluding, logging, status; MngInfo *mng_info; const char *value; int source; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; mng_info->equal_backgrounds=MagickTrue; /* See if user has requested a specific PNG subformat */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0; mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0; value=GetImageOption(image_info,"png:format"); if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",value); mng_info->write_png8 = MagickFalse; mng_info->write_png24 = MagickFalse; mng_info->write_png32 = MagickFalse; mng_info->write_png48 = MagickFalse; mng_info->write_png64 = MagickFalse; if (LocaleCompare(value,"png8") == 0) mng_info->write_png8 = MagickTrue; else if (LocaleCompare(value,"png24") == 0) mng_info->write_png24 = MagickTrue; else if (LocaleCompare(value,"png32") == 0) mng_info->write_png32 = MagickTrue; else if (LocaleCompare(value,"png48") == 0) mng_info->write_png48 = MagickTrue; else if (LocaleCompare(value,"png64") == 0) mng_info->write_png64 = MagickTrue; else if ((LocaleCompare(value,"png00") == 0) || LocaleCompare(image_info->magick,"PNG00") == 0) { /* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig. */ value=GetImageProperty(image,"png:IHDR.bit-depth-orig",exception); if (value != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited bit depth=%s",value); if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; } value=GetImageProperty(image,"png:IHDR.color-type-orig",exception); if (value != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited color type=%s",value); if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; } } } if (mng_info->write_png8) { mng_info->write_png_colortype = /* 3 */ 4; mng_info->write_png_depth = 8; image->depth = 8; } if (mng_info->write_png24) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 8; image->depth = 8; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageType(image,TrueColorAlphaType,exception); else (void) SetImageType(image,TrueColorType,exception); (void) SyncImage(image,exception); } if (mng_info->write_png32) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 8; image->depth = 8; image->alpha_trait = BlendPixelTrait; (void) SetImageType(image,TrueColorAlphaType,exception); (void) SyncImage(image,exception); } if (mng_info->write_png48) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 16; image->depth = 16; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageType(image,TrueColorAlphaType,exception); else (void) SetImageType(image,TrueColorType,exception); (void) SyncImage(image,exception); } if (mng_info->write_png64) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 16; image->depth = 16; image->alpha_trait = BlendPixelTrait; (void) SetImageType(image,TrueColorAlphaType,exception); (void) SyncImage(image,exception); } value=GetImageOption(image_info,"png:bit-depth"); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:bit-depth", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:bit-depth=%d was defined.\n",mng_info->write_png_depth); } value=GetImageOption(image_info,"png:color-type"); if (value != (char *) NULL) { /* We must store colortype+1 because 0 is a valid colortype */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_colortype = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:color-type", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:color-type=%d was defined.\n", mng_info->write_png_colortype-1); } /* Check for chunks to be excluded: * * The default is to not exclude any known chunks except for any * listed in the "unused_chunks" array, above. * * Chunks can be listed for exclusion via a "png:exclude-chunk" * define (in the image properties or in the image artifacts) * or via a mng_info member. For convenience, in addition * to or instead of a comma-separated list of chunks, the * "exclude-chunk" string can be simply "all" or "none". * * The exclude-chunk define takes priority over the mng_info. * * A "png:include-chunk" define takes priority over both the * mng_info and the "png:exclude-chunk" define. Like the * "exclude-chunk" string, it can define "all" or "none" as * well as a comma-separated list. Chunks that are unknown to * ImageMagick are always excluded, regardless of their "copy-safe" * status according to the PNG specification, and even if they * appear in the "include-chunk" list. Such defines appearing among * the image options take priority over those found among the image * artifacts. * * Finally, all chunks listed in the "unused_chunks" array are * automatically excluded, regardless of the other instructions * or lack thereof. * * if you exclude sRGB but not gAMA (recommended), then sRGB chunk * will not be written and the gAMA chunk will only be written if it * is not between .45 and .46, or approximately (1.0/2.2). * * If you exclude tRNS and the image has transparency, the colortype * is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA). * * The -strip option causes StripImage() to set the png:include-chunk * artifact to "none,trns,gama". */ mng_info->ping_exclude_bKGD=MagickFalse; mng_info->ping_exclude_caNv=MagickFalse; mng_info->ping_exclude_cHRM=MagickFalse; mng_info->ping_exclude_date=MagickFalse; mng_info->ping_exclude_eXIf=MagickFalse; mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */ mng_info->ping_exclude_gAMA=MagickFalse; mng_info->ping_exclude_iCCP=MagickFalse; /* mng_info->ping_exclude_iTXt=MagickFalse; */ mng_info->ping_exclude_oFFs=MagickFalse; mng_info->ping_exclude_pHYs=MagickFalse; mng_info->ping_exclude_sRGB=MagickFalse; mng_info->ping_exclude_tEXt=MagickFalse; mng_info->ping_exclude_tIME=MagickFalse; mng_info->ping_exclude_tRNS=MagickFalse; mng_info->ping_exclude_vpAg=MagickFalse; mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */ mng_info->ping_exclude_zTXt=MagickFalse; mng_info->ping_preserve_colormap=MagickFalse; value=GetImageOption(image_info,"png:preserve-colormap"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-colormap"); if (value != NULL) mng_info->ping_preserve_colormap=MagickTrue; mng_info->ping_preserve_iCCP=MagickFalse; value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) mng_info->ping_preserve_iCCP=MagickTrue; /* These compression-level, compression-strategy, and compression-filter * defines take precedence over values from the -quality option. */ value=GetImageOption(image_info,"png:compression-level"); if (value == NULL) value=GetImageArtifact(image,"png:compression-level"); if (value != NULL) { /* We have to add 1 to everything because 0 is a valid input, * and we want to use 0 (the default) to mean undefined. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_level = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_level = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_level = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_level = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_level = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_level = 6; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_compression_level = 7; else if (LocaleCompare(value,"7") == 0) mng_info->write_png_compression_level = 8; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_compression_level = 9; else if (LocaleCompare(value,"9") == 0) mng_info->write_png_compression_level = 10; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-level", "=%s",value); } value=GetImageOption(image_info,"png:compression-strategy"); if (value == NULL) value=GetImageArtifact(image,"png:compression-strategy"); if (value != NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_strategy = Z_FILTERED+1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; else if (LocaleCompare(value,"3") == 0) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy = Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else if (LocaleCompare(value,"4") == 0) #ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */ mng_info->write_png_compression_strategy = Z_FIXED+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-strategy", "=%s",value); } value=GetImageOption(image_info,"png:compression-filter"); if (value == NULL) value=GetImageArtifact(image,"png:compression-filter"); if (value != NULL) { /* To do: combinations of filters allowed by libpng * masks 0x08 through 0xf8 * * Implement this as a comma-separated list of 0,1,2,3,4,5 * where 5 is a special case meaning PNG_ALL_FILTERS. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_filter = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_filter = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_filter = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_filter = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_filter = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_filter = 6; else (void) ThrowMagickException(exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-filter", "=%s",value); } for (source=0; source<8; source++) { value = NULL; if (source == 0) value=GetImageOption(image_info,"png:exclude-chunks"); if (source == 1) value=GetImageArtifact(image,"png:exclude-chunks"); if (source == 2) value=GetImageOption(image_info,"png:exclude-chunk"); if (source == 3) value=GetImageArtifact(image,"png:exclude-chunk"); if (source == 4) value=GetImageOption(image_info,"png:include-chunks"); if (source == 5) value=GetImageArtifact(image,"png:include-chunks"); if (source == 6) value=GetImageOption(image_info,"png:include-chunk"); if (source == 7) value=GetImageArtifact(image,"png:include-chunk"); if (value == NULL) continue; if (source < 4) excluding = MagickTrue; else excluding = MagickFalse; if (logging != MagickFalse) { if (source == 0 || source == 2) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image options.\n", value); else if (source == 1 || source == 3) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image artifacts.\n", value); else if (source == 4 || source == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image options.\n", value); else /* if (source == 5 || source == 7) */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image artifacts.\n", value); } if (IsOptionMember("all",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding; mng_info->ping_exclude_caNv=excluding; mng_info->ping_exclude_cHRM=excluding; mng_info->ping_exclude_date=excluding; mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; mng_info->ping_exclude_gAMA=excluding; mng_info->ping_exclude_iCCP=excluding; /* mng_info->ping_exclude_iTXt=excluding; */ mng_info->ping_exclude_oFFs=excluding; mng_info->ping_exclude_pHYs=excluding; mng_info->ping_exclude_sRGB=excluding; mng_info->ping_exclude_tEXt=excluding; mng_info->ping_exclude_tIME=excluding; mng_info->ping_exclude_tRNS=excluding; mng_info->ping_exclude_vpAg=excluding; mng_info->ping_exclude_zCCP=excluding; mng_info->ping_exclude_zTXt=excluding; } if (IsOptionMember("none",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; /* mng_info->ping_exclude_iTXt=!excluding; */ mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_vpAg=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse : MagickTrue; } if (IsOptionMember("bkgd",value) != MagickFalse) mng_info->ping_exclude_bKGD=excluding; if (IsOptionMember("caNv",value) != MagickFalse) mng_info->ping_exclude_caNv=excluding; if (IsOptionMember("chrm",value) != MagickFalse) mng_info->ping_exclude_cHRM=excluding; if (IsOptionMember("date",value) != MagickFalse) mng_info->ping_exclude_date=excluding; if (IsOptionMember("exif",value) != MagickFalse) { mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; } if (IsOptionMember("gama",value) != MagickFalse) mng_info->ping_exclude_gAMA=excluding; if (IsOptionMember("iccp",value) != MagickFalse) mng_info->ping_exclude_iCCP=excluding; #if 0 if (IsOptionMember("itxt",value) != MagickFalse) mng_info->ping_exclude_iTXt=excluding; #endif if (IsOptionMember("offs",value) != MagickFalse) mng_info->ping_exclude_oFFs=excluding; if (IsOptionMember("phys",value) != MagickFalse) mng_info->ping_exclude_pHYs=excluding; if (IsOptionMember("srgb",value) != MagickFalse) mng_info->ping_exclude_sRGB=excluding; if (IsOptionMember("text",value) != MagickFalse) mng_info->ping_exclude_tEXt=excluding; if (IsOptionMember("time",value) != MagickFalse) mng_info->ping_exclude_tIME=excluding; if (IsOptionMember("trns",value) != MagickFalse) mng_info->ping_exclude_tRNS=excluding; if (IsOptionMember("vpag",value) != MagickFalse) mng_info->ping_exclude_vpAg=excluding; if (IsOptionMember("zccp",value) != MagickFalse) mng_info->ping_exclude_zCCP=excluding; if (IsOptionMember("ztxt",value) != MagickFalse) mng_info->ping_exclude_zTXt=excluding; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Chunks to be excluded from the output png:"); if (mng_info->ping_exclude_bKGD != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bKGD"); if (mng_info->ping_exclude_caNv != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " caNv"); if (mng_info->ping_exclude_cHRM != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " cHRM"); if (mng_info->ping_exclude_date != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " date"); if (mng_info->ping_exclude_EXIF != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " EXIF"); if (mng_info->ping_exclude_eXIf != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " eXIf"); if (mng_info->ping_exclude_gAMA != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " gAMA"); if (mng_info->ping_exclude_iCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iCCP"); #if 0 if (mng_info->ping_exclude_iTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iTXt"); #endif if (mng_info->ping_exclude_oFFs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " oFFs"); if (mng_info->ping_exclude_pHYs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pHYs"); if (mng_info->ping_exclude_sRGB != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " sRGB"); if (mng_info->ping_exclude_tEXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tEXt"); if (mng_info->ping_exclude_tIME != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tIME"); if (mng_info->ping_exclude_tRNS != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS"); if (mng_info->ping_exclude_vpAg != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " vpAg"); if (mng_info->ping_exclude_zCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zCCP"); if (mng_info->ping_exclude_zTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zTXt"); } mng_info->need_blob = MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image,exception); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()"); return(status); } #if defined(JNG_SUPPORTED) /* Write one JNG image */ static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image,ExceptionInfo *exception) { Image *jpeg_image; ImageInfo *jpeg_image_info; MagickBooleanType logging, status; size_t length; unsigned char *blob, chunk[80], *p; unsigned int jng_alpha_compression_method, jng_alpha_sample_depth, jng_color_type, transparent; size_t jng_alpha_quality, jng_quality; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOneJNGImage()"); blob=(unsigned char *) NULL; jpeg_image=(Image *) NULL; jpeg_image_info=(ImageInfo *) NULL; length=0; status=MagickTrue; transparent=image_info->type==GrayscaleAlphaType || image_info->type==TrueColorAlphaType || image->alpha_trait != UndefinedPixelTrait; jng_alpha_sample_depth = 0; jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000; jng_alpha_compression_method=image->compression==JPEGCompression? 8 : 0; jng_alpha_quality=image_info->quality == 0UL ? 75UL : image_info->quality; if (jng_alpha_quality >= 1000) jng_alpha_quality /= 1000; length=0; if (transparent != 0) { jng_color_type=14; /* Create JPEG blob, image, and image_info */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info for alpha."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=SeparateImage(image,AlphaChannel,exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); jpeg_image->alpha_trait=UndefinedPixelTrait; jpeg_image->quality=jng_alpha_quality; jpeg_image_info->type=GrayscaleType; (void) SetImageType(jpeg_image,GrayscaleType,exception); (void) AcquireUniqueFilename(jpeg_image->filename); (void) FormatLocaleString(jpeg_image_info->filename,MagickPathExtent, "%s",jpeg_image->filename); } else { jng_alpha_compression_method=0; jng_color_type=10; jng_alpha_sample_depth=0; } /* To do: check bit depth of PNG alpha channel */ /* Check if image is grayscale. */ if (image_info->type != TrueColorAlphaType && image_info->type != TrueColorType && SetImageGray(image,exception)) jng_color_type-=2; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Quality = %d",(int) jng_quality); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Color Type = %d",jng_color_type); if (transparent != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Compression = %d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Depth = %d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Quality = %d",(int) jng_alpha_quality); } } if (transparent != 0) { if (jng_alpha_compression_method==0) { const char *value; /* Encode alpha as a grayscale PNG blob */ status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating PNG blob."); (void) CopyMagickString(jpeg_image_info->magick,"PNG", MagickPathExtent); (void) CopyMagickString(jpeg_image->magick,"PNG",MagickPathExtent); jpeg_image_info->interlace=NoInterlace; /* Exclude all ancillary chunks */ (void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all"); blob=(unsigned char *) ImageToBlob(jpeg_image_info,jpeg_image, &length,exception); /* Retrieve sample depth used */ value=GetImageProperty(jpeg_image,"png:bit-depth-written",exception); if (value != (char *) NULL) jng_alpha_sample_depth= (unsigned int) value[0]; } else { /* Encode alpha as a grayscale JPEG blob */ status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image_info->magick,"JPEG", MagickPathExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); jpeg_image_info->interlace=NoInterlace; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=(unsigned char *) ImageToBlob(jpeg_image_info, jpeg_image,&length, exception); jng_alpha_sample_depth=8; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); } /* Destroy JPEG image and image_info */ jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); jpeg_image_info=DestroyImageInfo(jpeg_image_info); } /* Write JHDR chunk */ (void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */ PNGType(chunk,mng_JHDR); LogPNGChunk(logging,mng_JHDR,16L); PNGLong(chunk+4,(png_uint_32) image->columns); PNGLong(chunk+8,(png_uint_32) image->rows); chunk[12]=jng_color_type; chunk[13]=8; /* sample depth */ chunk[14]=8; /*jng_image_compression_method */ chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8); chunk[16]=jng_alpha_sample_depth; chunk[17]=jng_alpha_compression_method; chunk[18]=0; /*jng_alpha_filter_method */ chunk[19]=0; /*jng_alpha_interlace_method */ (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width:%15lu",(unsigned long) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG height:%14lu",(unsigned long) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG color type:%10d",jng_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG sample depth:%8d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG compression:%9d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG interlace:%11d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha depth:%9d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha compression:%3d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha filter:%8d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha interlace:%5d",0); } /* Write any JNG-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-b",logging); /* Write leading ancillary chunks */ if (transparent != 0) { /* Write JNG bKGD chunk */ unsigned char blue, green, red; ssize_t num_bytes; if (jng_color_type == 8 || jng_color_type == 12) num_bytes=6L; else num_bytes=10L; (void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L)); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L)); red=ScaleQuantumToChar(image->background_color.red); green=ScaleQuantumToChar(image->background_color.green); blue=ScaleQuantumToChar(image->background_color.blue); *(chunk+4)=0; *(chunk+5)=red; *(chunk+6)=0; *(chunk+7)=green; *(chunk+8)=0; *(chunk+9)=blue; (void) WriteBlob(image,(size_t) num_bytes,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes)); } if ((image->colorspace == sRGBColorspace || image->rendering_intent)) { /* Write JNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { if (image->gamma != 0.0) { /* Write JNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); } if ((mng_info->equal_chrms == MagickFalse) && (image->chromaticity.red_primary.x != 0.0)) { PrimaryInfo primary; /* Write JNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); } } if (image->resolution.x && image->resolution.y && !mng_info->equal_physs) { /* Write JNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->resolution.x+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.x || image->page.y)) { /* Write JNG oFFs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_oFFs); LogPNGChunk(logging,mng_oFFs,9L); PNGsLong(chunk+4,(ssize_t) (image->page.x)); PNGsLong(chunk+8,(ssize_t) (image->page.y)); chunk[12]=0; (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.width || image->page.height)) { (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (transparent != 0) { if (jng_alpha_compression_method==0) { register ssize_t i; size_t len; /* Write IDAT chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write IDAT chunks from blob, length=%.20g.",(double) length); /* Copy IDAT chunks */ len=0; p=blob+8; for (i=8; i<(ssize_t) length; i+=len+12) { len=(size_t) (*p) << 24; len|=(size_t) (*(p+1)) << 16; len|=(size_t) (*(p+2)) << 8; len|=(size_t) (*(p+3)); p+=4; if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */ { /* Found an IDAT chunk. */ (void) WriteBlobMSBULong(image,len); LogPNGChunk(logging,mng_IDAT,len); (void) WriteBlob(image,len+4,p); (void) WriteBlobMSBULong(image, crc32(0,p,(uInt) len+4)); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping %c%c%c%c chunk, length=%.20g.", *(p),*(p+1),*(p+2),*(p+3),(double) len); } p+=(8+len); } } else if (length != 0) { /* Write JDAA chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAA chunk, length=%.20g.",(double) length); (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAA); LogPNGChunk(logging,mng_JDAA,length); /* Write JDAT chunk(s) data */ (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob, (uInt) length)); } blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Encode image as a JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); (void) AcquireUniqueFilename(jpeg_image->filename); (void) FormatLocaleString(jpeg_image_info->filename,MagickPathExtent,"%s", jpeg_image->filename); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns, (double) jpeg_image->rows); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (jng_color_type == 8 || jng_color_type == 12) jpeg_image_info->type=GrayscaleType; jpeg_image_info->quality=jng_quality; jpeg_image->quality=jng_quality; (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MagickPathExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MagickPathExtent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=(unsigned char *) ImageToBlob(jpeg_image_info,jpeg_image,&length, exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAT chunk, length=%.20g.",(double) length); } /* Write JDAT chunk(s) */ (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAT); LogPNGChunk(logging,mng_JDAT,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length)); jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); jpeg_image_info=DestroyImageInfo(jpeg_image_info); blob=(unsigned char *) RelinquishMagickMemory(blob); /* Write any JNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-e",logging); /* Write IEND chunk */ (void) WriteBlobMSBULong(image,0L); PNGType(chunk,mng_IEND); LogPNGChunk(logging,mng_IEND,0); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOneJNGImage()"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJNGImage() writes a JPEG Network Graphics (JNG) image file. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteJNGImage method is: % % MagickBooleanType WriteJNGImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WriteJNGImage(const ImageInfo *image_info, Image *image, ExceptionInfo *exception) { MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; (void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n"); status=WriteOneJNGImage(mng_info,image_info,image,exception); mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); (void) CatchImageException(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteJNGImage()"); return(status); } #endif static MagickBooleanType WriteMNGImage(const ImageInfo *image_info, Image *image, ExceptionInfo *exception) { Image *next_image; MagickBooleanType status; volatile MagickBooleanType logging; MngInfo *mng_info; int image_count, need_iterations, need_matte; volatile int #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) need_local_plte, #endif all_images_are_gray, need_defi, use_global_plte; register ssize_t i; unsigned char chunk[800]; volatile unsigned int write_jng, write_mng; volatile size_t scene; size_t final_delay=0, initial_delay; #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; write_mng=LocaleCompare(image_info->magick,"MNG") == 0; /* * See if user has requested a specific PNG subformat to be used * for all of the PNGs in the MNG being written, e.g., * * convert *.png png8:animation.mng * * To do: check -define png:bit_depth and png:color_type as well, * or perhaps use mng:bit_depth and mng:color_type instead for * global settings. */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; write_jng=MagickFalse; if (image_info->compression == JPEGCompression) write_jng=MagickTrue; mng_info->adjoin=image_info->adjoin && (GetNextImageInList(image) != (Image *) NULL) && write_mng; if (logging != MagickFalse) { /* Log some info about the input */ Image *p; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Checking input image(s)\n" " Image_info depth: %.20g, Type: %d", (double) image_info->depth, image_info->type); scene=0; for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scene: %.20g\n, Image depth: %.20g", (double) scene++, (double) p->depth); if (p->alpha_trait != UndefinedPixelTrait) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: False"); if (p->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: PseudoClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: DirectClass"); if (p->colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) p->colors); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: unspecified"); if (mng_info->adjoin == MagickFalse) break; } } use_global_plte=MagickFalse; all_images_are_gray=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_defi=MagickFalse; need_matte=MagickFalse; mng_info->framing_mode=1; mng_info->old_framing_mode=1; if (write_mng) if (image_info->page != (char *) NULL) { /* Determine image bounding box. */ SetGeometry(image,&mng_info->page); (void) ParseMetaGeometry(image_info->page,&mng_info->page.x, &mng_info->page.y,&mng_info->page.width,&mng_info->page.height); } if (write_mng) { unsigned int need_geom; unsigned short red, green, blue; const char * option; mng_info->page=image->page; need_geom=MagickTrue; if (mng_info->page.width || mng_info->page.height) need_geom=MagickFalse; /* Check all the scenes. */ initial_delay=image->delay; need_iterations=MagickFalse; mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0; mng_info->equal_physs=MagickTrue, mng_info->equal_gammas=MagickTrue; mng_info->equal_srgbs=MagickTrue; mng_info->equal_backgrounds=MagickTrue; image_count=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) all_images_are_gray=MagickTrue; mng_info->equal_palettes=MagickFalse; need_local_plte=MagickFalse; #endif for (next_image=image; next_image != (Image *) NULL; ) { if (need_geom) { if ((next_image->columns+next_image->page.x) > mng_info->page.width) mng_info->page.width=next_image->columns+next_image->page.x; if ((next_image->rows+next_image->page.y) > mng_info->page.height) mng_info->page.height=next_image->rows+next_image->page.y; } if (next_image->page.x || next_image->page.y) need_defi=MagickTrue; if (next_image->alpha_trait != UndefinedPixelTrait) need_matte=MagickTrue; if ((int) next_image->dispose >= BackgroundDispose) if ((next_image->alpha_trait != UndefinedPixelTrait) || next_image->page.x || next_image->page.y || ((next_image->columns < mng_info->page.width) && (next_image->rows < mng_info->page.height))) mng_info->need_fram=MagickTrue; if (next_image->iterations) need_iterations=MagickTrue; final_delay=next_image->delay; if (final_delay != initial_delay || final_delay > 1UL* next_image->ticks_per_second) mng_info->need_fram=1; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* check for global palette possibility. */ if (image->alpha_trait != UndefinedPixelTrait) need_local_plte=MagickTrue; if (need_local_plte == 0) { if (SetImageGray(image,exception) == MagickFalse) all_images_are_gray=MagickFalse; mng_info->equal_palettes=PalettesAreEqual(image,next_image); if (use_global_plte == 0) use_global_plte=mng_info->equal_palettes; need_local_plte=!mng_info->equal_palettes; } #endif if (GetNextImageInList(next_image) != (Image *) NULL) { if (next_image->background_color.red != next_image->next->background_color.red || next_image->background_color.green != next_image->next->background_color.green || next_image->background_color.blue != next_image->next->background_color.blue) mng_info->equal_backgrounds=MagickFalse; if (next_image->gamma != next_image->next->gamma) mng_info->equal_gammas=MagickFalse; if (next_image->rendering_intent != next_image->next->rendering_intent) mng_info->equal_srgbs=MagickFalse; if ((next_image->units != next_image->next->units) || (next_image->resolution.x != next_image->next->resolution.x) || (next_image->resolution.y != next_image->next->resolution.y)) mng_info->equal_physs=MagickFalse; if (mng_info->equal_chrms) { if (next_image->chromaticity.red_primary.x != next_image->next->chromaticity.red_primary.x || next_image->chromaticity.red_primary.y != next_image->next->chromaticity.red_primary.y || next_image->chromaticity.green_primary.x != next_image->next->chromaticity.green_primary.x || next_image->chromaticity.green_primary.y != next_image->next->chromaticity.green_primary.y || next_image->chromaticity.blue_primary.x != next_image->next->chromaticity.blue_primary.x || next_image->chromaticity.blue_primary.y != next_image->next->chromaticity.blue_primary.y || next_image->chromaticity.white_point.x != next_image->next->chromaticity.white_point.x || next_image->chromaticity.white_point.y != next_image->next->chromaticity.white_point.y) mng_info->equal_chrms=MagickFalse; } } image_count++; next_image=GetNextImageInList(next_image); } if (image_count < 2) { mng_info->equal_backgrounds=MagickFalse; mng_info->equal_chrms=MagickFalse; mng_info->equal_gammas=MagickFalse; mng_info->equal_srgbs=MagickFalse; mng_info->equal_physs=MagickFalse; use_global_plte=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_iterations=MagickFalse; } if (mng_info->need_fram == MagickFalse) { /* Only certain framing rates 100/n are exactly representable without the FRAM chunk but we'll allow some slop in VLC files */ if (final_delay == 0) { if (need_iterations != MagickFalse) { /* It's probably a GIF with loop; don't run it *too* fast. */ if (mng_info->adjoin) { final_delay=10; (void) ThrowMagickException(exception,GetMagickModule(), CoderWarning, "input has zero delay between all frames; assuming", " 10 cs `%s'",""); } } else mng_info->ticks_per_second=0; } if (final_delay != 0) mng_info->ticks_per_second=(png_uint_32) (image->ticks_per_second/final_delay); if (final_delay > 50) mng_info->ticks_per_second=2; if (final_delay > 75) mng_info->ticks_per_second=1; if (final_delay > 125) mng_info->need_fram=MagickTrue; if (need_defi && final_delay > 2 && (final_delay != 4) && (final_delay != 5) && (final_delay != 10) && (final_delay != 20) && (final_delay != 25) && (final_delay != 50) && (final_delay != (size_t) image->ticks_per_second)) mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */ } if (mng_info->need_fram != MagickFalse) mng_info->ticks_per_second=image->ticks_per_second; /* If pseudocolor, we should also check to see if all the palettes are identical and write a global PLTE if they are. ../glennrp Feb 99. */ /* Write the MNG version 1.0 signature and MHDR chunk. */ (void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n"); (void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */ PNGType(chunk,mng_MHDR); LogPNGChunk(logging,mng_MHDR,28L); PNGLong(chunk+4,(png_uint_32) mng_info->page.width); PNGLong(chunk+8,(png_uint_32) mng_info->page.height); PNGLong(chunk+12,mng_info->ticks_per_second); PNGLong(chunk+16,0L); /* layer count=unknown */ PNGLong(chunk+20,0L); /* frame count=unknown */ PNGLong(chunk+24,0L); /* play time=unknown */ if (write_jng) { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,27L); /* simplicity=LC+JNG */ else PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */ else PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */ } } else { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,11L); /* simplicity=LC */ else PNGLong(chunk+28,9L); /* simplicity=VLC */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */ else PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */ } } (void) WriteBlob(image,32,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,32)); option=GetImageOption(image_info,"mng:need-cacheoff"); if (option != (const char *) NULL) { size_t length; /* Write "nEED CACHEOFF" to turn playback caching off for streaming MNG. */ PNGType(chunk,mng_nEED); length=CopyMagickString((char *) chunk+4,"CACHEOFF",20); (void) WriteBlobMSBULong(image,(size_t) length); LogPNGChunk(logging,mng_nEED,(size_t) length); length+=4; (void) WriteBlob(image,length,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length)); } if ((GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) != (Image *) NULL) && (image->iterations != 1)) { /* Write MNG TERM chunk */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_TERM); LogPNGChunk(logging,mng_TERM,10L); chunk[4]=3; /* repeat animation */ chunk[5]=0; /* show last frame when done */ PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) PNGLong(chunk+10,PNG_UINT_31_MAX); else PNGLong(chunk+10,(png_uint_32) image->iterations); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM delay: %.20g",(double) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM iterations: %.20g",(double) PNG_UINT_31_MAX); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image iterations: %.20g",(double) image->iterations); } (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); } /* To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if ((image->colorspace == sRGBColorspace || image->rendering_intent) && mng_info->equal_srgbs) { /* Write MNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); mng_info->have_write_global_srgb=MagickTrue; } else { if (image->gamma && mng_info->equal_gammas) { /* Write MNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); mng_info->have_write_global_gama=MagickTrue; } if (mng_info->equal_chrms) { PrimaryInfo primary; /* Write MNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); mng_info->have_write_global_chrm=MagickTrue; } } if (image->resolution.x && image->resolution.y && mng_info->equal_physs) { /* Write MNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->resolution.x*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->resolution.x+0.5)); PNGLong(chunk+8,(png_uint_32) (image->resolution.y+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } /* Write MNG BACK chunk and global bKGD chunk, if the image is transparent or does not cover the entire frame. */ if (write_mng && ((image->alpha_trait != UndefinedPixelTrait) || image->page.x > 0 || image->page.y > 0 || (image->page.width && (image->page.width+image->page.x < mng_info->page.width)) || (image->page.height && (image->page.height+image->page.y < mng_info->page.height)))) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_BACK); LogPNGChunk(logging,mng_BACK,6L); red=ScaleQuantumToShort(image->background_color.red); green=ScaleQuantumToShort(image->background_color.green); blue=ScaleQuantumToShort(image->background_color.blue); PNGShort(chunk+4,red); PNGShort(chunk+6,green); PNGShort(chunk+8,blue); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); if (mng_info->equal_backgrounds) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,6L); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); } } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if ((need_local_plte == MagickFalse) && (image->storage_class == PseudoClass) && (all_images_are_gray == MagickFalse)) { size_t data_length; /* Write MNG PLTE chunk */ data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=(unsigned char) (ScaleQuantumToChar( image->colormap[i].red) & 0xff); chunk[5+i*3]=(unsigned char) (ScaleQuantumToChar( image->colormap[i].green) & 0xff); chunk[6+i*3]=(unsigned char) (ScaleQuantumToChar( image->colormap[i].blue) & 0xff); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } #endif } scene=0; mng_info->delay=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) mng_info->equal_palettes=MagickFalse; #endif do { if (mng_info->adjoin) { #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* If we aren't using a global palette for the entire MNG, check to see if we can use one for two or more consecutive images. */ if (need_local_plte && use_global_plte && !all_images_are_gray) { if (mng_info->IsPalette) { /* When equal_palettes is true, this image has the same palette as the previous PseudoClass image */ mng_info->have_write_global_plte=mng_info->equal_palettes; mng_info->equal_palettes=PalettesAreEqual(image,image->next); if (mng_info->equal_palettes && !mng_info->have_write_global_plte) { /* Write MNG PLTE chunk */ size_t data_length; data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red); chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green); chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk, (uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } } else mng_info->have_write_global_plte=MagickFalse; } #endif if (need_defi) { ssize_t previous_x, previous_y; if (scene) { previous_x=mng_info->page.x; previous_y=mng_info->page.y; } else { previous_x=0; previous_y=0; } mng_info->page=image->page; if ((mng_info->page.x != previous_x) || (mng_info->page.y != previous_y)) { (void) WriteBlobMSBULong(image,12L); /* data length=12 */ PNGType(chunk,mng_DEFI); LogPNGChunk(logging,mng_DEFI,12L); chunk[4]=0; /* object 0 MSB */ chunk[5]=0; /* object 0 LSB */ chunk[6]=0; /* visible */ chunk[7]=0; /* abstract */ PNGLong(chunk+8,(png_uint_32) mng_info->page.x); PNGLong(chunk+12,(png_uint_32) mng_info->page.y); (void) WriteBlob(image,16,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,16)); } } } mng_info->write_mng=write_mng; if ((int) image->dispose >= 3) mng_info->framing_mode=3; if (mng_info->need_fram && mng_info->adjoin && ((image->delay != mng_info->delay) || (mng_info->framing_mode != mng_info->old_framing_mode))) { if (image->delay == mng_info->delay) { /* Write a MNG FRAM chunk with the new framing mode. */ (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,1L); chunk[4]=(unsigned char) mng_info->framing_mode; (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { /* Write a MNG FRAM chunk with the delay. */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,10L); chunk[4]=(unsigned char) mng_info->framing_mode; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=2; /* flag for changing default delay */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=0; /* flag for changing frame clipping */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) ((mng_info->ticks_per_second* image->delay)/MagickMax(image->ticks_per_second,1))); (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); mng_info->delay=(png_uint_32) image->delay; } mng_info->old_framing_mode=mng_info->framing_mode; } #if defined(JNG_SUPPORTED) if (image_info->compression == JPEGCompression) { ImageInfo *write_info; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing JNG object."); /* To do: specify the desired alpha compression method. */ write_info=CloneImageInfo(image_info); write_info->compression=UndefinedCompression; status=WriteOneJNGImage(mng_info,write_info,image,exception); write_info=DestroyImageInfo(write_info); } else #endif { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG object."); mng_info->need_blob = MagickFalse; mng_info->ping_preserve_colormap = MagickFalse; /* We don't want any ancillary chunks written */ mng_info->ping_exclude_bKGD=MagickTrue; mng_info->ping_exclude_caNv=MagickTrue; mng_info->ping_exclude_cHRM=MagickTrue; mng_info->ping_exclude_date=MagickTrue; mng_info->ping_exclude_EXIF=MagickTrue; mng_info->ping_exclude_gAMA=MagickTrue; mng_info->ping_exclude_iCCP=MagickTrue; /* mng_info->ping_exclude_iTXt=MagickTrue; */ mng_info->ping_exclude_oFFs=MagickTrue; mng_info->ping_exclude_pHYs=MagickTrue; mng_info->ping_exclude_sRGB=MagickTrue; mng_info->ping_exclude_tEXt=MagickTrue; mng_info->ping_exclude_tRNS=MagickTrue; mng_info->ping_exclude_vpAg=MagickTrue; mng_info->ping_exclude_zCCP=MagickTrue; mng_info->ping_exclude_zTXt=MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image,exception); } if (status == MagickFalse) { mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); return(MagickFalse); } (void) CatchImageException(image); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (mng_info->adjoin); if (write_mng) { while (GetPreviousImageInList(image) != (Image *) NULL) image=GetPreviousImageInList(image); /* Write the MEND chunk. */ (void) WriteBlobMSBULong(image,0x00000000L); PNGType(chunk,mng_MEND); LogPNGChunk(logging,mng_MEND,0L); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); } /* Relinquish resources. */ (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()"); return(MagickTrue); } #else /* PNG_LIBPNG_VER > 10011 */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info, Image *image) { (void) image; printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); ThrowBinaryException(CoderError,"PNG library is too old", image_info->filename); } static MagickBooleanType WriteMNGImage(const ImageInfo *image_info, Image *image) { return(WritePNGImage(image_info,image)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2567_1
crossvul-cpp_data_good_2603_0
/* * Copyright (C) 2001 Jens Axboe <axboe@kernel.dk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public Licens * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111- * */ #include <linux/mm.h> #include <linux/swap.h> #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/uio.h> #include <linux/iocontext.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/export.h> #include <linux/mempool.h> #include <linux/workqueue.h> #include <linux/cgroup.h> #include <trace/events/block.h> #include "blk.h" /* * Test patch to inline a certain number of bi_io_vec's inside the bio * itself, to shrink a bio data allocation from two mempool calls to one */ #define BIO_INLINE_VECS 4 /* * if you change this list, also change bvec_alloc or things will * break badly! cannot be bigger than what you can fit into an * unsigned short */ #define BV(x) { .nr_vecs = x, .name = "biovec-"__stringify(x) } static struct biovec_slab bvec_slabs[BVEC_POOL_NR] __read_mostly = { BV(1), BV(4), BV(16), BV(64), BV(128), BV(BIO_MAX_PAGES), }; #undef BV /* * fs_bio_set is the bio_set containing bio and iovec memory pools used by * IO code that does not need private memory pools. */ struct bio_set *fs_bio_set; EXPORT_SYMBOL(fs_bio_set); /* * Our slab pool management */ struct bio_slab { struct kmem_cache *slab; unsigned int slab_ref; unsigned int slab_size; char name[8]; }; static DEFINE_MUTEX(bio_slab_lock); static struct bio_slab *bio_slabs; static unsigned int bio_slab_nr, bio_slab_max; static struct kmem_cache *bio_find_or_create_slab(unsigned int extra_size) { unsigned int sz = sizeof(struct bio) + extra_size; struct kmem_cache *slab = NULL; struct bio_slab *bslab, *new_bio_slabs; unsigned int new_bio_slab_max; unsigned int i, entry = -1; mutex_lock(&bio_slab_lock); i = 0; while (i < bio_slab_nr) { bslab = &bio_slabs[i]; if (!bslab->slab && entry == -1) entry = i; else if (bslab->slab_size == sz) { slab = bslab->slab; bslab->slab_ref++; break; } i++; } if (slab) goto out_unlock; if (bio_slab_nr == bio_slab_max && entry == -1) { new_bio_slab_max = bio_slab_max << 1; new_bio_slabs = krealloc(bio_slabs, new_bio_slab_max * sizeof(struct bio_slab), GFP_KERNEL); if (!new_bio_slabs) goto out_unlock; bio_slab_max = new_bio_slab_max; bio_slabs = new_bio_slabs; } if (entry == -1) entry = bio_slab_nr++; bslab = &bio_slabs[entry]; snprintf(bslab->name, sizeof(bslab->name), "bio-%d", entry); slab = kmem_cache_create(bslab->name, sz, ARCH_KMALLOC_MINALIGN, SLAB_HWCACHE_ALIGN, NULL); if (!slab) goto out_unlock; bslab->slab = slab; bslab->slab_ref = 1; bslab->slab_size = sz; out_unlock: mutex_unlock(&bio_slab_lock); return slab; } static void bio_put_slab(struct bio_set *bs) { struct bio_slab *bslab = NULL; unsigned int i; mutex_lock(&bio_slab_lock); for (i = 0; i < bio_slab_nr; i++) { if (bs->bio_slab == bio_slabs[i].slab) { bslab = &bio_slabs[i]; break; } } if (WARN(!bslab, KERN_ERR "bio: unable to find slab!\n")) goto out; WARN_ON(!bslab->slab_ref); if (--bslab->slab_ref) goto out; kmem_cache_destroy(bslab->slab); bslab->slab = NULL; out: mutex_unlock(&bio_slab_lock); } unsigned int bvec_nr_vecs(unsigned short idx) { return bvec_slabs[idx].nr_vecs; } void bvec_free(mempool_t *pool, struct bio_vec *bv, unsigned int idx) { if (!idx) return; idx--; BIO_BUG_ON(idx >= BVEC_POOL_NR); if (idx == BVEC_POOL_MAX) { mempool_free(bv, pool); } else { struct biovec_slab *bvs = bvec_slabs + idx; kmem_cache_free(bvs->slab, bv); } } struct bio_vec *bvec_alloc(gfp_t gfp_mask, int nr, unsigned long *idx, mempool_t *pool) { struct bio_vec *bvl; /* * see comment near bvec_array define! */ switch (nr) { case 1: *idx = 0; break; case 2 ... 4: *idx = 1; break; case 5 ... 16: *idx = 2; break; case 17 ... 64: *idx = 3; break; case 65 ... 128: *idx = 4; break; case 129 ... BIO_MAX_PAGES: *idx = 5; break; default: return NULL; } /* * idx now points to the pool we want to allocate from. only the * 1-vec entry pool is mempool backed. */ if (*idx == BVEC_POOL_MAX) { fallback: bvl = mempool_alloc(pool, gfp_mask); } else { struct biovec_slab *bvs = bvec_slabs + *idx; gfp_t __gfp_mask = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_IO); /* * Make this allocation restricted and don't dump info on * allocation failures, since we'll fallback to the mempool * in case of failure. */ __gfp_mask |= __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN; /* * Try a slab allocation. If this fails and __GFP_DIRECT_RECLAIM * is set, retry with the 1-entry mempool */ bvl = kmem_cache_alloc(bvs->slab, __gfp_mask); if (unlikely(!bvl && (gfp_mask & __GFP_DIRECT_RECLAIM))) { *idx = BVEC_POOL_MAX; goto fallback; } } (*idx)++; return bvl; } void bio_uninit(struct bio *bio) { bio_disassociate_task(bio); } EXPORT_SYMBOL(bio_uninit); static void bio_free(struct bio *bio) { struct bio_set *bs = bio->bi_pool; void *p; bio_uninit(bio); if (bs) { bvec_free(bs->bvec_pool, bio->bi_io_vec, BVEC_POOL_IDX(bio)); /* * If we have front padding, adjust the bio pointer before freeing */ p = bio; p -= bs->front_pad; mempool_free(p, bs->bio_pool); } else { /* Bio was allocated by bio_kmalloc() */ kfree(bio); } } /* * Users of this function have their own bio allocation. Subsequently, * they must remember to pair any call to bio_init() with bio_uninit() * when IO has completed, or when the bio is released. */ void bio_init(struct bio *bio, struct bio_vec *table, unsigned short max_vecs) { memset(bio, 0, sizeof(*bio)); atomic_set(&bio->__bi_remaining, 1); atomic_set(&bio->__bi_cnt, 1); bio->bi_io_vec = table; bio->bi_max_vecs = max_vecs; } EXPORT_SYMBOL(bio_init); /** * bio_reset - reinitialize a bio * @bio: bio to reset * * Description: * After calling bio_reset(), @bio will be in the same state as a freshly * allocated bio returned bio bio_alloc_bioset() - the only fields that are * preserved are the ones that are initialized by bio_alloc_bioset(). See * comment in struct bio. */ void bio_reset(struct bio *bio) { unsigned long flags = bio->bi_flags & (~0UL << BIO_RESET_BITS); bio_uninit(bio); memset(bio, 0, BIO_RESET_BYTES); bio->bi_flags = flags; atomic_set(&bio->__bi_remaining, 1); } EXPORT_SYMBOL(bio_reset); static struct bio *__bio_chain_endio(struct bio *bio) { struct bio *parent = bio->bi_private; if (!parent->bi_status) parent->bi_status = bio->bi_status; bio_put(bio); return parent; } static void bio_chain_endio(struct bio *bio) { bio_endio(__bio_chain_endio(bio)); } /** * bio_chain - chain bio completions * @bio: the target bio * @parent: the @bio's parent bio * * The caller won't have a bi_end_io called when @bio completes - instead, * @parent's bi_end_io won't be called until both @parent and @bio have * completed; the chained bio will also be freed when it completes. * * The caller must not set bi_private or bi_end_io in @bio. */ void bio_chain(struct bio *bio, struct bio *parent) { BUG_ON(bio->bi_private || bio->bi_end_io); bio->bi_private = parent; bio->bi_end_io = bio_chain_endio; bio_inc_remaining(parent); } EXPORT_SYMBOL(bio_chain); static void bio_alloc_rescue(struct work_struct *work) { struct bio_set *bs = container_of(work, struct bio_set, rescue_work); struct bio *bio; while (1) { spin_lock(&bs->rescue_lock); bio = bio_list_pop(&bs->rescue_list); spin_unlock(&bs->rescue_lock); if (!bio) break; generic_make_request(bio); } } static void punt_bios_to_rescuer(struct bio_set *bs) { struct bio_list punt, nopunt; struct bio *bio; if (WARN_ON_ONCE(!bs->rescue_workqueue)) return; /* * In order to guarantee forward progress we must punt only bios that * were allocated from this bio_set; otherwise, if there was a bio on * there for a stacking driver higher up in the stack, processing it * could require allocating bios from this bio_set, and doing that from * our own rescuer would be bad. * * Since bio lists are singly linked, pop them all instead of trying to * remove from the middle of the list: */ bio_list_init(&punt); bio_list_init(&nopunt); while ((bio = bio_list_pop(&current->bio_list[0]))) bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio); current->bio_list[0] = nopunt; bio_list_init(&nopunt); while ((bio = bio_list_pop(&current->bio_list[1]))) bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio); current->bio_list[1] = nopunt; spin_lock(&bs->rescue_lock); bio_list_merge(&bs->rescue_list, &punt); spin_unlock(&bs->rescue_lock); queue_work(bs->rescue_workqueue, &bs->rescue_work); } /** * bio_alloc_bioset - allocate a bio for I/O * @gfp_mask: the GFP_ mask given to the slab allocator * @nr_iovecs: number of iovecs to pre-allocate * @bs: the bio_set to allocate from. * * Description: * If @bs is NULL, uses kmalloc() to allocate the bio; else the allocation is * backed by the @bs's mempool. * * When @bs is not NULL, if %__GFP_DIRECT_RECLAIM is set then bio_alloc will * always be able to allocate a bio. This is due to the mempool guarantees. * To make this work, callers must never allocate more than 1 bio at a time * from this pool. Callers that need to allocate more than 1 bio must always * submit the previously allocated bio for IO before attempting to allocate * a new one. Failure to do so can cause deadlocks under memory pressure. * * Note that when running under generic_make_request() (i.e. any block * driver), bios are not submitted until after you return - see the code in * generic_make_request() that converts recursion into iteration, to prevent * stack overflows. * * This would normally mean allocating multiple bios under * generic_make_request() would be susceptible to deadlocks, but we have * deadlock avoidance code that resubmits any blocked bios from a rescuer * thread. * * However, we do not guarantee forward progress for allocations from other * mempools. Doing multiple allocations from the same mempool under * generic_make_request() should be avoided - instead, use bio_set's front_pad * for per bio allocations. * * RETURNS: * Pointer to new bio on success, NULL on failure. */ struct bio *bio_alloc_bioset(gfp_t gfp_mask, unsigned int nr_iovecs, struct bio_set *bs) { gfp_t saved_gfp = gfp_mask; unsigned front_pad; unsigned inline_vecs; struct bio_vec *bvl = NULL; struct bio *bio; void *p; if (!bs) { if (nr_iovecs > UIO_MAXIOV) return NULL; p = kmalloc(sizeof(struct bio) + nr_iovecs * sizeof(struct bio_vec), gfp_mask); front_pad = 0; inline_vecs = nr_iovecs; } else { /* should not use nobvec bioset for nr_iovecs > 0 */ if (WARN_ON_ONCE(!bs->bvec_pool && nr_iovecs > 0)) return NULL; /* * generic_make_request() converts recursion to iteration; this * means if we're running beneath it, any bios we allocate and * submit will not be submitted (and thus freed) until after we * return. * * This exposes us to a potential deadlock if we allocate * multiple bios from the same bio_set() while running * underneath generic_make_request(). If we were to allocate * multiple bios (say a stacking block driver that was splitting * bios), we would deadlock if we exhausted the mempool's * reserve. * * We solve this, and guarantee forward progress, with a rescuer * workqueue per bio_set. If we go to allocate and there are * bios on current->bio_list, we first try the allocation * without __GFP_DIRECT_RECLAIM; if that fails, we punt those * bios we would be blocking to the rescuer workqueue before * we retry with the original gfp_flags. */ if (current->bio_list && (!bio_list_empty(&current->bio_list[0]) || !bio_list_empty(&current->bio_list[1])) && bs->rescue_workqueue) gfp_mask &= ~__GFP_DIRECT_RECLAIM; p = mempool_alloc(bs->bio_pool, gfp_mask); if (!p && gfp_mask != saved_gfp) { punt_bios_to_rescuer(bs); gfp_mask = saved_gfp; p = mempool_alloc(bs->bio_pool, gfp_mask); } front_pad = bs->front_pad; inline_vecs = BIO_INLINE_VECS; } if (unlikely(!p)) return NULL; bio = p + front_pad; bio_init(bio, NULL, 0); if (nr_iovecs > inline_vecs) { unsigned long idx = 0; bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx, bs->bvec_pool); if (!bvl && gfp_mask != saved_gfp) { punt_bios_to_rescuer(bs); gfp_mask = saved_gfp; bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx, bs->bvec_pool); } if (unlikely(!bvl)) goto err_free; bio->bi_flags |= idx << BVEC_POOL_OFFSET; } else if (nr_iovecs) { bvl = bio->bi_inline_vecs; } bio->bi_pool = bs; bio->bi_max_vecs = nr_iovecs; bio->bi_io_vec = bvl; return bio; err_free: mempool_free(p, bs->bio_pool); return NULL; } EXPORT_SYMBOL(bio_alloc_bioset); void zero_fill_bio(struct bio *bio) { unsigned long flags; struct bio_vec bv; struct bvec_iter iter; bio_for_each_segment(bv, bio, iter) { char *data = bvec_kmap_irq(&bv, &flags); memset(data, 0, bv.bv_len); flush_dcache_page(bv.bv_page); bvec_kunmap_irq(data, &flags); } } EXPORT_SYMBOL(zero_fill_bio); /** * bio_put - release a reference to a bio * @bio: bio to release reference to * * Description: * Put a reference to a &struct bio, either one you have gotten with * bio_alloc, bio_get or bio_clone_*. The last put of a bio will free it. **/ void bio_put(struct bio *bio) { if (!bio_flagged(bio, BIO_REFFED)) bio_free(bio); else { BIO_BUG_ON(!atomic_read(&bio->__bi_cnt)); /* * last put frees it */ if (atomic_dec_and_test(&bio->__bi_cnt)) bio_free(bio); } } EXPORT_SYMBOL(bio_put); inline int bio_phys_segments(struct request_queue *q, struct bio *bio) { if (unlikely(!bio_flagged(bio, BIO_SEG_VALID))) blk_recount_segments(q, bio); return bio->bi_phys_segments; } EXPORT_SYMBOL(bio_phys_segments); /** * __bio_clone_fast - clone a bio that shares the original bio's biovec * @bio: destination bio * @bio_src: bio to clone * * Clone a &bio. Caller will own the returned bio, but not * the actual data it points to. Reference count of returned * bio will be one. * * Caller must ensure that @bio_src is not freed before @bio. */ void __bio_clone_fast(struct bio *bio, struct bio *bio_src) { BUG_ON(bio->bi_pool && BVEC_POOL_IDX(bio)); /* * most users will be overriding ->bi_disk with a new target, * so we don't set nor calculate new physical/hw segment counts here */ bio->bi_disk = bio_src->bi_disk; bio_set_flag(bio, BIO_CLONED); bio->bi_opf = bio_src->bi_opf; bio->bi_write_hint = bio_src->bi_write_hint; bio->bi_iter = bio_src->bi_iter; bio->bi_io_vec = bio_src->bi_io_vec; bio_clone_blkcg_association(bio, bio_src); } EXPORT_SYMBOL(__bio_clone_fast); /** * bio_clone_fast - clone a bio that shares the original bio's biovec * @bio: bio to clone * @gfp_mask: allocation priority * @bs: bio_set to allocate from * * Like __bio_clone_fast, only also allocates the returned bio */ struct bio *bio_clone_fast(struct bio *bio, gfp_t gfp_mask, struct bio_set *bs) { struct bio *b; b = bio_alloc_bioset(gfp_mask, 0, bs); if (!b) return NULL; __bio_clone_fast(b, bio); if (bio_integrity(bio)) { int ret; ret = bio_integrity_clone(b, bio, gfp_mask); if (ret < 0) { bio_put(b); return NULL; } } return b; } EXPORT_SYMBOL(bio_clone_fast); /** * bio_clone_bioset - clone a bio * @bio_src: bio to clone * @gfp_mask: allocation priority * @bs: bio_set to allocate from * * Clone bio. Caller will own the returned bio, but not the actual data it * points to. Reference count of returned bio will be one. */ struct bio *bio_clone_bioset(struct bio *bio_src, gfp_t gfp_mask, struct bio_set *bs) { struct bvec_iter iter; struct bio_vec bv; struct bio *bio; /* * Pre immutable biovecs, __bio_clone() used to just do a memcpy from * bio_src->bi_io_vec to bio->bi_io_vec. * * We can't do that anymore, because: * * - The point of cloning the biovec is to produce a bio with a biovec * the caller can modify: bi_idx and bi_bvec_done should be 0. * * - The original bio could've had more than BIO_MAX_PAGES biovecs; if * we tried to clone the whole thing bio_alloc_bioset() would fail. * But the clone should succeed as long as the number of biovecs we * actually need to allocate is fewer than BIO_MAX_PAGES. * * - Lastly, bi_vcnt should not be looked at or relied upon by code * that does not own the bio - reason being drivers don't use it for * iterating over the biovec anymore, so expecting it to be kept up * to date (i.e. for clones that share the parent biovec) is just * asking for trouble and would force extra work on * __bio_clone_fast() anyways. */ bio = bio_alloc_bioset(gfp_mask, bio_segments(bio_src), bs); if (!bio) return NULL; bio->bi_disk = bio_src->bi_disk; bio->bi_opf = bio_src->bi_opf; bio->bi_write_hint = bio_src->bi_write_hint; bio->bi_iter.bi_sector = bio_src->bi_iter.bi_sector; bio->bi_iter.bi_size = bio_src->bi_iter.bi_size; switch (bio_op(bio)) { case REQ_OP_DISCARD: case REQ_OP_SECURE_ERASE: case REQ_OP_WRITE_ZEROES: break; case REQ_OP_WRITE_SAME: bio->bi_io_vec[bio->bi_vcnt++] = bio_src->bi_io_vec[0]; break; default: bio_for_each_segment(bv, bio_src, iter) bio->bi_io_vec[bio->bi_vcnt++] = bv; break; } if (bio_integrity(bio_src)) { int ret; ret = bio_integrity_clone(bio, bio_src, gfp_mask); if (ret < 0) { bio_put(bio); return NULL; } } bio_clone_blkcg_association(bio, bio_src); return bio; } EXPORT_SYMBOL(bio_clone_bioset); /** * bio_add_pc_page - attempt to add page to bio * @q: the target queue * @bio: destination bio * @page: page to add * @len: vec entry length * @offset: vec entry offset * * Attempt to add a page to the bio_vec maplist. This can fail for a * number of reasons, such as the bio being full or target block device * limitations. The target block device must allow bio's up to PAGE_SIZE, * so it is always possible to add a single page to an empty bio. * * This should only be used by REQ_PC bios. */ int bio_add_pc_page(struct request_queue *q, struct bio *bio, struct page *page, unsigned int len, unsigned int offset) { int retried_segments = 0; struct bio_vec *bvec; /* * cloned bio must not modify vec list */ if (unlikely(bio_flagged(bio, BIO_CLONED))) return 0; if (((bio->bi_iter.bi_size + len) >> 9) > queue_max_hw_sectors(q)) return 0; /* * For filesystems with a blocksize smaller than the pagesize * we will often be called with the same page as last time and * a consecutive offset. Optimize this special case. */ if (bio->bi_vcnt > 0) { struct bio_vec *prev = &bio->bi_io_vec[bio->bi_vcnt - 1]; if (page == prev->bv_page && offset == prev->bv_offset + prev->bv_len) { prev->bv_len += len; bio->bi_iter.bi_size += len; goto done; } /* * If the queue doesn't support SG gaps and adding this * offset would create a gap, disallow it. */ if (bvec_gap_to_prev(q, prev, offset)) return 0; } if (bio->bi_vcnt >= bio->bi_max_vecs) return 0; /* * setup the new entry, we might clear it again later if we * cannot add the page */ bvec = &bio->bi_io_vec[bio->bi_vcnt]; bvec->bv_page = page; bvec->bv_len = len; bvec->bv_offset = offset; bio->bi_vcnt++; bio->bi_phys_segments++; bio->bi_iter.bi_size += len; /* * Perform a recount if the number of segments is greater * than queue_max_segments(q). */ while (bio->bi_phys_segments > queue_max_segments(q)) { if (retried_segments) goto failed; retried_segments = 1; blk_recount_segments(q, bio); } /* If we may be able to merge these biovecs, force a recount */ if (bio->bi_vcnt > 1 && (BIOVEC_PHYS_MERGEABLE(bvec-1, bvec))) bio_clear_flag(bio, BIO_SEG_VALID); done: return len; failed: bvec->bv_page = NULL; bvec->bv_len = 0; bvec->bv_offset = 0; bio->bi_vcnt--; bio->bi_iter.bi_size -= len; blk_recount_segments(q, bio); return 0; } EXPORT_SYMBOL(bio_add_pc_page); /** * bio_add_page - attempt to add page to bio * @bio: destination bio * @page: page to add * @len: vec entry length * @offset: vec entry offset * * Attempt to add a page to the bio_vec maplist. This will only fail * if either bio->bi_vcnt == bio->bi_max_vecs or it's a cloned bio. */ int bio_add_page(struct bio *bio, struct page *page, unsigned int len, unsigned int offset) { struct bio_vec *bv; /* * cloned bio must not modify vec list */ if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED))) return 0; /* * For filesystems with a blocksize smaller than the pagesize * we will often be called with the same page as last time and * a consecutive offset. Optimize this special case. */ if (bio->bi_vcnt > 0) { bv = &bio->bi_io_vec[bio->bi_vcnt - 1]; if (page == bv->bv_page && offset == bv->bv_offset + bv->bv_len) { bv->bv_len += len; goto done; } } if (bio->bi_vcnt >= bio->bi_max_vecs) return 0; bv = &bio->bi_io_vec[bio->bi_vcnt]; bv->bv_page = page; bv->bv_len = len; bv->bv_offset = offset; bio->bi_vcnt++; done: bio->bi_iter.bi_size += len; return len; } EXPORT_SYMBOL(bio_add_page); /** * bio_iov_iter_get_pages - pin user or kernel pages and add them to a bio * @bio: bio to add pages to * @iter: iov iterator describing the region to be mapped * * Pins as many pages from *iter and appends them to @bio's bvec array. The * pages will have to be released using put_page() when done. */ int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter) { unsigned short nr_pages = bio->bi_max_vecs - bio->bi_vcnt; struct bio_vec *bv = bio->bi_io_vec + bio->bi_vcnt; struct page **pages = (struct page **)bv; size_t offset, diff; ssize_t size; size = iov_iter_get_pages(iter, pages, LONG_MAX, nr_pages, &offset); if (unlikely(size <= 0)) return size ? size : -EFAULT; nr_pages = (size + offset + PAGE_SIZE - 1) / PAGE_SIZE; /* * Deep magic below: We need to walk the pinned pages backwards * because we are abusing the space allocated for the bio_vecs * for the page array. Because the bio_vecs are larger than the * page pointers by definition this will always work. But it also * means we can't use bio_add_page, so any changes to it's semantics * need to be reflected here as well. */ bio->bi_iter.bi_size += size; bio->bi_vcnt += nr_pages; diff = (nr_pages * PAGE_SIZE - offset) - size; while (nr_pages--) { bv[nr_pages].bv_page = pages[nr_pages]; bv[nr_pages].bv_len = PAGE_SIZE; bv[nr_pages].bv_offset = 0; } bv[0].bv_offset += offset; bv[0].bv_len -= offset; if (diff) bv[bio->bi_vcnt - 1].bv_len -= diff; iov_iter_advance(iter, size); return 0; } EXPORT_SYMBOL_GPL(bio_iov_iter_get_pages); struct submit_bio_ret { struct completion event; int error; }; static void submit_bio_wait_endio(struct bio *bio) { struct submit_bio_ret *ret = bio->bi_private; ret->error = blk_status_to_errno(bio->bi_status); complete(&ret->event); } /** * submit_bio_wait - submit a bio, and wait until it completes * @bio: The &struct bio which describes the I/O * * Simple wrapper around submit_bio(). Returns 0 on success, or the error from * bio_endio() on failure. * * WARNING: Unlike to how submit_bio() is usually used, this function does not * result in bio reference to be consumed. The caller must drop the reference * on his own. */ int submit_bio_wait(struct bio *bio) { struct submit_bio_ret ret; init_completion(&ret.event); bio->bi_private = &ret; bio->bi_end_io = submit_bio_wait_endio; bio->bi_opf |= REQ_SYNC; submit_bio(bio); wait_for_completion_io(&ret.event); return ret.error; } EXPORT_SYMBOL(submit_bio_wait); /** * bio_advance - increment/complete a bio by some number of bytes * @bio: bio to advance * @bytes: number of bytes to complete * * This updates bi_sector, bi_size and bi_idx; if the number of bytes to * complete doesn't align with a bvec boundary, then bv_len and bv_offset will * be updated on the last bvec as well. * * @bio will then represent the remaining, uncompleted portion of the io. */ void bio_advance(struct bio *bio, unsigned bytes) { if (bio_integrity(bio)) bio_integrity_advance(bio, bytes); bio_advance_iter(bio, &bio->bi_iter, bytes); } EXPORT_SYMBOL(bio_advance); /** * bio_alloc_pages - allocates a single page for each bvec in a bio * @bio: bio to allocate pages for * @gfp_mask: flags for allocation * * Allocates pages up to @bio->bi_vcnt. * * Returns 0 on success, -ENOMEM on failure. On failure, any allocated pages are * freed. */ int bio_alloc_pages(struct bio *bio, gfp_t gfp_mask) { int i; struct bio_vec *bv; bio_for_each_segment_all(bv, bio, i) { bv->bv_page = alloc_page(gfp_mask); if (!bv->bv_page) { while (--bv >= bio->bi_io_vec) __free_page(bv->bv_page); return -ENOMEM; } } return 0; } EXPORT_SYMBOL(bio_alloc_pages); /** * bio_copy_data - copy contents of data buffers from one chain of bios to * another * @src: source bio list * @dst: destination bio list * * If @src and @dst are single bios, bi_next must be NULL - otherwise, treats * @src and @dst as linked lists of bios. * * Stops when it reaches the end of either @src or @dst - that is, copies * min(src->bi_size, dst->bi_size) bytes (or the equivalent for lists of bios). */ void bio_copy_data(struct bio *dst, struct bio *src) { struct bvec_iter src_iter, dst_iter; struct bio_vec src_bv, dst_bv; void *src_p, *dst_p; unsigned bytes; src_iter = src->bi_iter; dst_iter = dst->bi_iter; while (1) { if (!src_iter.bi_size) { src = src->bi_next; if (!src) break; src_iter = src->bi_iter; } if (!dst_iter.bi_size) { dst = dst->bi_next; if (!dst) break; dst_iter = dst->bi_iter; } src_bv = bio_iter_iovec(src, src_iter); dst_bv = bio_iter_iovec(dst, dst_iter); bytes = min(src_bv.bv_len, dst_bv.bv_len); src_p = kmap_atomic(src_bv.bv_page); dst_p = kmap_atomic(dst_bv.bv_page); memcpy(dst_p + dst_bv.bv_offset, src_p + src_bv.bv_offset, bytes); kunmap_atomic(dst_p); kunmap_atomic(src_p); bio_advance_iter(src, &src_iter, bytes); bio_advance_iter(dst, &dst_iter, bytes); } } EXPORT_SYMBOL(bio_copy_data); struct bio_map_data { int is_our_pages; struct iov_iter iter; struct iovec iov[]; }; static struct bio_map_data *bio_alloc_map_data(unsigned int iov_count, gfp_t gfp_mask) { if (iov_count > UIO_MAXIOV) return NULL; return kmalloc(sizeof(struct bio_map_data) + sizeof(struct iovec) * iov_count, gfp_mask); } /** * bio_copy_from_iter - copy all pages from iov_iter to bio * @bio: The &struct bio which describes the I/O as destination * @iter: iov_iter as source * * Copy all pages from iov_iter to bio. * Returns 0 on success, or error on failure. */ static int bio_copy_from_iter(struct bio *bio, struct iov_iter iter) { int i; struct bio_vec *bvec; bio_for_each_segment_all(bvec, bio, i) { ssize_t ret; ret = copy_page_from_iter(bvec->bv_page, bvec->bv_offset, bvec->bv_len, &iter); if (!iov_iter_count(&iter)) break; if (ret < bvec->bv_len) return -EFAULT; } return 0; } /** * bio_copy_to_iter - copy all pages from bio to iov_iter * @bio: The &struct bio which describes the I/O as source * @iter: iov_iter as destination * * Copy all pages from bio to iov_iter. * Returns 0 on success, or error on failure. */ static int bio_copy_to_iter(struct bio *bio, struct iov_iter iter) { int i; struct bio_vec *bvec; bio_for_each_segment_all(bvec, bio, i) { ssize_t ret; ret = copy_page_to_iter(bvec->bv_page, bvec->bv_offset, bvec->bv_len, &iter); if (!iov_iter_count(&iter)) break; if (ret < bvec->bv_len) return -EFAULT; } return 0; } void bio_free_pages(struct bio *bio) { struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) __free_page(bvec->bv_page); } EXPORT_SYMBOL(bio_free_pages); /** * bio_uncopy_user - finish previously mapped bio * @bio: bio being terminated * * Free pages allocated from bio_copy_user_iov() and write back data * to user space in case of a read. */ int bio_uncopy_user(struct bio *bio) { struct bio_map_data *bmd = bio->bi_private; int ret = 0; if (!bio_flagged(bio, BIO_NULL_MAPPED)) { /* * if we're in a workqueue, the request is orphaned, so * don't copy into a random user address space, just free * and return -EINTR so user space doesn't expect any data. */ if (!current->mm) ret = -EINTR; else if (bio_data_dir(bio) == READ) ret = bio_copy_to_iter(bio, bmd->iter); if (bmd->is_our_pages) bio_free_pages(bio); } kfree(bmd); bio_put(bio); return ret; } /** * bio_copy_user_iov - copy user data to bio * @q: destination block queue * @map_data: pointer to the rq_map_data holding pages (if necessary) * @iter: iovec iterator * @gfp_mask: memory allocation flags * * Prepares and returns a bio for indirect user io, bouncing data * to/from kernel pages as necessary. Must be paired with * call bio_uncopy_user() on io completion. */ struct bio *bio_copy_user_iov(struct request_queue *q, struct rq_map_data *map_data, const struct iov_iter *iter, gfp_t gfp_mask) { struct bio_map_data *bmd; struct page *page; struct bio *bio; int i, ret; int nr_pages = 0; unsigned int len = iter->count; unsigned int offset = map_data ? offset_in_page(map_data->offset) : 0; for (i = 0; i < iter->nr_segs; i++) { unsigned long uaddr; unsigned long end; unsigned long start; uaddr = (unsigned long) iter->iov[i].iov_base; end = (uaddr + iter->iov[i].iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT; start = uaddr >> PAGE_SHIFT; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages += end - start; } if (offset) nr_pages++; bmd = bio_alloc_map_data(iter->nr_segs, gfp_mask); if (!bmd) return ERR_PTR(-ENOMEM); /* * We need to do a deep copy of the iov_iter including the iovecs. * The caller provided iov might point to an on-stack or otherwise * shortlived one. */ bmd->is_our_pages = map_data ? 0 : 1; memcpy(bmd->iov, iter->iov, sizeof(struct iovec) * iter->nr_segs); iov_iter_init(&bmd->iter, iter->type, bmd->iov, iter->nr_segs, iter->count); ret = -ENOMEM; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) goto out_bmd; ret = 0; if (map_data) { nr_pages = 1 << map_data->page_order; i = map_data->offset / PAGE_SIZE; } while (len) { unsigned int bytes = PAGE_SIZE; bytes -= offset; if (bytes > len) bytes = len; if (map_data) { if (i == map_data->nr_entries * nr_pages) { ret = -ENOMEM; break; } page = map_data->pages[i / nr_pages]; page += (i % nr_pages); i++; } else { page = alloc_page(q->bounce_gfp | gfp_mask); if (!page) { ret = -ENOMEM; break; } } if (bio_add_pc_page(q, bio, page, bytes, offset) < bytes) break; len -= bytes; offset = 0; } if (ret) goto cleanup; /* * success */ if (((iter->type & WRITE) && (!map_data || !map_data->null_mapped)) || (map_data && map_data->from_user)) { ret = bio_copy_from_iter(bio, *iter); if (ret) goto cleanup; } bio->bi_private = bmd; return bio; cleanup: if (!map_data) bio_free_pages(bio); bio_put(bio); out_bmd: kfree(bmd); return ERR_PTR(ret); } /** * bio_map_user_iov - map user iovec into bio * @q: the struct request_queue for the bio * @iter: iovec iterator * @gfp_mask: memory allocation flags * * Map the user space address into a bio suitable for io to a block * device. Returns an error pointer in case of error. */ struct bio *bio_map_user_iov(struct request_queue *q, const struct iov_iter *iter, gfp_t gfp_mask) { int j; int nr_pages = 0; struct page **pages; struct bio *bio; int cur_page = 0; int ret, offset; struct iov_iter i; struct iovec iov; struct bio_vec *bvec; iov_for_each(iov, i, *iter) { unsigned long uaddr = (unsigned long) iov.iov_base; unsigned long len = iov.iov_len; unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = uaddr >> PAGE_SHIFT; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages += end - start; /* * buffer must be aligned to at least logical block size for now */ if (uaddr & queue_dma_alignment(q)) return ERR_PTR(-EINVAL); } if (!nr_pages) return ERR_PTR(-EINVAL); bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); ret = -ENOMEM; pages = kcalloc(nr_pages, sizeof(struct page *), gfp_mask); if (!pages) goto out; iov_for_each(iov, i, *iter) { unsigned long uaddr = (unsigned long) iov.iov_base; unsigned long len = iov.iov_len; unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = uaddr >> PAGE_SHIFT; const int local_nr_pages = end - start; const int page_limit = cur_page + local_nr_pages; ret = get_user_pages_fast(uaddr, local_nr_pages, (iter->type & WRITE) != WRITE, &pages[cur_page]); if (unlikely(ret < local_nr_pages)) { for (j = cur_page; j < page_limit; j++) { if (!pages[j]) break; put_page(pages[j]); } ret = -EFAULT; goto out_unmap; } offset = offset_in_page(uaddr); for (j = cur_page; j < page_limit; j++) { unsigned int bytes = PAGE_SIZE - offset; unsigned short prev_bi_vcnt = bio->bi_vcnt; if (len <= 0) break; if (bytes > len) bytes = len; /* * sorry... */ if (bio_add_pc_page(q, bio, pages[j], bytes, offset) < bytes) break; /* * check if vector was merged with previous * drop page reference if needed */ if (bio->bi_vcnt == prev_bi_vcnt) put_page(pages[j]); len -= bytes; offset = 0; } cur_page = j; /* * release the pages we didn't map into the bio, if any */ while (j < page_limit) put_page(pages[j++]); } kfree(pages); bio_set_flag(bio, BIO_USER_MAPPED); /* * subtle -- if bio_map_user_iov() ended up bouncing a bio, * it would normally disappear when its bi_end_io is run. * however, we need it for the unmap, so grab an extra * reference to it */ bio_get(bio); return bio; out_unmap: bio_for_each_segment_all(bvec, bio, j) { put_page(bvec->bv_page); } out: kfree(pages); bio_put(bio); return ERR_PTR(ret); } static void __bio_unmap_user(struct bio *bio) { struct bio_vec *bvec; int i; /* * make sure we dirty pages we wrote to */ bio_for_each_segment_all(bvec, bio, i) { if (bio_data_dir(bio) == READ) set_page_dirty_lock(bvec->bv_page); put_page(bvec->bv_page); } bio_put(bio); } /** * bio_unmap_user - unmap a bio * @bio: the bio being unmapped * * Unmap a bio previously mapped by bio_map_user_iov(). Must be called from * process context. * * bio_unmap_user() may sleep. */ void bio_unmap_user(struct bio *bio) { __bio_unmap_user(bio); bio_put(bio); } static void bio_map_kern_endio(struct bio *bio) { bio_put(bio); } /** * bio_map_kern - map kernel address into bio * @q: the struct request_queue for the bio * @data: pointer to buffer to map * @len: length in bytes * @gfp_mask: allocation flags for bio allocation * * Map the kernel address into a bio suitable for io to a block * device. Returns an error pointer in case of error. */ struct bio *bio_map_kern(struct request_queue *q, void *data, unsigned int len, gfp_t gfp_mask) { unsigned long kaddr = (unsigned long)data; unsigned long end = (kaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = kaddr >> PAGE_SHIFT; const int nr_pages = end - start; int offset, i; struct bio *bio; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); offset = offset_in_page(kaddr); for (i = 0; i < nr_pages; i++) { unsigned int bytes = PAGE_SIZE - offset; if (len <= 0) break; if (bytes > len) bytes = len; if (bio_add_pc_page(q, bio, virt_to_page(data), bytes, offset) < bytes) { /* we don't support partial mappings */ bio_put(bio); return ERR_PTR(-EINVAL); } data += bytes; len -= bytes; offset = 0; } bio->bi_end_io = bio_map_kern_endio; return bio; } EXPORT_SYMBOL(bio_map_kern); static void bio_copy_kern_endio(struct bio *bio) { bio_free_pages(bio); bio_put(bio); } static void bio_copy_kern_endio_read(struct bio *bio) { char *p = bio->bi_private; struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) { memcpy(p, page_address(bvec->bv_page), bvec->bv_len); p += bvec->bv_len; } bio_copy_kern_endio(bio); } /** * bio_copy_kern - copy kernel address into bio * @q: the struct request_queue for the bio * @data: pointer to buffer to copy * @len: length in bytes * @gfp_mask: allocation flags for bio and page allocation * @reading: data direction is READ * * copy the kernel address into a bio suitable for io to a block * device. Returns an error pointer in case of error. */ struct bio *bio_copy_kern(struct request_queue *q, void *data, unsigned int len, gfp_t gfp_mask, int reading) { unsigned long kaddr = (unsigned long)data; unsigned long end = (kaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = kaddr >> PAGE_SHIFT; struct bio *bio; void *p = data; int nr_pages = 0; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages = end - start; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); while (len) { struct page *page; unsigned int bytes = PAGE_SIZE; if (bytes > len) bytes = len; page = alloc_page(q->bounce_gfp | gfp_mask); if (!page) goto cleanup; if (!reading) memcpy(page_address(page), p, bytes); if (bio_add_pc_page(q, bio, page, bytes, 0) < bytes) break; len -= bytes; p += bytes; } if (reading) { bio->bi_end_io = bio_copy_kern_endio_read; bio->bi_private = data; } else { bio->bi_end_io = bio_copy_kern_endio; } return bio; cleanup: bio_free_pages(bio); bio_put(bio); return ERR_PTR(-ENOMEM); } /* * bio_set_pages_dirty() and bio_check_pages_dirty() are support functions * for performing direct-IO in BIOs. * * The problem is that we cannot run set_page_dirty() from interrupt context * because the required locks are not interrupt-safe. So what we can do is to * mark the pages dirty _before_ performing IO. And in interrupt context, * check that the pages are still dirty. If so, fine. If not, redirty them * in process context. * * We special-case compound pages here: normally this means reads into hugetlb * pages. The logic in here doesn't really work right for compound pages * because the VM does not uniformly chase down the head page in all cases. * But dirtiness of compound pages is pretty meaningless anyway: the VM doesn't * handle them at all. So we skip compound pages here at an early stage. * * Note that this code is very hard to test under normal circumstances because * direct-io pins the pages with get_user_pages(). This makes * is_page_cache_freeable return false, and the VM will not clean the pages. * But other code (eg, flusher threads) could clean the pages if they are mapped * pagecache. * * Simply disabling the call to bio_set_pages_dirty() is a good way to test the * deferred bio dirtying paths. */ /* * bio_set_pages_dirty() will mark all the bio's pages as dirty. */ void bio_set_pages_dirty(struct bio *bio) { struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) { struct page *page = bvec->bv_page; if (page && !PageCompound(page)) set_page_dirty_lock(page); } } static void bio_release_pages(struct bio *bio) { struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) { struct page *page = bvec->bv_page; if (page) put_page(page); } } /* * bio_check_pages_dirty() will check that all the BIO's pages are still dirty. * If they are, then fine. If, however, some pages are clean then they must * have been written out during the direct-IO read. So we take another ref on * the BIO and the offending pages and re-dirty the pages in process context. * * It is expected that bio_check_pages_dirty() will wholly own the BIO from * here on. It will run one put_page() against each page and will run one * bio_put() against the BIO. */ static void bio_dirty_fn(struct work_struct *work); static DECLARE_WORK(bio_dirty_work, bio_dirty_fn); static DEFINE_SPINLOCK(bio_dirty_lock); static struct bio *bio_dirty_list; /* * This runs in process context */ static void bio_dirty_fn(struct work_struct *work) { unsigned long flags; struct bio *bio; spin_lock_irqsave(&bio_dirty_lock, flags); bio = bio_dirty_list; bio_dirty_list = NULL; spin_unlock_irqrestore(&bio_dirty_lock, flags); while (bio) { struct bio *next = bio->bi_private; bio_set_pages_dirty(bio); bio_release_pages(bio); bio_put(bio); bio = next; } } void bio_check_pages_dirty(struct bio *bio) { struct bio_vec *bvec; int nr_clean_pages = 0; int i; bio_for_each_segment_all(bvec, bio, i) { struct page *page = bvec->bv_page; if (PageDirty(page) || PageCompound(page)) { put_page(page); bvec->bv_page = NULL; } else { nr_clean_pages++; } } if (nr_clean_pages) { unsigned long flags; spin_lock_irqsave(&bio_dirty_lock, flags); bio->bi_private = bio_dirty_list; bio_dirty_list = bio; spin_unlock_irqrestore(&bio_dirty_lock, flags); schedule_work(&bio_dirty_work); } else { bio_put(bio); } } void generic_start_io_acct(struct request_queue *q, int rw, unsigned long sectors, struct hd_struct *part) { int cpu = part_stat_lock(); part_round_stats(q, cpu, part); part_stat_inc(cpu, part, ios[rw]); part_stat_add(cpu, part, sectors[rw], sectors); part_inc_in_flight(q, part, rw); part_stat_unlock(); } EXPORT_SYMBOL(generic_start_io_acct); void generic_end_io_acct(struct request_queue *q, int rw, struct hd_struct *part, unsigned long start_time) { unsigned long duration = jiffies - start_time; int cpu = part_stat_lock(); part_stat_add(cpu, part, ticks[rw], duration); part_round_stats(q, cpu, part); part_dec_in_flight(q, part, rw); part_stat_unlock(); } EXPORT_SYMBOL(generic_end_io_acct); #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE void bio_flush_dcache_pages(struct bio *bi) { struct bio_vec bvec; struct bvec_iter iter; bio_for_each_segment(bvec, bi, iter) flush_dcache_page(bvec.bv_page); } EXPORT_SYMBOL(bio_flush_dcache_pages); #endif static inline bool bio_remaining_done(struct bio *bio) { /* * If we're not chaining, then ->__bi_remaining is always 1 and * we always end io on the first invocation. */ if (!bio_flagged(bio, BIO_CHAIN)) return true; BUG_ON(atomic_read(&bio->__bi_remaining) <= 0); if (atomic_dec_and_test(&bio->__bi_remaining)) { bio_clear_flag(bio, BIO_CHAIN); return true; } return false; } /** * bio_endio - end I/O on a bio * @bio: bio * * Description: * bio_endio() will end I/O on the whole bio. bio_endio() is the preferred * way to end I/O on a bio. No one should call bi_end_io() directly on a * bio unless they own it and thus know that it has an end_io function. * * bio_endio() can be called several times on a bio that has been chained * using bio_chain(). The ->bi_end_io() function will only be called the * last time. At this point the BLK_TA_COMPLETE tracing event will be * generated if BIO_TRACE_COMPLETION is set. **/ void bio_endio(struct bio *bio) { again: if (!bio_remaining_done(bio)) return; if (!bio_integrity_endio(bio)) return; /* * Need to have a real endio function for chained bios, otherwise * various corner cases will break (like stacking block devices that * save/restore bi_end_io) - however, we want to avoid unbounded * recursion and blowing the stack. Tail call optimization would * handle this, but compiling with frame pointers also disables * gcc's sibling call optimization. */ if (bio->bi_end_io == bio_chain_endio) { bio = __bio_chain_endio(bio); goto again; } if (bio->bi_disk && bio_flagged(bio, BIO_TRACE_COMPLETION)) { trace_block_bio_complete(bio->bi_disk->queue, bio, blk_status_to_errno(bio->bi_status)); bio_clear_flag(bio, BIO_TRACE_COMPLETION); } blk_throtl_bio_endio(bio); /* release cgroup info */ bio_uninit(bio); if (bio->bi_end_io) bio->bi_end_io(bio); } EXPORT_SYMBOL(bio_endio); /** * bio_split - split a bio * @bio: bio to split * @sectors: number of sectors to split from the front of @bio * @gfp: gfp mask * @bs: bio set to allocate from * * Allocates and returns a new bio which represents @sectors from the start of * @bio, and updates @bio to represent the remaining sectors. * * Unless this is a discard request the newly allocated bio will point * to @bio's bi_io_vec; it is the caller's responsibility to ensure that * @bio is not freed before the split. */ struct bio *bio_split(struct bio *bio, int sectors, gfp_t gfp, struct bio_set *bs) { struct bio *split = NULL; BUG_ON(sectors <= 0); BUG_ON(sectors >= bio_sectors(bio)); split = bio_clone_fast(bio, gfp, bs); if (!split) return NULL; split->bi_iter.bi_size = sectors << 9; if (bio_integrity(split)) bio_integrity_trim(split); bio_advance(bio, split->bi_iter.bi_size); if (bio_flagged(bio, BIO_TRACE_COMPLETION)) bio_set_flag(bio, BIO_TRACE_COMPLETION); return split; } EXPORT_SYMBOL(bio_split); /** * bio_trim - trim a bio * @bio: bio to trim * @offset: number of sectors to trim from the front of @bio * @size: size we want to trim @bio to, in sectors */ void bio_trim(struct bio *bio, int offset, int size) { /* 'bio' is a cloned bio which we need to trim to match * the given offset and size. */ size <<= 9; if (offset == 0 && size == bio->bi_iter.bi_size) return; bio_clear_flag(bio, BIO_SEG_VALID); bio_advance(bio, offset << 9); bio->bi_iter.bi_size = size; if (bio_integrity(bio)) bio_integrity_trim(bio); } EXPORT_SYMBOL_GPL(bio_trim); /* * create memory pools for biovec's in a bio_set. * use the global biovec slabs created for general use. */ mempool_t *biovec_create_pool(int pool_entries) { struct biovec_slab *bp = bvec_slabs + BVEC_POOL_MAX; return mempool_create_slab_pool(pool_entries, bp->slab); } void bioset_free(struct bio_set *bs) { if (bs->rescue_workqueue) destroy_workqueue(bs->rescue_workqueue); if (bs->bio_pool) mempool_destroy(bs->bio_pool); if (bs->bvec_pool) mempool_destroy(bs->bvec_pool); bioset_integrity_free(bs); bio_put_slab(bs); kfree(bs); } EXPORT_SYMBOL(bioset_free); /** * bioset_create - Create a bio_set * @pool_size: Number of bio and bio_vecs to cache in the mempool * @front_pad: Number of bytes to allocate in front of the returned bio * @flags: Flags to modify behavior, currently %BIOSET_NEED_BVECS * and %BIOSET_NEED_RESCUER * * Description: * Set up a bio_set to be used with @bio_alloc_bioset. Allows the caller * to ask for a number of bytes to be allocated in front of the bio. * Front pad allocation is useful for embedding the bio inside * another structure, to avoid allocating extra data to go with the bio. * Note that the bio must be embedded at the END of that structure always, * or things will break badly. * If %BIOSET_NEED_BVECS is set in @flags, a separate pool will be allocated * for allocating iovecs. This pool is not needed e.g. for bio_clone_fast(). * If %BIOSET_NEED_RESCUER is set, a workqueue is created which can be used to * dispatch queued requests when the mempool runs out of space. * */ struct bio_set *bioset_create(unsigned int pool_size, unsigned int front_pad, int flags) { unsigned int back_pad = BIO_INLINE_VECS * sizeof(struct bio_vec); struct bio_set *bs; bs = kzalloc(sizeof(*bs), GFP_KERNEL); if (!bs) return NULL; bs->front_pad = front_pad; spin_lock_init(&bs->rescue_lock); bio_list_init(&bs->rescue_list); INIT_WORK(&bs->rescue_work, bio_alloc_rescue); bs->bio_slab = bio_find_or_create_slab(front_pad + back_pad); if (!bs->bio_slab) { kfree(bs); return NULL; } bs->bio_pool = mempool_create_slab_pool(pool_size, bs->bio_slab); if (!bs->bio_pool) goto bad; if (flags & BIOSET_NEED_BVECS) { bs->bvec_pool = biovec_create_pool(pool_size); if (!bs->bvec_pool) goto bad; } if (!(flags & BIOSET_NEED_RESCUER)) return bs; bs->rescue_workqueue = alloc_workqueue("bioset", WQ_MEM_RECLAIM, 0); if (!bs->rescue_workqueue) goto bad; return bs; bad: bioset_free(bs); return NULL; } EXPORT_SYMBOL(bioset_create); #ifdef CONFIG_BLK_CGROUP /** * bio_associate_blkcg - associate a bio with the specified blkcg * @bio: target bio * @blkcg_css: css of the blkcg to associate * * Associate @bio with the blkcg specified by @blkcg_css. Block layer will * treat @bio as if it were issued by a task which belongs to the blkcg. * * This function takes an extra reference of @blkcg_css which will be put * when @bio is released. The caller must own @bio and is responsible for * synchronizing calls to this function. */ int bio_associate_blkcg(struct bio *bio, struct cgroup_subsys_state *blkcg_css) { if (unlikely(bio->bi_css)) return -EBUSY; css_get(blkcg_css); bio->bi_css = blkcg_css; return 0; } EXPORT_SYMBOL_GPL(bio_associate_blkcg); /** * bio_associate_current - associate a bio with %current * @bio: target bio * * Associate @bio with %current if it hasn't been associated yet. Block * layer will treat @bio as if it were issued by %current no matter which * task actually issues it. * * This function takes an extra reference of @task's io_context and blkcg * which will be put when @bio is released. The caller must own @bio, * ensure %current->io_context exists, and is responsible for synchronizing * calls to this function. */ int bio_associate_current(struct bio *bio) { struct io_context *ioc; if (bio->bi_css) return -EBUSY; ioc = current->io_context; if (!ioc) return -ENOENT; get_io_context_active(ioc); bio->bi_ioc = ioc; bio->bi_css = task_get_css(current, io_cgrp_id); return 0; } EXPORT_SYMBOL_GPL(bio_associate_current); /** * bio_disassociate_task - undo bio_associate_current() * @bio: target bio */ void bio_disassociate_task(struct bio *bio) { if (bio->bi_ioc) { put_io_context(bio->bi_ioc); bio->bi_ioc = NULL; } if (bio->bi_css) { css_put(bio->bi_css); bio->bi_css = NULL; } } /** * bio_clone_blkcg_association - clone blkcg association from src to dst bio * @dst: destination bio * @src: source bio */ void bio_clone_blkcg_association(struct bio *dst, struct bio *src) { if (src->bi_css) WARN_ON(bio_associate_blkcg(dst, src->bi_css)); } EXPORT_SYMBOL_GPL(bio_clone_blkcg_association); #endif /* CONFIG_BLK_CGROUP */ static void __init biovec_init_slabs(void) { int i; for (i = 0; i < BVEC_POOL_NR; i++) { int size; struct biovec_slab *bvs = bvec_slabs + i; if (bvs->nr_vecs <= BIO_INLINE_VECS) { bvs->slab = NULL; continue; } size = bvs->nr_vecs * sizeof(struct bio_vec); bvs->slab = kmem_cache_create(bvs->name, size, 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); } } static int __init init_bio(void) { bio_slab_max = 2; bio_slab_nr = 0; bio_slabs = kzalloc(bio_slab_max * sizeof(struct bio_slab), GFP_KERNEL); if (!bio_slabs) panic("bio: can't allocate bios\n"); bio_integrity_init(); biovec_init_slabs(); fs_bio_set = bioset_create(BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS); if (!fs_bio_set) panic("bio: can't allocate bios\n"); if (bioset_integrity_create(fs_bio_set, BIO_POOL_SIZE)) panic("bio: can't create integrity pool\n"); return 0; } subsys_initcall(init_bio);
./CrossVul/dataset_final_sorted/CWE-772/c/good_2603_0
crossvul-cpp_data_good_2604_0
/* * Copyright (C) 2001 Jens Axboe <axboe@kernel.dk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public Licens * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111- * */ #include <linux/mm.h> #include <linux/swap.h> #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/uio.h> #include <linux/iocontext.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/export.h> #include <linux/mempool.h> #include <linux/workqueue.h> #include <linux/cgroup.h> #include <trace/events/block.h> #include "blk.h" /* * Test patch to inline a certain number of bi_io_vec's inside the bio * itself, to shrink a bio data allocation from two mempool calls to one */ #define BIO_INLINE_VECS 4 /* * if you change this list, also change bvec_alloc or things will * break badly! cannot be bigger than what you can fit into an * unsigned short */ #define BV(x) { .nr_vecs = x, .name = "biovec-"__stringify(x) } static struct biovec_slab bvec_slabs[BVEC_POOL_NR] __read_mostly = { BV(1), BV(4), BV(16), BV(64), BV(128), BV(BIO_MAX_PAGES), }; #undef BV /* * fs_bio_set is the bio_set containing bio and iovec memory pools used by * IO code that does not need private memory pools. */ struct bio_set *fs_bio_set; EXPORT_SYMBOL(fs_bio_set); /* * Our slab pool management */ struct bio_slab { struct kmem_cache *slab; unsigned int slab_ref; unsigned int slab_size; char name[8]; }; static DEFINE_MUTEX(bio_slab_lock); static struct bio_slab *bio_slabs; static unsigned int bio_slab_nr, bio_slab_max; static struct kmem_cache *bio_find_or_create_slab(unsigned int extra_size) { unsigned int sz = sizeof(struct bio) + extra_size; struct kmem_cache *slab = NULL; struct bio_slab *bslab, *new_bio_slabs; unsigned int new_bio_slab_max; unsigned int i, entry = -1; mutex_lock(&bio_slab_lock); i = 0; while (i < bio_slab_nr) { bslab = &bio_slabs[i]; if (!bslab->slab && entry == -1) entry = i; else if (bslab->slab_size == sz) { slab = bslab->slab; bslab->slab_ref++; break; } i++; } if (slab) goto out_unlock; if (bio_slab_nr == bio_slab_max && entry == -1) { new_bio_slab_max = bio_slab_max << 1; new_bio_slabs = krealloc(bio_slabs, new_bio_slab_max * sizeof(struct bio_slab), GFP_KERNEL); if (!new_bio_slabs) goto out_unlock; bio_slab_max = new_bio_slab_max; bio_slabs = new_bio_slabs; } if (entry == -1) entry = bio_slab_nr++; bslab = &bio_slabs[entry]; snprintf(bslab->name, sizeof(bslab->name), "bio-%d", entry); slab = kmem_cache_create(bslab->name, sz, ARCH_KMALLOC_MINALIGN, SLAB_HWCACHE_ALIGN, NULL); if (!slab) goto out_unlock; bslab->slab = slab; bslab->slab_ref = 1; bslab->slab_size = sz; out_unlock: mutex_unlock(&bio_slab_lock); return slab; } static void bio_put_slab(struct bio_set *bs) { struct bio_slab *bslab = NULL; unsigned int i; mutex_lock(&bio_slab_lock); for (i = 0; i < bio_slab_nr; i++) { if (bs->bio_slab == bio_slabs[i].slab) { bslab = &bio_slabs[i]; break; } } if (WARN(!bslab, KERN_ERR "bio: unable to find slab!\n")) goto out; WARN_ON(!bslab->slab_ref); if (--bslab->slab_ref) goto out; kmem_cache_destroy(bslab->slab); bslab->slab = NULL; out: mutex_unlock(&bio_slab_lock); } unsigned int bvec_nr_vecs(unsigned short idx) { return bvec_slabs[idx].nr_vecs; } void bvec_free(mempool_t *pool, struct bio_vec *bv, unsigned int idx) { if (!idx) return; idx--; BIO_BUG_ON(idx >= BVEC_POOL_NR); if (idx == BVEC_POOL_MAX) { mempool_free(bv, pool); } else { struct biovec_slab *bvs = bvec_slabs + idx; kmem_cache_free(bvs->slab, bv); } } struct bio_vec *bvec_alloc(gfp_t gfp_mask, int nr, unsigned long *idx, mempool_t *pool) { struct bio_vec *bvl; /* * see comment near bvec_array define! */ switch (nr) { case 1: *idx = 0; break; case 2 ... 4: *idx = 1; break; case 5 ... 16: *idx = 2; break; case 17 ... 64: *idx = 3; break; case 65 ... 128: *idx = 4; break; case 129 ... BIO_MAX_PAGES: *idx = 5; break; default: return NULL; } /* * idx now points to the pool we want to allocate from. only the * 1-vec entry pool is mempool backed. */ if (*idx == BVEC_POOL_MAX) { fallback: bvl = mempool_alloc(pool, gfp_mask); } else { struct biovec_slab *bvs = bvec_slabs + *idx; gfp_t __gfp_mask = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_IO); /* * Make this allocation restricted and don't dump info on * allocation failures, since we'll fallback to the mempool * in case of failure. */ __gfp_mask |= __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN; /* * Try a slab allocation. If this fails and __GFP_DIRECT_RECLAIM * is set, retry with the 1-entry mempool */ bvl = kmem_cache_alloc(bvs->slab, __gfp_mask); if (unlikely(!bvl && (gfp_mask & __GFP_DIRECT_RECLAIM))) { *idx = BVEC_POOL_MAX; goto fallback; } } (*idx)++; return bvl; } void bio_uninit(struct bio *bio) { bio_disassociate_task(bio); } EXPORT_SYMBOL(bio_uninit); static void bio_free(struct bio *bio) { struct bio_set *bs = bio->bi_pool; void *p; bio_uninit(bio); if (bs) { bvec_free(bs->bvec_pool, bio->bi_io_vec, BVEC_POOL_IDX(bio)); /* * If we have front padding, adjust the bio pointer before freeing */ p = bio; p -= bs->front_pad; mempool_free(p, bs->bio_pool); } else { /* Bio was allocated by bio_kmalloc() */ kfree(bio); } } /* * Users of this function have their own bio allocation. Subsequently, * they must remember to pair any call to bio_init() with bio_uninit() * when IO has completed, or when the bio is released. */ void bio_init(struct bio *bio, struct bio_vec *table, unsigned short max_vecs) { memset(bio, 0, sizeof(*bio)); atomic_set(&bio->__bi_remaining, 1); atomic_set(&bio->__bi_cnt, 1); bio->bi_io_vec = table; bio->bi_max_vecs = max_vecs; } EXPORT_SYMBOL(bio_init); /** * bio_reset - reinitialize a bio * @bio: bio to reset * * Description: * After calling bio_reset(), @bio will be in the same state as a freshly * allocated bio returned bio bio_alloc_bioset() - the only fields that are * preserved are the ones that are initialized by bio_alloc_bioset(). See * comment in struct bio. */ void bio_reset(struct bio *bio) { unsigned long flags = bio->bi_flags & (~0UL << BIO_RESET_BITS); bio_uninit(bio); memset(bio, 0, BIO_RESET_BYTES); bio->bi_flags = flags; atomic_set(&bio->__bi_remaining, 1); } EXPORT_SYMBOL(bio_reset); static struct bio *__bio_chain_endio(struct bio *bio) { struct bio *parent = bio->bi_private; if (!parent->bi_status) parent->bi_status = bio->bi_status; bio_put(bio); return parent; } static void bio_chain_endio(struct bio *bio) { bio_endio(__bio_chain_endio(bio)); } /** * bio_chain - chain bio completions * @bio: the target bio * @parent: the @bio's parent bio * * The caller won't have a bi_end_io called when @bio completes - instead, * @parent's bi_end_io won't be called until both @parent and @bio have * completed; the chained bio will also be freed when it completes. * * The caller must not set bi_private or bi_end_io in @bio. */ void bio_chain(struct bio *bio, struct bio *parent) { BUG_ON(bio->bi_private || bio->bi_end_io); bio->bi_private = parent; bio->bi_end_io = bio_chain_endio; bio_inc_remaining(parent); } EXPORT_SYMBOL(bio_chain); static void bio_alloc_rescue(struct work_struct *work) { struct bio_set *bs = container_of(work, struct bio_set, rescue_work); struct bio *bio; while (1) { spin_lock(&bs->rescue_lock); bio = bio_list_pop(&bs->rescue_list); spin_unlock(&bs->rescue_lock); if (!bio) break; generic_make_request(bio); } } static void punt_bios_to_rescuer(struct bio_set *bs) { struct bio_list punt, nopunt; struct bio *bio; if (WARN_ON_ONCE(!bs->rescue_workqueue)) return; /* * In order to guarantee forward progress we must punt only bios that * were allocated from this bio_set; otherwise, if there was a bio on * there for a stacking driver higher up in the stack, processing it * could require allocating bios from this bio_set, and doing that from * our own rescuer would be bad. * * Since bio lists are singly linked, pop them all instead of trying to * remove from the middle of the list: */ bio_list_init(&punt); bio_list_init(&nopunt); while ((bio = bio_list_pop(&current->bio_list[0]))) bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio); current->bio_list[0] = nopunt; bio_list_init(&nopunt); while ((bio = bio_list_pop(&current->bio_list[1]))) bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio); current->bio_list[1] = nopunt; spin_lock(&bs->rescue_lock); bio_list_merge(&bs->rescue_list, &punt); spin_unlock(&bs->rescue_lock); queue_work(bs->rescue_workqueue, &bs->rescue_work); } /** * bio_alloc_bioset - allocate a bio for I/O * @gfp_mask: the GFP_ mask given to the slab allocator * @nr_iovecs: number of iovecs to pre-allocate * @bs: the bio_set to allocate from. * * Description: * If @bs is NULL, uses kmalloc() to allocate the bio; else the allocation is * backed by the @bs's mempool. * * When @bs is not NULL, if %__GFP_DIRECT_RECLAIM is set then bio_alloc will * always be able to allocate a bio. This is due to the mempool guarantees. * To make this work, callers must never allocate more than 1 bio at a time * from this pool. Callers that need to allocate more than 1 bio must always * submit the previously allocated bio for IO before attempting to allocate * a new one. Failure to do so can cause deadlocks under memory pressure. * * Note that when running under generic_make_request() (i.e. any block * driver), bios are not submitted until after you return - see the code in * generic_make_request() that converts recursion into iteration, to prevent * stack overflows. * * This would normally mean allocating multiple bios under * generic_make_request() would be susceptible to deadlocks, but we have * deadlock avoidance code that resubmits any blocked bios from a rescuer * thread. * * However, we do not guarantee forward progress for allocations from other * mempools. Doing multiple allocations from the same mempool under * generic_make_request() should be avoided - instead, use bio_set's front_pad * for per bio allocations. * * RETURNS: * Pointer to new bio on success, NULL on failure. */ struct bio *bio_alloc_bioset(gfp_t gfp_mask, unsigned int nr_iovecs, struct bio_set *bs) { gfp_t saved_gfp = gfp_mask; unsigned front_pad; unsigned inline_vecs; struct bio_vec *bvl = NULL; struct bio *bio; void *p; if (!bs) { if (nr_iovecs > UIO_MAXIOV) return NULL; p = kmalloc(sizeof(struct bio) + nr_iovecs * sizeof(struct bio_vec), gfp_mask); front_pad = 0; inline_vecs = nr_iovecs; } else { /* should not use nobvec bioset for nr_iovecs > 0 */ if (WARN_ON_ONCE(!bs->bvec_pool && nr_iovecs > 0)) return NULL; /* * generic_make_request() converts recursion to iteration; this * means if we're running beneath it, any bios we allocate and * submit will not be submitted (and thus freed) until after we * return. * * This exposes us to a potential deadlock if we allocate * multiple bios from the same bio_set() while running * underneath generic_make_request(). If we were to allocate * multiple bios (say a stacking block driver that was splitting * bios), we would deadlock if we exhausted the mempool's * reserve. * * We solve this, and guarantee forward progress, with a rescuer * workqueue per bio_set. If we go to allocate and there are * bios on current->bio_list, we first try the allocation * without __GFP_DIRECT_RECLAIM; if that fails, we punt those * bios we would be blocking to the rescuer workqueue before * we retry with the original gfp_flags. */ if (current->bio_list && (!bio_list_empty(&current->bio_list[0]) || !bio_list_empty(&current->bio_list[1])) && bs->rescue_workqueue) gfp_mask &= ~__GFP_DIRECT_RECLAIM; p = mempool_alloc(bs->bio_pool, gfp_mask); if (!p && gfp_mask != saved_gfp) { punt_bios_to_rescuer(bs); gfp_mask = saved_gfp; p = mempool_alloc(bs->bio_pool, gfp_mask); } front_pad = bs->front_pad; inline_vecs = BIO_INLINE_VECS; } if (unlikely(!p)) return NULL; bio = p + front_pad; bio_init(bio, NULL, 0); if (nr_iovecs > inline_vecs) { unsigned long idx = 0; bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx, bs->bvec_pool); if (!bvl && gfp_mask != saved_gfp) { punt_bios_to_rescuer(bs); gfp_mask = saved_gfp; bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx, bs->bvec_pool); } if (unlikely(!bvl)) goto err_free; bio->bi_flags |= idx << BVEC_POOL_OFFSET; } else if (nr_iovecs) { bvl = bio->bi_inline_vecs; } bio->bi_pool = bs; bio->bi_max_vecs = nr_iovecs; bio->bi_io_vec = bvl; return bio; err_free: mempool_free(p, bs->bio_pool); return NULL; } EXPORT_SYMBOL(bio_alloc_bioset); void zero_fill_bio(struct bio *bio) { unsigned long flags; struct bio_vec bv; struct bvec_iter iter; bio_for_each_segment(bv, bio, iter) { char *data = bvec_kmap_irq(&bv, &flags); memset(data, 0, bv.bv_len); flush_dcache_page(bv.bv_page); bvec_kunmap_irq(data, &flags); } } EXPORT_SYMBOL(zero_fill_bio); /** * bio_put - release a reference to a bio * @bio: bio to release reference to * * Description: * Put a reference to a &struct bio, either one you have gotten with * bio_alloc, bio_get or bio_clone_*. The last put of a bio will free it. **/ void bio_put(struct bio *bio) { if (!bio_flagged(bio, BIO_REFFED)) bio_free(bio); else { BIO_BUG_ON(!atomic_read(&bio->__bi_cnt)); /* * last put frees it */ if (atomic_dec_and_test(&bio->__bi_cnt)) bio_free(bio); } } EXPORT_SYMBOL(bio_put); inline int bio_phys_segments(struct request_queue *q, struct bio *bio) { if (unlikely(!bio_flagged(bio, BIO_SEG_VALID))) blk_recount_segments(q, bio); return bio->bi_phys_segments; } EXPORT_SYMBOL(bio_phys_segments); /** * __bio_clone_fast - clone a bio that shares the original bio's biovec * @bio: destination bio * @bio_src: bio to clone * * Clone a &bio. Caller will own the returned bio, but not * the actual data it points to. Reference count of returned * bio will be one. * * Caller must ensure that @bio_src is not freed before @bio. */ void __bio_clone_fast(struct bio *bio, struct bio *bio_src) { BUG_ON(bio->bi_pool && BVEC_POOL_IDX(bio)); /* * most users will be overriding ->bi_disk with a new target, * so we don't set nor calculate new physical/hw segment counts here */ bio->bi_disk = bio_src->bi_disk; bio_set_flag(bio, BIO_CLONED); bio->bi_opf = bio_src->bi_opf; bio->bi_write_hint = bio_src->bi_write_hint; bio->bi_iter = bio_src->bi_iter; bio->bi_io_vec = bio_src->bi_io_vec; bio_clone_blkcg_association(bio, bio_src); } EXPORT_SYMBOL(__bio_clone_fast); /** * bio_clone_fast - clone a bio that shares the original bio's biovec * @bio: bio to clone * @gfp_mask: allocation priority * @bs: bio_set to allocate from * * Like __bio_clone_fast, only also allocates the returned bio */ struct bio *bio_clone_fast(struct bio *bio, gfp_t gfp_mask, struct bio_set *bs) { struct bio *b; b = bio_alloc_bioset(gfp_mask, 0, bs); if (!b) return NULL; __bio_clone_fast(b, bio); if (bio_integrity(bio)) { int ret; ret = bio_integrity_clone(b, bio, gfp_mask); if (ret < 0) { bio_put(b); return NULL; } } return b; } EXPORT_SYMBOL(bio_clone_fast); /** * bio_clone_bioset - clone a bio * @bio_src: bio to clone * @gfp_mask: allocation priority * @bs: bio_set to allocate from * * Clone bio. Caller will own the returned bio, but not the actual data it * points to. Reference count of returned bio will be one. */ struct bio *bio_clone_bioset(struct bio *bio_src, gfp_t gfp_mask, struct bio_set *bs) { struct bvec_iter iter; struct bio_vec bv; struct bio *bio; /* * Pre immutable biovecs, __bio_clone() used to just do a memcpy from * bio_src->bi_io_vec to bio->bi_io_vec. * * We can't do that anymore, because: * * - The point of cloning the biovec is to produce a bio with a biovec * the caller can modify: bi_idx and bi_bvec_done should be 0. * * - The original bio could've had more than BIO_MAX_PAGES biovecs; if * we tried to clone the whole thing bio_alloc_bioset() would fail. * But the clone should succeed as long as the number of biovecs we * actually need to allocate is fewer than BIO_MAX_PAGES. * * - Lastly, bi_vcnt should not be looked at or relied upon by code * that does not own the bio - reason being drivers don't use it for * iterating over the biovec anymore, so expecting it to be kept up * to date (i.e. for clones that share the parent biovec) is just * asking for trouble and would force extra work on * __bio_clone_fast() anyways. */ bio = bio_alloc_bioset(gfp_mask, bio_segments(bio_src), bs); if (!bio) return NULL; bio->bi_disk = bio_src->bi_disk; bio->bi_opf = bio_src->bi_opf; bio->bi_write_hint = bio_src->bi_write_hint; bio->bi_iter.bi_sector = bio_src->bi_iter.bi_sector; bio->bi_iter.bi_size = bio_src->bi_iter.bi_size; switch (bio_op(bio)) { case REQ_OP_DISCARD: case REQ_OP_SECURE_ERASE: case REQ_OP_WRITE_ZEROES: break; case REQ_OP_WRITE_SAME: bio->bi_io_vec[bio->bi_vcnt++] = bio_src->bi_io_vec[0]; break; default: bio_for_each_segment(bv, bio_src, iter) bio->bi_io_vec[bio->bi_vcnt++] = bv; break; } if (bio_integrity(bio_src)) { int ret; ret = bio_integrity_clone(bio, bio_src, gfp_mask); if (ret < 0) { bio_put(bio); return NULL; } } bio_clone_blkcg_association(bio, bio_src); return bio; } EXPORT_SYMBOL(bio_clone_bioset); /** * bio_add_pc_page - attempt to add page to bio * @q: the target queue * @bio: destination bio * @page: page to add * @len: vec entry length * @offset: vec entry offset * * Attempt to add a page to the bio_vec maplist. This can fail for a * number of reasons, such as the bio being full or target block device * limitations. The target block device must allow bio's up to PAGE_SIZE, * so it is always possible to add a single page to an empty bio. * * This should only be used by REQ_PC bios. */ int bio_add_pc_page(struct request_queue *q, struct bio *bio, struct page *page, unsigned int len, unsigned int offset) { int retried_segments = 0; struct bio_vec *bvec; /* * cloned bio must not modify vec list */ if (unlikely(bio_flagged(bio, BIO_CLONED))) return 0; if (((bio->bi_iter.bi_size + len) >> 9) > queue_max_hw_sectors(q)) return 0; /* * For filesystems with a blocksize smaller than the pagesize * we will often be called with the same page as last time and * a consecutive offset. Optimize this special case. */ if (bio->bi_vcnt > 0) { struct bio_vec *prev = &bio->bi_io_vec[bio->bi_vcnt - 1]; if (page == prev->bv_page && offset == prev->bv_offset + prev->bv_len) { prev->bv_len += len; bio->bi_iter.bi_size += len; goto done; } /* * If the queue doesn't support SG gaps and adding this * offset would create a gap, disallow it. */ if (bvec_gap_to_prev(q, prev, offset)) return 0; } if (bio->bi_vcnt >= bio->bi_max_vecs) return 0; /* * setup the new entry, we might clear it again later if we * cannot add the page */ bvec = &bio->bi_io_vec[bio->bi_vcnt]; bvec->bv_page = page; bvec->bv_len = len; bvec->bv_offset = offset; bio->bi_vcnt++; bio->bi_phys_segments++; bio->bi_iter.bi_size += len; /* * Perform a recount if the number of segments is greater * than queue_max_segments(q). */ while (bio->bi_phys_segments > queue_max_segments(q)) { if (retried_segments) goto failed; retried_segments = 1; blk_recount_segments(q, bio); } /* If we may be able to merge these biovecs, force a recount */ if (bio->bi_vcnt > 1 && (BIOVEC_PHYS_MERGEABLE(bvec-1, bvec))) bio_clear_flag(bio, BIO_SEG_VALID); done: return len; failed: bvec->bv_page = NULL; bvec->bv_len = 0; bvec->bv_offset = 0; bio->bi_vcnt--; bio->bi_iter.bi_size -= len; blk_recount_segments(q, bio); return 0; } EXPORT_SYMBOL(bio_add_pc_page); /** * bio_add_page - attempt to add page to bio * @bio: destination bio * @page: page to add * @len: vec entry length * @offset: vec entry offset * * Attempt to add a page to the bio_vec maplist. This will only fail * if either bio->bi_vcnt == bio->bi_max_vecs or it's a cloned bio. */ int bio_add_page(struct bio *bio, struct page *page, unsigned int len, unsigned int offset) { struct bio_vec *bv; /* * cloned bio must not modify vec list */ if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED))) return 0; /* * For filesystems with a blocksize smaller than the pagesize * we will often be called with the same page as last time and * a consecutive offset. Optimize this special case. */ if (bio->bi_vcnt > 0) { bv = &bio->bi_io_vec[bio->bi_vcnt - 1]; if (page == bv->bv_page && offset == bv->bv_offset + bv->bv_len) { bv->bv_len += len; goto done; } } if (bio->bi_vcnt >= bio->bi_max_vecs) return 0; bv = &bio->bi_io_vec[bio->bi_vcnt]; bv->bv_page = page; bv->bv_len = len; bv->bv_offset = offset; bio->bi_vcnt++; done: bio->bi_iter.bi_size += len; return len; } EXPORT_SYMBOL(bio_add_page); /** * bio_iov_iter_get_pages - pin user or kernel pages and add them to a bio * @bio: bio to add pages to * @iter: iov iterator describing the region to be mapped * * Pins as many pages from *iter and appends them to @bio's bvec array. The * pages will have to be released using put_page() when done. */ int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter) { unsigned short nr_pages = bio->bi_max_vecs - bio->bi_vcnt; struct bio_vec *bv = bio->bi_io_vec + bio->bi_vcnt; struct page **pages = (struct page **)bv; size_t offset, diff; ssize_t size; size = iov_iter_get_pages(iter, pages, LONG_MAX, nr_pages, &offset); if (unlikely(size <= 0)) return size ? size : -EFAULT; nr_pages = (size + offset + PAGE_SIZE - 1) / PAGE_SIZE; /* * Deep magic below: We need to walk the pinned pages backwards * because we are abusing the space allocated for the bio_vecs * for the page array. Because the bio_vecs are larger than the * page pointers by definition this will always work. But it also * means we can't use bio_add_page, so any changes to it's semantics * need to be reflected here as well. */ bio->bi_iter.bi_size += size; bio->bi_vcnt += nr_pages; diff = (nr_pages * PAGE_SIZE - offset) - size; while (nr_pages--) { bv[nr_pages].bv_page = pages[nr_pages]; bv[nr_pages].bv_len = PAGE_SIZE; bv[nr_pages].bv_offset = 0; } bv[0].bv_offset += offset; bv[0].bv_len -= offset; if (diff) bv[bio->bi_vcnt - 1].bv_len -= diff; iov_iter_advance(iter, size); return 0; } EXPORT_SYMBOL_GPL(bio_iov_iter_get_pages); struct submit_bio_ret { struct completion event; int error; }; static void submit_bio_wait_endio(struct bio *bio) { struct submit_bio_ret *ret = bio->bi_private; ret->error = blk_status_to_errno(bio->bi_status); complete(&ret->event); } /** * submit_bio_wait - submit a bio, and wait until it completes * @bio: The &struct bio which describes the I/O * * Simple wrapper around submit_bio(). Returns 0 on success, or the error from * bio_endio() on failure. * * WARNING: Unlike to how submit_bio() is usually used, this function does not * result in bio reference to be consumed. The caller must drop the reference * on his own. */ int submit_bio_wait(struct bio *bio) { struct submit_bio_ret ret; init_completion(&ret.event); bio->bi_private = &ret; bio->bi_end_io = submit_bio_wait_endio; bio->bi_opf |= REQ_SYNC; submit_bio(bio); wait_for_completion_io(&ret.event); return ret.error; } EXPORT_SYMBOL(submit_bio_wait); /** * bio_advance - increment/complete a bio by some number of bytes * @bio: bio to advance * @bytes: number of bytes to complete * * This updates bi_sector, bi_size and bi_idx; if the number of bytes to * complete doesn't align with a bvec boundary, then bv_len and bv_offset will * be updated on the last bvec as well. * * @bio will then represent the remaining, uncompleted portion of the io. */ void bio_advance(struct bio *bio, unsigned bytes) { if (bio_integrity(bio)) bio_integrity_advance(bio, bytes); bio_advance_iter(bio, &bio->bi_iter, bytes); } EXPORT_SYMBOL(bio_advance); /** * bio_alloc_pages - allocates a single page for each bvec in a bio * @bio: bio to allocate pages for * @gfp_mask: flags for allocation * * Allocates pages up to @bio->bi_vcnt. * * Returns 0 on success, -ENOMEM on failure. On failure, any allocated pages are * freed. */ int bio_alloc_pages(struct bio *bio, gfp_t gfp_mask) { int i; struct bio_vec *bv; bio_for_each_segment_all(bv, bio, i) { bv->bv_page = alloc_page(gfp_mask); if (!bv->bv_page) { while (--bv >= bio->bi_io_vec) __free_page(bv->bv_page); return -ENOMEM; } } return 0; } EXPORT_SYMBOL(bio_alloc_pages); /** * bio_copy_data - copy contents of data buffers from one chain of bios to * another * @src: source bio list * @dst: destination bio list * * If @src and @dst are single bios, bi_next must be NULL - otherwise, treats * @src and @dst as linked lists of bios. * * Stops when it reaches the end of either @src or @dst - that is, copies * min(src->bi_size, dst->bi_size) bytes (or the equivalent for lists of bios). */ void bio_copy_data(struct bio *dst, struct bio *src) { struct bvec_iter src_iter, dst_iter; struct bio_vec src_bv, dst_bv; void *src_p, *dst_p; unsigned bytes; src_iter = src->bi_iter; dst_iter = dst->bi_iter; while (1) { if (!src_iter.bi_size) { src = src->bi_next; if (!src) break; src_iter = src->bi_iter; } if (!dst_iter.bi_size) { dst = dst->bi_next; if (!dst) break; dst_iter = dst->bi_iter; } src_bv = bio_iter_iovec(src, src_iter); dst_bv = bio_iter_iovec(dst, dst_iter); bytes = min(src_bv.bv_len, dst_bv.bv_len); src_p = kmap_atomic(src_bv.bv_page); dst_p = kmap_atomic(dst_bv.bv_page); memcpy(dst_p + dst_bv.bv_offset, src_p + src_bv.bv_offset, bytes); kunmap_atomic(dst_p); kunmap_atomic(src_p); bio_advance_iter(src, &src_iter, bytes); bio_advance_iter(dst, &dst_iter, bytes); } } EXPORT_SYMBOL(bio_copy_data); struct bio_map_data { int is_our_pages; struct iov_iter iter; struct iovec iov[]; }; static struct bio_map_data *bio_alloc_map_data(unsigned int iov_count, gfp_t gfp_mask) { if (iov_count > UIO_MAXIOV) return NULL; return kmalloc(sizeof(struct bio_map_data) + sizeof(struct iovec) * iov_count, gfp_mask); } /** * bio_copy_from_iter - copy all pages from iov_iter to bio * @bio: The &struct bio which describes the I/O as destination * @iter: iov_iter as source * * Copy all pages from iov_iter to bio. * Returns 0 on success, or error on failure. */ static int bio_copy_from_iter(struct bio *bio, struct iov_iter iter) { int i; struct bio_vec *bvec; bio_for_each_segment_all(bvec, bio, i) { ssize_t ret; ret = copy_page_from_iter(bvec->bv_page, bvec->bv_offset, bvec->bv_len, &iter); if (!iov_iter_count(&iter)) break; if (ret < bvec->bv_len) return -EFAULT; } return 0; } /** * bio_copy_to_iter - copy all pages from bio to iov_iter * @bio: The &struct bio which describes the I/O as source * @iter: iov_iter as destination * * Copy all pages from bio to iov_iter. * Returns 0 on success, or error on failure. */ static int bio_copy_to_iter(struct bio *bio, struct iov_iter iter) { int i; struct bio_vec *bvec; bio_for_each_segment_all(bvec, bio, i) { ssize_t ret; ret = copy_page_to_iter(bvec->bv_page, bvec->bv_offset, bvec->bv_len, &iter); if (!iov_iter_count(&iter)) break; if (ret < bvec->bv_len) return -EFAULT; } return 0; } void bio_free_pages(struct bio *bio) { struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) __free_page(bvec->bv_page); } EXPORT_SYMBOL(bio_free_pages); /** * bio_uncopy_user - finish previously mapped bio * @bio: bio being terminated * * Free pages allocated from bio_copy_user_iov() and write back data * to user space in case of a read. */ int bio_uncopy_user(struct bio *bio) { struct bio_map_data *bmd = bio->bi_private; int ret = 0; if (!bio_flagged(bio, BIO_NULL_MAPPED)) { /* * if we're in a workqueue, the request is orphaned, so * don't copy into a random user address space, just free * and return -EINTR so user space doesn't expect any data. */ if (!current->mm) ret = -EINTR; else if (bio_data_dir(bio) == READ) ret = bio_copy_to_iter(bio, bmd->iter); if (bmd->is_our_pages) bio_free_pages(bio); } kfree(bmd); bio_put(bio); return ret; } /** * bio_copy_user_iov - copy user data to bio * @q: destination block queue * @map_data: pointer to the rq_map_data holding pages (if necessary) * @iter: iovec iterator * @gfp_mask: memory allocation flags * * Prepares and returns a bio for indirect user io, bouncing data * to/from kernel pages as necessary. Must be paired with * call bio_uncopy_user() on io completion. */ struct bio *bio_copy_user_iov(struct request_queue *q, struct rq_map_data *map_data, const struct iov_iter *iter, gfp_t gfp_mask) { struct bio_map_data *bmd; struct page *page; struct bio *bio; int i, ret; int nr_pages = 0; unsigned int len = iter->count; unsigned int offset = map_data ? offset_in_page(map_data->offset) : 0; for (i = 0; i < iter->nr_segs; i++) { unsigned long uaddr; unsigned long end; unsigned long start; uaddr = (unsigned long) iter->iov[i].iov_base; end = (uaddr + iter->iov[i].iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT; start = uaddr >> PAGE_SHIFT; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages += end - start; } if (offset) nr_pages++; bmd = bio_alloc_map_data(iter->nr_segs, gfp_mask); if (!bmd) return ERR_PTR(-ENOMEM); /* * We need to do a deep copy of the iov_iter including the iovecs. * The caller provided iov might point to an on-stack or otherwise * shortlived one. */ bmd->is_our_pages = map_data ? 0 : 1; memcpy(bmd->iov, iter->iov, sizeof(struct iovec) * iter->nr_segs); iov_iter_init(&bmd->iter, iter->type, bmd->iov, iter->nr_segs, iter->count); ret = -ENOMEM; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) goto out_bmd; ret = 0; if (map_data) { nr_pages = 1 << map_data->page_order; i = map_data->offset / PAGE_SIZE; } while (len) { unsigned int bytes = PAGE_SIZE; bytes -= offset; if (bytes > len) bytes = len; if (map_data) { if (i == map_data->nr_entries * nr_pages) { ret = -ENOMEM; break; } page = map_data->pages[i / nr_pages]; page += (i % nr_pages); i++; } else { page = alloc_page(q->bounce_gfp | gfp_mask); if (!page) { ret = -ENOMEM; break; } } if (bio_add_pc_page(q, bio, page, bytes, offset) < bytes) break; len -= bytes; offset = 0; } if (ret) goto cleanup; /* * success */ if (((iter->type & WRITE) && (!map_data || !map_data->null_mapped)) || (map_data && map_data->from_user)) { ret = bio_copy_from_iter(bio, *iter); if (ret) goto cleanup; } bio->bi_private = bmd; return bio; cleanup: if (!map_data) bio_free_pages(bio); bio_put(bio); out_bmd: kfree(bmd); return ERR_PTR(ret); } /** * bio_map_user_iov - map user iovec into bio * @q: the struct request_queue for the bio * @iter: iovec iterator * @gfp_mask: memory allocation flags * * Map the user space address into a bio suitable for io to a block * device. Returns an error pointer in case of error. */ struct bio *bio_map_user_iov(struct request_queue *q, const struct iov_iter *iter, gfp_t gfp_mask) { int j; int nr_pages = 0; struct page **pages; struct bio *bio; int cur_page = 0; int ret, offset; struct iov_iter i; struct iovec iov; iov_for_each(iov, i, *iter) { unsigned long uaddr = (unsigned long) iov.iov_base; unsigned long len = iov.iov_len; unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = uaddr >> PAGE_SHIFT; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages += end - start; /* * buffer must be aligned to at least logical block size for now */ if (uaddr & queue_dma_alignment(q)) return ERR_PTR(-EINVAL); } if (!nr_pages) return ERR_PTR(-EINVAL); bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); ret = -ENOMEM; pages = kcalloc(nr_pages, sizeof(struct page *), gfp_mask); if (!pages) goto out; iov_for_each(iov, i, *iter) { unsigned long uaddr = (unsigned long) iov.iov_base; unsigned long len = iov.iov_len; unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = uaddr >> PAGE_SHIFT; const int local_nr_pages = end - start; const int page_limit = cur_page + local_nr_pages; ret = get_user_pages_fast(uaddr, local_nr_pages, (iter->type & WRITE) != WRITE, &pages[cur_page]); if (ret < local_nr_pages) { ret = -EFAULT; goto out_unmap; } offset = offset_in_page(uaddr); for (j = cur_page; j < page_limit; j++) { unsigned int bytes = PAGE_SIZE - offset; unsigned short prev_bi_vcnt = bio->bi_vcnt; if (len <= 0) break; if (bytes > len) bytes = len; /* * sorry... */ if (bio_add_pc_page(q, bio, pages[j], bytes, offset) < bytes) break; /* * check if vector was merged with previous * drop page reference if needed */ if (bio->bi_vcnt == prev_bi_vcnt) put_page(pages[j]); len -= bytes; offset = 0; } cur_page = j; /* * release the pages we didn't map into the bio, if any */ while (j < page_limit) put_page(pages[j++]); } kfree(pages); bio_set_flag(bio, BIO_USER_MAPPED); /* * subtle -- if bio_map_user_iov() ended up bouncing a bio, * it would normally disappear when its bi_end_io is run. * however, we need it for the unmap, so grab an extra * reference to it */ bio_get(bio); return bio; out_unmap: for (j = 0; j < nr_pages; j++) { if (!pages[j]) break; put_page(pages[j]); } out: kfree(pages); bio_put(bio); return ERR_PTR(ret); } static void __bio_unmap_user(struct bio *bio) { struct bio_vec *bvec; int i; /* * make sure we dirty pages we wrote to */ bio_for_each_segment_all(bvec, bio, i) { if (bio_data_dir(bio) == READ) set_page_dirty_lock(bvec->bv_page); put_page(bvec->bv_page); } bio_put(bio); } /** * bio_unmap_user - unmap a bio * @bio: the bio being unmapped * * Unmap a bio previously mapped by bio_map_user_iov(). Must be called from * process context. * * bio_unmap_user() may sleep. */ void bio_unmap_user(struct bio *bio) { __bio_unmap_user(bio); bio_put(bio); } static void bio_map_kern_endio(struct bio *bio) { bio_put(bio); } /** * bio_map_kern - map kernel address into bio * @q: the struct request_queue for the bio * @data: pointer to buffer to map * @len: length in bytes * @gfp_mask: allocation flags for bio allocation * * Map the kernel address into a bio suitable for io to a block * device. Returns an error pointer in case of error. */ struct bio *bio_map_kern(struct request_queue *q, void *data, unsigned int len, gfp_t gfp_mask) { unsigned long kaddr = (unsigned long)data; unsigned long end = (kaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = kaddr >> PAGE_SHIFT; const int nr_pages = end - start; int offset, i; struct bio *bio; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); offset = offset_in_page(kaddr); for (i = 0; i < nr_pages; i++) { unsigned int bytes = PAGE_SIZE - offset; if (len <= 0) break; if (bytes > len) bytes = len; if (bio_add_pc_page(q, bio, virt_to_page(data), bytes, offset) < bytes) { /* we don't support partial mappings */ bio_put(bio); return ERR_PTR(-EINVAL); } data += bytes; len -= bytes; offset = 0; } bio->bi_end_io = bio_map_kern_endio; return bio; } EXPORT_SYMBOL(bio_map_kern); static void bio_copy_kern_endio(struct bio *bio) { bio_free_pages(bio); bio_put(bio); } static void bio_copy_kern_endio_read(struct bio *bio) { char *p = bio->bi_private; struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) { memcpy(p, page_address(bvec->bv_page), bvec->bv_len); p += bvec->bv_len; } bio_copy_kern_endio(bio); } /** * bio_copy_kern - copy kernel address into bio * @q: the struct request_queue for the bio * @data: pointer to buffer to copy * @len: length in bytes * @gfp_mask: allocation flags for bio and page allocation * @reading: data direction is READ * * copy the kernel address into a bio suitable for io to a block * device. Returns an error pointer in case of error. */ struct bio *bio_copy_kern(struct request_queue *q, void *data, unsigned int len, gfp_t gfp_mask, int reading) { unsigned long kaddr = (unsigned long)data; unsigned long end = (kaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = kaddr >> PAGE_SHIFT; struct bio *bio; void *p = data; int nr_pages = 0; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages = end - start; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); while (len) { struct page *page; unsigned int bytes = PAGE_SIZE; if (bytes > len) bytes = len; page = alloc_page(q->bounce_gfp | gfp_mask); if (!page) goto cleanup; if (!reading) memcpy(page_address(page), p, bytes); if (bio_add_pc_page(q, bio, page, bytes, 0) < bytes) break; len -= bytes; p += bytes; } if (reading) { bio->bi_end_io = bio_copy_kern_endio_read; bio->bi_private = data; } else { bio->bi_end_io = bio_copy_kern_endio; } return bio; cleanup: bio_free_pages(bio); bio_put(bio); return ERR_PTR(-ENOMEM); } /* * bio_set_pages_dirty() and bio_check_pages_dirty() are support functions * for performing direct-IO in BIOs. * * The problem is that we cannot run set_page_dirty() from interrupt context * because the required locks are not interrupt-safe. So what we can do is to * mark the pages dirty _before_ performing IO. And in interrupt context, * check that the pages are still dirty. If so, fine. If not, redirty them * in process context. * * We special-case compound pages here: normally this means reads into hugetlb * pages. The logic in here doesn't really work right for compound pages * because the VM does not uniformly chase down the head page in all cases. * But dirtiness of compound pages is pretty meaningless anyway: the VM doesn't * handle them at all. So we skip compound pages here at an early stage. * * Note that this code is very hard to test under normal circumstances because * direct-io pins the pages with get_user_pages(). This makes * is_page_cache_freeable return false, and the VM will not clean the pages. * But other code (eg, flusher threads) could clean the pages if they are mapped * pagecache. * * Simply disabling the call to bio_set_pages_dirty() is a good way to test the * deferred bio dirtying paths. */ /* * bio_set_pages_dirty() will mark all the bio's pages as dirty. */ void bio_set_pages_dirty(struct bio *bio) { struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) { struct page *page = bvec->bv_page; if (page && !PageCompound(page)) set_page_dirty_lock(page); } } static void bio_release_pages(struct bio *bio) { struct bio_vec *bvec; int i; bio_for_each_segment_all(bvec, bio, i) { struct page *page = bvec->bv_page; if (page) put_page(page); } } /* * bio_check_pages_dirty() will check that all the BIO's pages are still dirty. * If they are, then fine. If, however, some pages are clean then they must * have been written out during the direct-IO read. So we take another ref on * the BIO and the offending pages and re-dirty the pages in process context. * * It is expected that bio_check_pages_dirty() will wholly own the BIO from * here on. It will run one put_page() against each page and will run one * bio_put() against the BIO. */ static void bio_dirty_fn(struct work_struct *work); static DECLARE_WORK(bio_dirty_work, bio_dirty_fn); static DEFINE_SPINLOCK(bio_dirty_lock); static struct bio *bio_dirty_list; /* * This runs in process context */ static void bio_dirty_fn(struct work_struct *work) { unsigned long flags; struct bio *bio; spin_lock_irqsave(&bio_dirty_lock, flags); bio = bio_dirty_list; bio_dirty_list = NULL; spin_unlock_irqrestore(&bio_dirty_lock, flags); while (bio) { struct bio *next = bio->bi_private; bio_set_pages_dirty(bio); bio_release_pages(bio); bio_put(bio); bio = next; } } void bio_check_pages_dirty(struct bio *bio) { struct bio_vec *bvec; int nr_clean_pages = 0; int i; bio_for_each_segment_all(bvec, bio, i) { struct page *page = bvec->bv_page; if (PageDirty(page) || PageCompound(page)) { put_page(page); bvec->bv_page = NULL; } else { nr_clean_pages++; } } if (nr_clean_pages) { unsigned long flags; spin_lock_irqsave(&bio_dirty_lock, flags); bio->bi_private = bio_dirty_list; bio_dirty_list = bio; spin_unlock_irqrestore(&bio_dirty_lock, flags); schedule_work(&bio_dirty_work); } else { bio_put(bio); } } void generic_start_io_acct(struct request_queue *q, int rw, unsigned long sectors, struct hd_struct *part) { int cpu = part_stat_lock(); part_round_stats(q, cpu, part); part_stat_inc(cpu, part, ios[rw]); part_stat_add(cpu, part, sectors[rw], sectors); part_inc_in_flight(q, part, rw); part_stat_unlock(); } EXPORT_SYMBOL(generic_start_io_acct); void generic_end_io_acct(struct request_queue *q, int rw, struct hd_struct *part, unsigned long start_time) { unsigned long duration = jiffies - start_time; int cpu = part_stat_lock(); part_stat_add(cpu, part, ticks[rw], duration); part_round_stats(q, cpu, part); part_dec_in_flight(q, part, rw); part_stat_unlock(); } EXPORT_SYMBOL(generic_end_io_acct); #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE void bio_flush_dcache_pages(struct bio *bi) { struct bio_vec bvec; struct bvec_iter iter; bio_for_each_segment(bvec, bi, iter) flush_dcache_page(bvec.bv_page); } EXPORT_SYMBOL(bio_flush_dcache_pages); #endif static inline bool bio_remaining_done(struct bio *bio) { /* * If we're not chaining, then ->__bi_remaining is always 1 and * we always end io on the first invocation. */ if (!bio_flagged(bio, BIO_CHAIN)) return true; BUG_ON(atomic_read(&bio->__bi_remaining) <= 0); if (atomic_dec_and_test(&bio->__bi_remaining)) { bio_clear_flag(bio, BIO_CHAIN); return true; } return false; } /** * bio_endio - end I/O on a bio * @bio: bio * * Description: * bio_endio() will end I/O on the whole bio. bio_endio() is the preferred * way to end I/O on a bio. No one should call bi_end_io() directly on a * bio unless they own it and thus know that it has an end_io function. * * bio_endio() can be called several times on a bio that has been chained * using bio_chain(). The ->bi_end_io() function will only be called the * last time. At this point the BLK_TA_COMPLETE tracing event will be * generated if BIO_TRACE_COMPLETION is set. **/ void bio_endio(struct bio *bio) { again: if (!bio_remaining_done(bio)) return; if (!bio_integrity_endio(bio)) return; /* * Need to have a real endio function for chained bios, otherwise * various corner cases will break (like stacking block devices that * save/restore bi_end_io) - however, we want to avoid unbounded * recursion and blowing the stack. Tail call optimization would * handle this, but compiling with frame pointers also disables * gcc's sibling call optimization. */ if (bio->bi_end_io == bio_chain_endio) { bio = __bio_chain_endio(bio); goto again; } if (bio->bi_disk && bio_flagged(bio, BIO_TRACE_COMPLETION)) { trace_block_bio_complete(bio->bi_disk->queue, bio, blk_status_to_errno(bio->bi_status)); bio_clear_flag(bio, BIO_TRACE_COMPLETION); } blk_throtl_bio_endio(bio); /* release cgroup info */ bio_uninit(bio); if (bio->bi_end_io) bio->bi_end_io(bio); } EXPORT_SYMBOL(bio_endio); /** * bio_split - split a bio * @bio: bio to split * @sectors: number of sectors to split from the front of @bio * @gfp: gfp mask * @bs: bio set to allocate from * * Allocates and returns a new bio which represents @sectors from the start of * @bio, and updates @bio to represent the remaining sectors. * * Unless this is a discard request the newly allocated bio will point * to @bio's bi_io_vec; it is the caller's responsibility to ensure that * @bio is not freed before the split. */ struct bio *bio_split(struct bio *bio, int sectors, gfp_t gfp, struct bio_set *bs) { struct bio *split = NULL; BUG_ON(sectors <= 0); BUG_ON(sectors >= bio_sectors(bio)); split = bio_clone_fast(bio, gfp, bs); if (!split) return NULL; split->bi_iter.bi_size = sectors << 9; if (bio_integrity(split)) bio_integrity_trim(split); bio_advance(bio, split->bi_iter.bi_size); if (bio_flagged(bio, BIO_TRACE_COMPLETION)) bio_set_flag(bio, BIO_TRACE_COMPLETION); return split; } EXPORT_SYMBOL(bio_split); /** * bio_trim - trim a bio * @bio: bio to trim * @offset: number of sectors to trim from the front of @bio * @size: size we want to trim @bio to, in sectors */ void bio_trim(struct bio *bio, int offset, int size) { /* 'bio' is a cloned bio which we need to trim to match * the given offset and size. */ size <<= 9; if (offset == 0 && size == bio->bi_iter.bi_size) return; bio_clear_flag(bio, BIO_SEG_VALID); bio_advance(bio, offset << 9); bio->bi_iter.bi_size = size; if (bio_integrity(bio)) bio_integrity_trim(bio); } EXPORT_SYMBOL_GPL(bio_trim); /* * create memory pools for biovec's in a bio_set. * use the global biovec slabs created for general use. */ mempool_t *biovec_create_pool(int pool_entries) { struct biovec_slab *bp = bvec_slabs + BVEC_POOL_MAX; return mempool_create_slab_pool(pool_entries, bp->slab); } void bioset_free(struct bio_set *bs) { if (bs->rescue_workqueue) destroy_workqueue(bs->rescue_workqueue); if (bs->bio_pool) mempool_destroy(bs->bio_pool); if (bs->bvec_pool) mempool_destroy(bs->bvec_pool); bioset_integrity_free(bs); bio_put_slab(bs); kfree(bs); } EXPORT_SYMBOL(bioset_free); /** * bioset_create - Create a bio_set * @pool_size: Number of bio and bio_vecs to cache in the mempool * @front_pad: Number of bytes to allocate in front of the returned bio * @flags: Flags to modify behavior, currently %BIOSET_NEED_BVECS * and %BIOSET_NEED_RESCUER * * Description: * Set up a bio_set to be used with @bio_alloc_bioset. Allows the caller * to ask for a number of bytes to be allocated in front of the bio. * Front pad allocation is useful for embedding the bio inside * another structure, to avoid allocating extra data to go with the bio. * Note that the bio must be embedded at the END of that structure always, * or things will break badly. * If %BIOSET_NEED_BVECS is set in @flags, a separate pool will be allocated * for allocating iovecs. This pool is not needed e.g. for bio_clone_fast(). * If %BIOSET_NEED_RESCUER is set, a workqueue is created which can be used to * dispatch queued requests when the mempool runs out of space. * */ struct bio_set *bioset_create(unsigned int pool_size, unsigned int front_pad, int flags) { unsigned int back_pad = BIO_INLINE_VECS * sizeof(struct bio_vec); struct bio_set *bs; bs = kzalloc(sizeof(*bs), GFP_KERNEL); if (!bs) return NULL; bs->front_pad = front_pad; spin_lock_init(&bs->rescue_lock); bio_list_init(&bs->rescue_list); INIT_WORK(&bs->rescue_work, bio_alloc_rescue); bs->bio_slab = bio_find_or_create_slab(front_pad + back_pad); if (!bs->bio_slab) { kfree(bs); return NULL; } bs->bio_pool = mempool_create_slab_pool(pool_size, bs->bio_slab); if (!bs->bio_pool) goto bad; if (flags & BIOSET_NEED_BVECS) { bs->bvec_pool = biovec_create_pool(pool_size); if (!bs->bvec_pool) goto bad; } if (!(flags & BIOSET_NEED_RESCUER)) return bs; bs->rescue_workqueue = alloc_workqueue("bioset", WQ_MEM_RECLAIM, 0); if (!bs->rescue_workqueue) goto bad; return bs; bad: bioset_free(bs); return NULL; } EXPORT_SYMBOL(bioset_create); #ifdef CONFIG_BLK_CGROUP /** * bio_associate_blkcg - associate a bio with the specified blkcg * @bio: target bio * @blkcg_css: css of the blkcg to associate * * Associate @bio with the blkcg specified by @blkcg_css. Block layer will * treat @bio as if it were issued by a task which belongs to the blkcg. * * This function takes an extra reference of @blkcg_css which will be put * when @bio is released. The caller must own @bio and is responsible for * synchronizing calls to this function. */ int bio_associate_blkcg(struct bio *bio, struct cgroup_subsys_state *blkcg_css) { if (unlikely(bio->bi_css)) return -EBUSY; css_get(blkcg_css); bio->bi_css = blkcg_css; return 0; } EXPORT_SYMBOL_GPL(bio_associate_blkcg); /** * bio_associate_current - associate a bio with %current * @bio: target bio * * Associate @bio with %current if it hasn't been associated yet. Block * layer will treat @bio as if it were issued by %current no matter which * task actually issues it. * * This function takes an extra reference of @task's io_context and blkcg * which will be put when @bio is released. The caller must own @bio, * ensure %current->io_context exists, and is responsible for synchronizing * calls to this function. */ int bio_associate_current(struct bio *bio) { struct io_context *ioc; if (bio->bi_css) return -EBUSY; ioc = current->io_context; if (!ioc) return -ENOENT; get_io_context_active(ioc); bio->bi_ioc = ioc; bio->bi_css = task_get_css(current, io_cgrp_id); return 0; } EXPORT_SYMBOL_GPL(bio_associate_current); /** * bio_disassociate_task - undo bio_associate_current() * @bio: target bio */ void bio_disassociate_task(struct bio *bio) { if (bio->bi_ioc) { put_io_context(bio->bi_ioc); bio->bi_ioc = NULL; } if (bio->bi_css) { css_put(bio->bi_css); bio->bi_css = NULL; } } /** * bio_clone_blkcg_association - clone blkcg association from src to dst bio * @dst: destination bio * @src: source bio */ void bio_clone_blkcg_association(struct bio *dst, struct bio *src) { if (src->bi_css) WARN_ON(bio_associate_blkcg(dst, src->bi_css)); } EXPORT_SYMBOL_GPL(bio_clone_blkcg_association); #endif /* CONFIG_BLK_CGROUP */ static void __init biovec_init_slabs(void) { int i; for (i = 0; i < BVEC_POOL_NR; i++) { int size; struct biovec_slab *bvs = bvec_slabs + i; if (bvs->nr_vecs <= BIO_INLINE_VECS) { bvs->slab = NULL; continue; } size = bvs->nr_vecs * sizeof(struct bio_vec); bvs->slab = kmem_cache_create(bvs->name, size, 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); } } static int __init init_bio(void) { bio_slab_max = 2; bio_slab_nr = 0; bio_slabs = kzalloc(bio_slab_max * sizeof(struct bio_slab), GFP_KERNEL); if (!bio_slabs) panic("bio: can't allocate bios\n"); bio_integrity_init(); biovec_init_slabs(); fs_bio_set = bioset_create(BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS); if (!fs_bio_set) panic("bio: can't allocate bios\n"); if (bioset_integrity_create(fs_bio_set, BIO_POOL_SIZE)) panic("bio: can't create integrity pool\n"); return 0; } subsys_initcall(init_bio);
./CrossVul/dataset_final_sorted/CWE-772/c/good_2604_0
crossvul-cpp_data_bad_2622_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP CCCC X X % % P P C X X % % PPPP C X % % P C X X % % P CCCC X X % % % % % % Read/Write ZSoft IBM PC Paintbrush Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/memory-private.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" /* Typedef declarations. */ typedef struct _PCXInfo { unsigned char identifier, version, encoding, bits_per_pixel; unsigned short left, top, right, bottom, horizontal_resolution, vertical_resolution; unsigned char reserved, planes; unsigned short bytes_per_line, palette_info, horizontal_screensize, vertical_screensize; unsigned char colormap_signature; } PCXInfo; /* Forward declarations. */ static MagickBooleanType WritePCXImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s D C X % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsDCX() returns MagickTrue if the image format type, identified by the % magick string, is DCX. % % The format of the IsDCX method is: % % MagickBooleanType IsDCX(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsDCX(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\261\150\336\72",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P C X % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPCX() returns MagickTrue if the image format type, identified by the % magick string, is PCX. % % The format of the IsPCX method is: % % MagickBooleanType IsPCX(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPCX(const unsigned char *magick,const size_t length) { if (length < 2) return(MagickFalse); if (memcmp(magick,"\012\002",2) == 0) return(MagickTrue); if (memcmp(magick,"\012\005",2) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P C X I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPCXImage() reads a ZSoft IBM PC Paintbrush file and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadPCXImage method is: % % Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPCXException(severity,tag) \ { \ if (scanline != (unsigned char *) NULL) \ scanline=(unsigned char *) RelinquishMagickMemory(scanline); \ if (pixel_info != (MemoryInfo *) NULL) \ pixel_info=RelinquishVirtualMemory(pixel_info); \ if (page_table != (MagickOffsetType *) NULL) \ page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table); \ ThrowReaderException(severity,tag); \ } Image *image; int bits, id, mask; MagickBooleanType status; MagickOffsetType offset, *page_table; MemoryInfo *pixel_info; PCXInfo pcx_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p, *r; size_t one, pcx_packets; ssize_t count, y; unsigned char packet, pcx_colormap[768], *pixels, *scanline; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a PCX file. */ page_table=(MagickOffsetType *) NULL; scanline=(unsigned char *) NULL; pixel_info=(MemoryInfo *) NULL; if (LocaleCompare(image_info->magick,"DCX") == 0) { size_t magic; /* Read the DCX page table. */ magic=ReadBlobLSBLong(image); if (magic != 987654321) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL, sizeof(*page_table)); if (page_table == (MagickOffsetType *) NULL) ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed"); for (id=0; id < 1024; id++) { page_table[id]=(MagickOffsetType) ReadBlobLSBLong(image); if (page_table[id] == 0) break; } } if (page_table != (MagickOffsetType *) NULL) { offset=SeekBlob(image,(MagickOffsetType) page_table[0],SEEK_SET); if (offset < 0) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,1,&pcx_info.identifier); for (id=1; id < 1024; id++) { int bits_per_pixel; /* Verify PCX identifier. */ pcx_info.version=(unsigned char) ReadBlobByte(image); if ((count != 1) || (pcx_info.identifier != 0x0a)) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); pcx_info.encoding=(unsigned char) ReadBlobByte(image); bits_per_pixel=ReadBlobByte(image); if (bits_per_pixel == -1) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); pcx_info.bits_per_pixel=(unsigned char) bits_per_pixel; pcx_info.left=ReadBlobLSBShort(image); pcx_info.top=ReadBlobLSBShort(image); pcx_info.right=ReadBlobLSBShort(image); pcx_info.bottom=ReadBlobLSBShort(image); pcx_info.horizontal_resolution=ReadBlobLSBShort(image); pcx_info.vertical_resolution=ReadBlobLSBShort(image); /* Read PCX raster colormap. */ image->columns=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.right- pcx_info.left)+1UL; image->rows=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.bottom- pcx_info.top)+1UL; if ((image->columns == 0) || (image->rows == 0) || ((pcx_info.bits_per_pixel != 1) && (pcx_info.bits_per_pixel != 2) && (pcx_info.bits_per_pixel != 4) && (pcx_info.bits_per_pixel != 8))) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); image->depth=pcx_info.bits_per_pixel; image->units=PixelsPerInchResolution; image->x_resolution=(double) pcx_info.horizontal_resolution; image->y_resolution=(double) pcx_info.vertical_resolution; image->colors=16; count=ReadBlob(image,3*image->colors,pcx_colormap); if (count != (ssize_t) (3*image->colors)) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); pcx_info.reserved=(unsigned char) ReadBlobByte(image); pcx_info.planes=(unsigned char) ReadBlobByte(image); if (pcx_info.planes > 6) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); if ((pcx_info.bits_per_pixel*pcx_info.planes) >= 64) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); if (pcx_info.planes == 0) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); one=1; if ((pcx_info.bits_per_pixel != 8) || (pcx_info.planes == 1)) if ((pcx_info.version == 3) || (pcx_info.version == 5) || ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)) image->colors=(size_t) MagickMin(one << (1UL* (pcx_info.bits_per_pixel*pcx_info.planes)),256UL); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed"); if ((pcx_info.bits_per_pixel >= 8) && (pcx_info.planes != 1)) image->storage_class=DirectClass; p=pcx_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].blue=ScaleCharToQuantum(*p++); } pcx_info.bytes_per_line=ReadBlobLSBShort(image); pcx_info.palette_info=ReadBlobLSBShort(image); pcx_info.horizontal_screensize=ReadBlobLSBShort(image); pcx_info.vertical_screensize=ReadBlobLSBShort(image); for (i=0; i < 54; i++) (void) ReadBlobByte(image); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Read image data. */ if (HeapOverflowSanityCheck(image->rows, (size_t) pcx_info.bytes_per_line) != MagickFalse) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); pcx_packets=(size_t) image->rows*pcx_info.bytes_per_line; if (HeapOverflowSanityCheck(pcx_packets, (size_t) pcx_info.planes) != MagickFalse) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); pcx_packets=(size_t) pcx_packets*pcx_info.planes; if ((size_t) (pcx_info.bits_per_pixel*pcx_info.planes*image->columns) > (pcx_packets*8U)) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); scanline=(unsigned char *) AcquireQuantumMemory(MagickMax(image->columns, pcx_info.bytes_per_line),MagickMax(8,pcx_info.planes)*sizeof(*scanline)); pixel_info=AcquireVirtualMemory(pcx_packets,2*sizeof(*pixels)); if ((scanline == (unsigned char *) NULL) || (pixel_info == (MemoryInfo *) NULL)) { if (scanline != (unsigned char *) NULL) scanline=(unsigned char *) RelinquishMagickMemory(scanline); if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Uncompress image data. */ p=pixels; if (pcx_info.encoding == 0) while (pcx_packets != 0) { packet=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile"); *p++=packet; pcx_packets--; } else while (pcx_packets != 0) { packet=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile"); if ((packet & 0xc0) != 0xc0) { *p++=packet; pcx_packets--; continue; } count=(ssize_t) (packet & 0x3f); packet=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile"); for ( ; count != 0; count--) { *p++=packet; pcx_packets--; if (pcx_packets == 0) break; } } if (image->storage_class == DirectClass) image->matte=pcx_info.planes > 3 ? MagickTrue : MagickFalse; else if ((pcx_info.version == 5) || ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)) { /* Initialize image colormap. */ if (image->colors > 256) ThrowPCXException(CorruptImageError,"ColormapExceeds256Colors"); if ((pcx_info.bits_per_pixel*pcx_info.planes) == 1) { /* Monochrome colormap. */ image->colormap[0].red=(Quantum) 0; image->colormap[0].green=(Quantum) 0; image->colormap[0].blue=(Quantum) 0; image->colormap[1].red=QuantumRange; image->colormap[1].green=QuantumRange; image->colormap[1].blue=QuantumRange; } else if (image->colors > 16) { /* 256 color images have their color map at the end of the file. */ pcx_info.colormap_signature=(unsigned char) ReadBlobByte(image); count=ReadBlob(image,3*image->colors,pcx_colormap); p=pcx_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].blue=ScaleCharToQuantum(*p++); } } } /* Convert PCX raster image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(y*pcx_info.bytes_per_line*pcx_info.planes); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); r=scanline; if (image->storage_class == DirectClass) for (i=0; i < pcx_info.planes; i++) { r=scanline+i; for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) { switch (i) { case 0: { *r=(*p++); break; } case 1: { *r=(*p++); break; } case 2: { *r=(*p++); break; } case 3: default: { *r=(*p++); break; } } r+=pcx_info.planes; } } else if (pcx_info.planes > 1) { for (x=0; x < (ssize_t) image->columns; x++) *r++=0; for (i=0; i < pcx_info.planes; i++) { r=scanline; for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) { bits=(*p++); for (mask=0x80; mask != 0; mask>>=1) { if (bits & mask) *r|=1 << i; r++; } } } } else switch (pcx_info.bits_per_pixel) { case 1: { register ssize_t bit; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00); p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (ssize_t) (8-(image->columns % 8)); bit--) *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00); p++; } break; } case 2: { for (x=0; x < ((ssize_t) image->columns-3); x+=4) { *r++=(*p >> 6) & 0x3; *r++=(*p >> 4) & 0x3; *r++=(*p >> 2) & 0x3; *r++=(*p) & 0x3; p++; } if ((image->columns % 4) != 0) { for (i=3; i >= (ssize_t) (4-(image->columns % 4)); i--) *r++=(unsigned char) ((*p >> (i*2)) & 0x03); p++; } break; } case 4: { for (x=0; x < ((ssize_t) image->columns-1); x+=2) { *r++=(*p >> 4) & 0xf; *r++=(*p) & 0xf; p++; } if ((image->columns % 2) != 0) *r++=(*p++ >> 4) & 0xf; break; } case 8: { (void) CopyMagickMemory(r,p,image->columns); break; } default: break; } /* Transfer image scanline. */ r=scanline; for (x=0; x < (ssize_t) image->columns; x++) { if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x,*r++); else { SetPixelRed(q,ScaleCharToQuantum(*r++)); SetPixelGreen(q,ScaleCharToQuantum(*r++)); SetPixelBlue(q,ScaleCharToQuantum(*r++)); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*r++)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (image->storage_class == PseudoClass) (void) SyncImage(image); scanline=(unsigned char *) RelinquishMagickMemory(scanline); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (page_table == (MagickOffsetType *) NULL) break; if (page_table[id] == 0) break; offset=SeekBlob(image,(MagickOffsetType) page_table[id],SEEK_SET); if (offset < 0) ThrowPCXException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,1,&pcx_info.identifier); if ((count != 0) && (pcx_info.identifier == 0x0a)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } if (page_table != (MagickOffsetType *) NULL) page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P C X I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPCXImage() adds attributes for the PCX image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPCXImage method is: % % size_t RegisterPCXImage(void) % */ ModuleExport size_t RegisterPCXImage(void) { MagickInfo *entry; entry=SetMagickInfo("DCX"); entry->decoder=(DecodeImageHandler *) ReadPCXImage; entry->encoder=(EncodeImageHandler *) WritePCXImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsDCX; entry->description=ConstantString("ZSoft IBM PC multi-page Paintbrush"); entry->module=ConstantString("PCX"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PCX"); entry->decoder=(DecodeImageHandler *) ReadPCXImage; entry->encoder=(EncodeImageHandler *) WritePCXImage; entry->magick=(IsImageFormatHandler *) IsPCX; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("ZSoft IBM PC Paintbrush"); entry->module=ConstantString("PCX"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P C X I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPCXImage() removes format registrations made by the % PCX module from the list of supported formats. % % The format of the UnregisterPCXImage method is: % % UnregisterPCXImage(void) % */ ModuleExport void UnregisterPCXImage(void) { (void) UnregisterMagickInfo("DCX"); (void) UnregisterMagickInfo("PCX"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P C X I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePCXImage() writes an image in the ZSoft IBM PC Paintbrush file % format. % % The format of the WritePCXImage method is: % % MagickBooleanType WritePCXImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % */ static MagickBooleanType PCXWritePixels(PCXInfo *pcx_info, const unsigned char *pixels,Image *image) { register const unsigned char *q; register ssize_t i, x; ssize_t count; unsigned char packet, previous; q=pixels; for (i=0; i < (ssize_t) pcx_info->planes; i++) { if (pcx_info->encoding == 0) { for (x=0; x < (ssize_t) pcx_info->bytes_per_line; x++) (void) WriteBlobByte(image,(unsigned char) (*q++)); } else { previous=(*q++); count=1; for (x=0; x < (ssize_t) (pcx_info->bytes_per_line-1); x++) { packet=(*q++); if ((packet == previous) && (count < 63)) { count++; continue; } if ((count > 1) || ((previous & 0xc0) == 0xc0)) { count|=0xc0; (void) WriteBlobByte(image,(unsigned char) count); } (void) WriteBlobByte(image,previous); previous=packet; count=1; } if ((count > 1) || ((previous & 0xc0) == 0xc0)) { count|=0xc0; (void) WriteBlobByte(image,(unsigned char) count); } (void) WriteBlobByte(image,previous); } } return (MagickTrue); } static MagickBooleanType WritePCXImage(const ImageInfo *image_info,Image *image) { MagickBooleanType status; MagickOffsetType offset, *page_table, scene; MemoryInfo *pixel_info; PCXInfo pcx_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; size_t length; ssize_t y; unsigned char *pcx_colormap, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); page_table=(MagickOffsetType *) NULL; if ((LocaleCompare(image_info->magick,"DCX") == 0) || ((GetNextImageInList(image) != (Image *) NULL) && (image_info->adjoin != MagickFalse))) { /* Write the DCX page table. */ (void) WriteBlobLSBLong(image,0x3ADE68B1L); page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL, sizeof(*page_table)); if (page_table == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); for (scene=0; scene < 1024; scene++) (void) WriteBlobLSBLong(image,0x00000000L); } scene=0; do { if (page_table != (MagickOffsetType *) NULL) page_table[scene]=TellBlob(image); /* Initialize PCX raster file header. */ pcx_info.identifier=0x0a; pcx_info.version=5; pcx_info.encoding=image_info->compression == NoCompression ? 0 : 1; pcx_info.bits_per_pixel=8; if ((image->storage_class == PseudoClass) && (SetImageMonochrome(image,&image->exception) != MagickFalse)) pcx_info.bits_per_pixel=1; pcx_info.left=0; pcx_info.top=0; pcx_info.right=(unsigned short) (image->columns-1); pcx_info.bottom=(unsigned short) (image->rows-1); switch (image->units) { case UndefinedResolution: case PixelsPerInchResolution: default: { pcx_info.horizontal_resolution=(unsigned short) image->x_resolution; pcx_info.vertical_resolution=(unsigned short) image->y_resolution; break; } case PixelsPerCentimeterResolution: { pcx_info.horizontal_resolution=(unsigned short) (2.54*image->x_resolution+0.5); pcx_info.vertical_resolution=(unsigned short) (2.54*image->y_resolution+0.5); break; } } pcx_info.reserved=0; pcx_info.planes=1; if ((image->storage_class == DirectClass) || (image->colors > 256)) { pcx_info.planes=3; if (image->matte != MagickFalse) pcx_info.planes++; } pcx_info.bytes_per_line=(unsigned short) (((size_t) image->columns* pcx_info.bits_per_pixel+7)/8); pcx_info.palette_info=1; pcx_info.colormap_signature=0x0c; /* Write PCX header. */ (void) WriteBlobByte(image,pcx_info.identifier); (void) WriteBlobByte(image,pcx_info.version); (void) WriteBlobByte(image,pcx_info.encoding); (void) WriteBlobByte(image,pcx_info.bits_per_pixel); (void) WriteBlobLSBShort(image,pcx_info.left); (void) WriteBlobLSBShort(image,pcx_info.top); (void) WriteBlobLSBShort(image,pcx_info.right); (void) WriteBlobLSBShort(image,pcx_info.bottom); (void) WriteBlobLSBShort(image,pcx_info.horizontal_resolution); (void) WriteBlobLSBShort(image,pcx_info.vertical_resolution); /* Dump colormap to file. */ pcx_colormap=(unsigned char *) AcquireQuantumMemory(256UL, 3*sizeof(*pcx_colormap)); if (pcx_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(pcx_colormap,0,3*256*sizeof(*pcx_colormap)); q=pcx_colormap; if ((image->storage_class == PseudoClass) && (image->colors <= 256)) for (i=0; i < (ssize_t) image->colors; i++) { *q++=ScaleQuantumToChar(image->colormap[i].red); *q++=ScaleQuantumToChar(image->colormap[i].green); *q++=ScaleQuantumToChar(image->colormap[i].blue); } (void) WriteBlob(image,3*16,(const unsigned char *) pcx_colormap); (void) WriteBlobByte(image,pcx_info.reserved); (void) WriteBlobByte(image,pcx_info.planes); (void) WriteBlobLSBShort(image,pcx_info.bytes_per_line); (void) WriteBlobLSBShort(image,pcx_info.palette_info); for (i=0; i < 58; i++) (void) WriteBlobByte(image,'\0'); length=(size_t) pcx_info.bytes_per_line; pixel_info=AcquireVirtualMemory(length,pcx_info.planes*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); q=pixels; if ((image->storage_class == DirectClass) || (image->colors > 256)) { /* Convert DirectClass image to PCX raster pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { q=pixels; for (i=0; i < pcx_info.planes; i++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; switch ((int) i) { case 0: { for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) { *q++=ScaleQuantumToChar(GetPixelRed(p)); p++; } break; } case 1: { for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) { *q++=ScaleQuantumToChar(GetPixelGreen(p)); p++; } break; } case 2: { for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(p)); p++; } break; } case 3: default: { for (x=(ssize_t) pcx_info.bytes_per_line; x != 0; x--) { *q++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p))); p++; } break; } } } if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { if (pcx_info.bits_per_pixel > 1) for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels; for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { register unsigned char bit, byte; /* Convert PseudoClass image to a PCX monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); bit=0; byte=0; q=pixels; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (GetPixelLuma(image,p) >= (QuantumRange/2.0)) byte|=0x01; bit++; if (bit == 8) { *q++=byte; bit=0; byte=0; } p++; } if (bit != 0) *q++=byte << (8-bit); if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } (void) WriteBlobByte(image,pcx_info.colormap_signature); (void) WriteBlob(image,3*256,pcx_colormap); } pixel_info=RelinquishVirtualMemory(pixel_info); pcx_colormap=(unsigned char *) RelinquishMagickMemory(pcx_colormap); if (page_table == (MagickOffsetType *) NULL) break; if (scene >= 1023) break; if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); if (page_table != (MagickOffsetType *) NULL) { /* Write the DCX page table. */ page_table[scene+1]=0; offset=SeekBlob(image,0L,SEEK_SET); if (offset < 0) ThrowWriterException(CorruptImageError,"ImproperImageHeader"); (void) WriteBlobLSBLong(image,0x3ADE68B1L); for (i=0; i <= (ssize_t) scene; i++) (void) WriteBlobLSBLong(image,(unsigned int) page_table[i]); page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table); } if (status == MagickFalse) { char *message; message=GetExceptionMessage(errno); (void) ThrowMagickException(&image->exception,GetMagickModule(), FileOpenError,"UnableToWriteFile","`%s': %s",image->filename,message); message=DestroyString(message); } (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_2622_0
crossvul-cpp_data_good_4476_0
/* $OpenBSD: table.c,v 1.49 2020/12/23 08:12:14 martijn Exp $ */ /* * Copyright (c) 2013 Eric Faurot <eric@openbsd.org> * Copyright (c) 2008 Gilles Chehade <gilles@poolp.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/types.h> #include <sys/queue.h> #include <sys/tree.h> #include <sys/socket.h> #include <sys/stat.h> #include <netinet/in.h> #include <arpa/inet.h> #include <net/if.h> #include <errno.h> #include <event.h> #include <imsg.h> #include <stdio.h> #include <stdlib.h> #include <regex.h> #include <limits.h> #include <string.h> #include <unistd.h> #include "smtpd.h" #include "log.h" struct table_backend *table_backend_lookup(const char *); extern struct table_backend table_backend_static; extern struct table_backend table_backend_db; extern struct table_backend table_backend_getpwnam; extern struct table_backend table_backend_proc; static const char * table_service_name(enum table_service); static int table_parse_lookup(enum table_service, const char *, const char *, union lookup *); static int parse_sockaddr(struct sockaddr *, int, const char *); static unsigned int last_table_id = 0; static struct table_backend *backends[] = { &table_backend_static, &table_backend_db, &table_backend_getpwnam, &table_backend_proc, NULL }; struct table_backend * table_backend_lookup(const char *backend) { int i; if (!strcmp(backend, "file")) backend = "static"; for (i = 0; backends[i]; i++) if (!strcmp(backends[i]->name, backend)) return (backends[i]); return NULL; } static const char * table_service_name(enum table_service s) { switch (s) { case K_NONE: return "NONE"; case K_ALIAS: return "ALIAS"; case K_DOMAIN: return "DOMAIN"; case K_CREDENTIALS: return "CREDENTIALS"; case K_NETADDR: return "NETADDR"; case K_USERINFO: return "USERINFO"; case K_SOURCE: return "SOURCE"; case K_MAILADDR: return "MAILADDR"; case K_ADDRNAME: return "ADDRNAME"; case K_MAILADDRMAP: return "MAILADDRMAP"; case K_RELAYHOST: return "RELAYHOST"; case K_STRING: return "STRING"; case K_REGEX: return "REGEX"; } return "???"; } struct table * table_find(struct smtpd *conf, const char *name) { return dict_get(conf->sc_tables_dict, name); } int table_match(struct table *table, enum table_service kind, const char *key) { return table_lookup(table, kind, key, NULL); } int table_lookup(struct table *table, enum table_service kind, const char *key, union lookup *lk) { char lkey[1024], *buf = NULL; int r; r = -1; if (table->t_backend->lookup == NULL) errno = ENOTSUP; else if (!lowercase(lkey, key, sizeof lkey)) { log_warnx("warn: lookup key too long: %s", key); errno = EINVAL; } else r = table->t_backend->lookup(table, kind, lkey, lk ? &buf : NULL); if (r == 1) { log_trace(TRACE_LOOKUP, "lookup: %s \"%s\" as %s in table %s:%s -> %s%s%s", lk ? "lookup" : "match", key, table_service_name(kind), table->t_backend->name, table->t_name, lk ? "\"" : "", lk ? buf : "true", lk ? "\"" : ""); if (buf) r = table_parse_lookup(kind, lkey, buf, lk); } else log_trace(TRACE_LOOKUP, "lookup: %s \"%s\" as %s in table %s:%s -> %s%s", lk ? "lookup" : "match", key, table_service_name(kind), table->t_backend->name, table->t_name, (r == -1) ? "error: " : (lk ? "none" : "false"), (r == -1) ? strerror(errno) : ""); free(buf); return (r); } int table_fetch(struct table *table, enum table_service kind, union lookup *lk) { char *buf = NULL; int r; r = -1; if (table->t_backend->fetch == NULL) errno = ENOTSUP; else r = table->t_backend->fetch(table, kind, &buf); if (r == 1) { log_trace(TRACE_LOOKUP, "lookup: fetch %s from table %s:%s -> \"%s\"", table_service_name(kind), table->t_backend->name, table->t_name, buf); r = table_parse_lookup(kind, NULL, buf, lk); } else log_trace(TRACE_LOOKUP, "lookup: fetch %s from table %s:%s -> %s%s", table_service_name(kind), table->t_backend->name, table->t_name, (r == -1) ? "error: " : "none", (r == -1) ? strerror(errno) : ""); free(buf); return (r); } struct table * table_create(struct smtpd *conf, const char *backend, const char *name, const char *config) { struct table *t; struct table_backend *tb; char path[LINE_MAX]; size_t n; struct stat sb; if (name && table_find(conf, name)) fatalx("table_create: table \"%s\" already defined", name); if ((tb = table_backend_lookup(backend)) == NULL) { if ((size_t)snprintf(path, sizeof(path), PATH_LIBEXEC"/table-%s", backend) >= sizeof(path)) { fatalx("table_create: path too long \"" PATH_LIBEXEC"/table-%s\"", backend); } if (stat(path, &sb) == 0) { tb = table_backend_lookup("proc"); (void)strlcpy(path, backend, sizeof(path)); if (config) { (void)strlcat(path, ":", sizeof(path)); if (strlcat(path, config, sizeof(path)) >= sizeof(path)) fatalx("table_create: config file path too long"); } config = path; } } if (tb == NULL) fatalx("table_create: backend \"%s\" does not exist", backend); t = xcalloc(1, sizeof(*t)); t->t_backend = tb; if (config) { if (strlcpy(t->t_config, config, sizeof t->t_config) >= sizeof t->t_config) fatalx("table_create: table config \"%s\" too large", t->t_config); } if (strcmp(tb->name, "static") != 0) t->t_type = T_DYNAMIC; if (name == NULL) (void)snprintf(t->t_name, sizeof(t->t_name), "<dynamic:%u>", last_table_id++); else { n = strlcpy(t->t_name, name, sizeof(t->t_name)); if (n >= sizeof(t->t_name)) fatalx("table_create: table name too long"); } dict_set(conf->sc_tables_dict, t->t_name, t); return (t); } void table_destroy(struct smtpd *conf, struct table *t) { dict_xpop(conf->sc_tables_dict, t->t_name); free(t); } int table_config(struct table *t) { if (t->t_backend->config == NULL) return (1); return (t->t_backend->config(t)); } void table_add(struct table *t, const char *key, const char *val) { if (t->t_backend->add == NULL) fatalx("table_add: cannot add to table"); if (t->t_backend->add(t, key, val) == 0) log_warnx("warn: failed to add \"%s\" in table \"%s\"", key, t->t_name); } void table_dump(struct table *t) { const char *type; char buf[LINE_MAX]; switch(t->t_type) { case T_NONE: type = "NONE"; break; case T_DYNAMIC: type = "DYNAMIC"; break; case T_LIST: type = "LIST"; break; case T_HASH: type = "HASH"; break; default: type = "???"; break; } if (t->t_config[0]) snprintf(buf, sizeof(buf), " config=\"%s\"", t->t_config); else buf[0] = '\0'; log_debug("TABLE \"%s\" backend=%s type=%s%s", t->t_name, t->t_backend->name, type, buf); if (t->t_backend->dump) t->t_backend->dump(t); } int table_check_type(struct table *t, uint32_t mask) { return t->t_type & mask; } int table_check_service(struct table *t, uint32_t mask) { return t->t_backend->services & mask; } int table_check_use(struct table *t, uint32_t tmask, uint32_t smask) { return table_check_type(t, tmask) && table_check_service(t, smask); } int table_open(struct table *t) { if (t->t_backend->open == NULL) return (1); return (t->t_backend->open(t)); } void table_close(struct table *t) { if (t->t_backend->close) t->t_backend->close(t); } int table_update(struct table *t) { if (t->t_backend->update == NULL) return (1); return (t->t_backend->update(t)); } /* * quick reminder: * in *_match() s1 comes from session, s2 comes from table */ int table_domain_match(const char *s1, const char *s2) { return hostname_match(s1, s2); } int table_mailaddr_match(const char *s1, const char *s2) { struct mailaddr m1; struct mailaddr m2; if (!text_to_mailaddr(&m1, s1)) return 0; if (!text_to_mailaddr(&m2, s2)) return 0; return mailaddr_match(&m1, &m2); } static int table_match_mask(struct sockaddr_storage *, struct netaddr *); static int table_inet4_match(struct sockaddr_in *, struct netaddr *); static int table_inet6_match(struct sockaddr_in6 *, struct netaddr *); int table_netaddr_match(const char *s1, const char *s2) { struct netaddr n1; struct netaddr n2; if (strcasecmp(s1, s2) == 0) return 1; if (!text_to_netaddr(&n1, s1)) return 0; if (!text_to_netaddr(&n2, s2)) return 0; if (n1.ss.ss_family != n2.ss.ss_family) return 0; if (n1.ss.ss_len != n2.ss.ss_len) return 0; return table_match_mask(&n1.ss, &n2); } static int table_match_mask(struct sockaddr_storage *ss, struct netaddr *ssmask) { if (ss->ss_family == AF_INET) return table_inet4_match((struct sockaddr_in *)ss, ssmask); if (ss->ss_family == AF_INET6) return table_inet6_match((struct sockaddr_in6 *)ss, ssmask); return (0); } static int table_inet4_match(struct sockaddr_in *ss, struct netaddr *ssmask) { in_addr_t mask; int i; /* a.b.c.d/8 -> htonl(0xff000000) */ mask = 0; for (i = 0; i < ssmask->bits; ++i) mask = (mask >> 1) | 0x80000000; mask = htonl(mask); /* (addr & mask) == (net & mask) */ if ((ss->sin_addr.s_addr & mask) == (((struct sockaddr_in *)ssmask)->sin_addr.s_addr & mask)) return 1; return 0; } static int table_inet6_match(struct sockaddr_in6 *ss, struct netaddr *ssmask) { struct in6_addr *in; struct in6_addr *inmask; struct in6_addr mask; int i; memset(&mask, 0, sizeof(mask)); for (i = 0; i < ssmask->bits / 8; i++) mask.s6_addr[i] = 0xff; i = ssmask->bits % 8; if (i) mask.s6_addr[ssmask->bits / 8] = 0xff00 >> i; in = &ss->sin6_addr; inmask = &((struct sockaddr_in6 *)&ssmask->ss)->sin6_addr; for (i = 0; i < 16; i++) { if ((in->s6_addr[i] & mask.s6_addr[i]) != (inmask->s6_addr[i] & mask.s6_addr[i])) return (0); } return (1); } int table_regex_match(const char *string, const char *pattern) { regex_t preg; int cflags = REG_EXTENDED|REG_NOSUB; int ret; if (strncmp(pattern, "(?i)", 4) == 0) { cflags |= REG_ICASE; pattern += 4; } if (regcomp(&preg, pattern, cflags) != 0) return (0); ret = regexec(&preg, string, 0, NULL, 0); regfree(&preg); if (ret != 0) return (0); return (1); } void table_dump_all(struct smtpd *conf) { struct table *t; void *iter; iter = NULL; while (dict_iter(conf->sc_tables_dict, &iter, NULL, (void **)&t)) table_dump(t); } void table_open_all(struct smtpd *conf) { struct table *t; void *iter; iter = NULL; while (dict_iter(conf->sc_tables_dict, &iter, NULL, (void **)&t)) if (!table_open(t)) fatalx("failed to open table %s", t->t_name); } void table_close_all(struct smtpd *conf) { struct table *t; void *iter; iter = NULL; while (dict_iter(conf->sc_tables_dict, &iter, NULL, (void **)&t)) table_close(t); } static int table_parse_lookup(enum table_service service, const char *key, const char *line, union lookup *lk) { char buffer[LINE_MAX], *p; size_t len; len = strlen(line); switch (service) { case K_ALIAS: lk->expand = calloc(1, sizeof(*lk->expand)); if (lk->expand == NULL) return (-1); if (!expand_line(lk->expand, line, 1)) { expand_free(lk->expand); return (-1); } return (1); case K_DOMAIN: if (strlcpy(lk->domain.name, line, sizeof(lk->domain.name)) >= sizeof(lk->domain.name)) return (-1); return (1); case K_CREDENTIALS: /* credentials are stored as user:password */ if (len < 3) return (-1); /* too big to fit in a smtp session line */ if (len >= LINE_MAX) return (-1); p = strchr(line, ':'); if (p == NULL) { if (strlcpy(lk->creds.username, key, sizeof (lk->creds.username)) >= sizeof (lk->creds.username)) return (-1); if (strlcpy(lk->creds.password, line, sizeof(lk->creds.password)) >= sizeof(lk->creds.password)) return (-1); return (1); } if (p == line || p == line + len - 1) return (-1); memmove(lk->creds.username, line, p - line); lk->creds.username[p - line] = '\0'; if (strlcpy(lk->creds.password, p+1, sizeof(lk->creds.password)) >= sizeof(lk->creds.password)) return (-1); return (1); case K_NETADDR: if (!text_to_netaddr(&lk->netaddr, line)) return (-1); return (1); case K_USERINFO: if (!bsnprintf(buffer, sizeof(buffer), "%s:%s", key, line)) return (-1); if (!text_to_userinfo(&lk->userinfo, buffer)) return (-1); return (1); case K_SOURCE: if (parse_sockaddr((struct sockaddr *)&lk->source.addr, PF_UNSPEC, line) == -1) return (-1); return (1); case K_MAILADDR: if (!text_to_mailaddr(&lk->mailaddr, line)) return (-1); return (1); case K_MAILADDRMAP: lk->maddrmap = calloc(1, sizeof(*lk->maddrmap)); if (lk->maddrmap == NULL) return (-1); maddrmap_init(lk->maddrmap); if (!mailaddr_line(lk->maddrmap, line)) { maddrmap_free(lk->maddrmap); return (-1); } return (1); case K_ADDRNAME: if (parse_sockaddr((struct sockaddr *)&lk->addrname.addr, PF_UNSPEC, key) == -1) return (-1); if (strlcpy(lk->addrname.name, line, sizeof(lk->addrname.name)) >= sizeof(lk->addrname.name)) return (-1); return (1); case K_RELAYHOST: if (strlcpy(lk->relayhost, line, sizeof(lk->relayhost)) >= sizeof(lk->relayhost)) return (-1); return (1); default: return (-1); } } static int parse_sockaddr(struct sockaddr *sa, int family, const char *str) { struct in_addr ina; struct in6_addr in6a; struct sockaddr_in *sin; struct sockaddr_in6 *sin6; char *cp, *str2; const char *errstr; switch (family) { case PF_UNSPEC: if (parse_sockaddr(sa, PF_INET, str) == 0) return (0); return parse_sockaddr(sa, PF_INET6, str); case PF_INET: if (inet_pton(PF_INET, str, &ina) != 1) return (-1); sin = (struct sockaddr_in *)sa; memset(sin, 0, sizeof *sin); sin->sin_len = sizeof(struct sockaddr_in); sin->sin_family = PF_INET; sin->sin_addr.s_addr = ina.s_addr; return (0); case PF_INET6: if (strncasecmp("ipv6:", str, 5) == 0) str += 5; cp = strchr(str, SCOPE_DELIMITER); if (cp) { str2 = strdup(str); if (str2 == NULL) return (-1); str2[cp - str] = '\0'; if (inet_pton(PF_INET6, str2, &in6a) != 1) { free(str2); return (-1); } cp++; free(str2); } else if (inet_pton(PF_INET6, str, &in6a) != 1) return (-1); sin6 = (struct sockaddr_in6 *)sa; memset(sin6, 0, sizeof *sin6); sin6->sin6_len = sizeof(struct sockaddr_in6); sin6->sin6_family = PF_INET6; sin6->sin6_addr = in6a; if (cp == NULL) return (0); if (IN6_IS_ADDR_LINKLOCAL(&in6a) || IN6_IS_ADDR_MC_LINKLOCAL(&in6a) || IN6_IS_ADDR_MC_INTFACELOCAL(&in6a)) if ((sin6->sin6_scope_id = if_nametoindex(cp))) return (0); sin6->sin6_scope_id = strtonum(cp, 0, UINT32_MAX, &errstr); if (errstr) return (-1); return (0); default: break; } return (-1); }
./CrossVul/dataset_final_sorted/CWE-772/c/good_4476_0
crossvul-cpp_data_good_2608_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M SSSSS L % % MM MM SS L % % M M M SSS L % % M M SS L % % M M SSSSS LLLLL % % % % % % Execute Magick Scripting Language Scripts. % % % % Software Design % % Cristy % % Leonard Rosenthol % % William Radcliffe % % December 2001 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/annotate.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/composite.h" #include "MagickCore/constitute.h" #include "MagickCore/decorate.h" #include "MagickCore/display.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/effect.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum-private.h" #include "MagickCore/registry.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/shear.h" #include "MagickCore/signature.h" #include "MagickCore/statistic.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/transform.h" #include "MagickCore/threshold.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_XML_DELEGATE) # if defined(MAGICKCORE_WINDOWS_SUPPORT) # if !defined(__MINGW32__) && !defined(__MINGW64__) # include <win32config.h> # endif # endif # include <libxml/parser.h> # include <libxml/xmlmemory.h> # include <libxml/parserInternals.h> # include <libxml/xmlerror.h> #endif /* Define Declatations. */ #define ThrowMSLException(severity,tag,reason) \ (void) ThrowMagickException(msl_info->exception,GetMagickModule(),severity, \ tag,"`%s'",reason); /* Typedef declaractions. */ typedef struct _MSLGroupInfo { size_t numImages; /* how many images are in this group */ } MSLGroupInfo; typedef struct _MSLInfo { ExceptionInfo *exception; ssize_t n, number_groups; ImageInfo **image_info; DrawInfo **draw_info; Image **attributes, **image; char *content; MSLGroupInfo *group_info; #if defined(MAGICKCORE_XML_DELEGATE) xmlParserCtxtPtr parser; xmlDocPtr document; #endif } MSLInfo; /* Forward declarations. */ #if defined(MAGICKCORE_XML_DELEGATE) static MagickBooleanType WriteMSLImage(const ImageInfo *,Image *,ExceptionInfo *); static MagickBooleanType SetMSLAttributes(MSLInfo *,const char *,const char *); #endif #if defined(MAGICKCORE_XML_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d M S L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMSLImage() reads a Magick Scripting Language file and returns it. % It allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadMSLImage method is: % % Image *ReadMSLImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static inline Image *GetImageCache(const ImageInfo *image_info,const char *path, ExceptionInfo *exception) { char key[MagickPathExtent]; ExceptionInfo *sans_exception; Image *image; ImageInfo *read_info; (void) FormatLocaleString(key,MagickPathExtent,"cache:%s",path); sans_exception=AcquireExceptionInfo(); image=(Image *) GetImageRegistry(ImageRegistryType,key,sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if (image != (Image *) NULL) return(image); read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->filename,path,MagickPathExtent); image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) (void) SetImageRegistry(ImageRegistryType,key,image,exception); return(image); } static int IsPathDirectory(const char *path) { MagickBooleanType status; struct stat attributes; if ((path == (const char *) NULL) || (*path == '\0')) return(MagickFalse); status=GetPathAttributes(path,&attributes); if (status == MagickFalse) return(-1); if (S_ISDIR(attributes.st_mode) == 0) return(0); return(1); } static int MSLIsStandalone(void *context) { MSLInfo *msl_info; /* Is this document tagged standalone? */ (void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.MSLIsStandalone()"); msl_info=(MSLInfo *) context; return(msl_info->document->standalone == 1); } static int MSLHasInternalSubset(void *context) { MSLInfo *msl_info; /* Does this document has an internal subset? */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.MSLHasInternalSubset()"); msl_info=(MSLInfo *) context; return(msl_info->document->intSubset != NULL); } static int MSLHasExternalSubset(void *context) { MSLInfo *msl_info; /* Does this document has an external subset? */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.MSLHasExternalSubset()"); msl_info=(MSLInfo *) context; return(msl_info->document->extSubset != NULL); } static void MSLInternalSubset(void *context,const xmlChar *name, const xmlChar *external_id,const xmlChar *system_id) { MSLInfo *msl_info; /* Does this document has an internal subset? */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.internalSubset(%s %s %s)",name, (external_id != (const xmlChar *) NULL ? (const char *) external_id : " "), (system_id != (const xmlChar *) NULL ? (const char *) system_id : " ")); msl_info=(MSLInfo *) context; (void) xmlCreateIntSubset(msl_info->document,name,external_id,system_id); } static xmlParserInputPtr MSLResolveEntity(void *context, const xmlChar *public_id,const xmlChar *system_id) { MSLInfo *msl_info; xmlParserInputPtr stream; /* Special entity resolver, better left to the parser, it has more context than the application layer. The default behaviour is to not resolve the entities, in that case the ENTITY_REF nodes are built in the structure (and the parameter values). */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.resolveEntity(%s, %s)", (public_id != (const xmlChar *) NULL ? (const char *) public_id : "none"), (system_id != (const xmlChar *) NULL ? (const char *) system_id : "none")); msl_info=(MSLInfo *) context; stream=xmlLoadExternalEntity((const char *) system_id,(const char *) public_id,msl_info->parser); return(stream); } static xmlEntityPtr MSLGetEntity(void *context,const xmlChar *name) { MSLInfo *msl_info; /* Get an entity by name. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.MSLGetEntity(%s)",(const char *) name); msl_info=(MSLInfo *) context; return(xmlGetDocEntity(msl_info->document,name)); } static xmlEntityPtr MSLGetParameterEntity(void *context,const xmlChar *name) { MSLInfo *msl_info; /* Get a parameter entity by name. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.getParameterEntity(%s)",(const char *) name); msl_info=(MSLInfo *) context; return(xmlGetParameterEntity(msl_info->document,name)); } static void MSLEntityDeclaration(void *context,const xmlChar *name,int type, const xmlChar *public_id,const xmlChar *system_id,xmlChar *content) { MSLInfo *msl_info; /* An entity definition has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.entityDecl(%s, %d, %s, %s, %s)",name,type, public_id != (const xmlChar *) NULL ? (const char *) public_id : "none", system_id != (const xmlChar *) NULL ? (const char *) system_id : "none", content); msl_info=(MSLInfo *) context; if (msl_info->parser->inSubset == 1) (void) xmlAddDocEntity(msl_info->document,name,type,public_id,system_id, content); else if (msl_info->parser->inSubset == 2) (void) xmlAddDtdEntity(msl_info->document,name,type,public_id,system_id, content); } static void MSLAttributeDeclaration(void *context,const xmlChar *element, const xmlChar *name,int type,int value,const xmlChar *default_value, xmlEnumerationPtr tree) { MSLInfo *msl_info; xmlChar *fullname, *prefix; xmlParserCtxtPtr parser; /* An attribute definition has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.attributeDecl(%s, %s, %d, %d, %s, ...)\n",element,name,type,value, default_value); msl_info=(MSLInfo *) context; fullname=(xmlChar *) NULL; prefix=(xmlChar *) NULL; parser=msl_info->parser; fullname=(xmlChar *) xmlSplitQName(parser,name,&prefix); if (parser->inSubset == 1) (void) xmlAddAttributeDecl(&parser->vctxt,msl_info->document->intSubset, element,fullname,prefix,(xmlAttributeType) type, (xmlAttributeDefault) value,default_value,tree); else if (parser->inSubset == 2) (void) xmlAddAttributeDecl(&parser->vctxt,msl_info->document->extSubset, element,fullname,prefix,(xmlAttributeType) type, (xmlAttributeDefault) value,default_value,tree); if (prefix != (xmlChar *) NULL) xmlFree(prefix); if (fullname != (xmlChar *) NULL) xmlFree(fullname); } static void MSLElementDeclaration(void *context,const xmlChar *name,int type, xmlElementContentPtr content) { MSLInfo *msl_info; xmlParserCtxtPtr parser; /* An element definition has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.elementDecl(%s, %d, ...)",name,type); msl_info=(MSLInfo *) context; parser=msl_info->parser; if (parser->inSubset == 1) (void) xmlAddElementDecl(&parser->vctxt,msl_info->document->intSubset, name,(xmlElementTypeVal) type,content); else if (parser->inSubset == 2) (void) xmlAddElementDecl(&parser->vctxt,msl_info->document->extSubset, name,(xmlElementTypeVal) type,content); } static void MSLNotationDeclaration(void *context,const xmlChar *name, const xmlChar *public_id,const xmlChar *system_id) { MSLInfo *msl_info; xmlParserCtxtPtr parser; /* What to do when a notation declaration has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.notationDecl(%s, %s, %s)",name, public_id != (const xmlChar *) NULL ? (const char *) public_id : "none", system_id != (const xmlChar *) NULL ? (const char *) system_id : "none"); msl_info=(MSLInfo *) context; parser=msl_info->parser; if (parser->inSubset == 1) (void) xmlAddNotationDecl(&parser->vctxt,msl_info->document->intSubset, name,public_id,system_id); else if (parser->inSubset == 2) (void) xmlAddNotationDecl(&parser->vctxt,msl_info->document->intSubset, name,public_id,system_id); } static void MSLUnparsedEntityDeclaration(void *context,const xmlChar *name, const xmlChar *public_id,const xmlChar *system_id,const xmlChar *notation) { MSLInfo *msl_info; /* What to do when an unparsed entity declaration is parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.unparsedEntityDecl(%s, %s, %s, %s)",name, public_id != (const xmlChar *) NULL ? (const char *) public_id : "none", system_id != (const xmlChar *) NULL ? (const char *) system_id : "none", notation); msl_info=(MSLInfo *) context; (void) xmlAddDocEntity(msl_info->document,name, XML_EXTERNAL_GENERAL_UNPARSED_ENTITY,public_id,system_id,notation); } static void MSLSetDocumentLocator(void *context,xmlSAXLocatorPtr location) { MSLInfo *msl_info; /* Receive the document locator at startup, actually xmlDefaultSAXLocator. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.setDocumentLocator()\n"); (void) location; msl_info=(MSLInfo *) context; (void) msl_info; } static void MSLStartDocument(void *context) { MSLInfo *msl_info; xmlParserCtxtPtr parser; /* Called when the document start being processed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.startDocument()"); msl_info=(MSLInfo *) context; parser=msl_info->parser; msl_info->document=xmlNewDoc(parser->version); if (msl_info->document == (xmlDocPtr) NULL) return; if (parser->encoding == NULL) msl_info->document->encoding=NULL; else msl_info->document->encoding=xmlStrdup(parser->encoding); msl_info->document->standalone=parser->standalone; } static void MSLEndDocument(void *context) { MSLInfo *msl_info; /* Called when the document end has been detected. */ (void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.endDocument()"); msl_info=(MSLInfo *) context; if (msl_info->content != (char *) NULL) msl_info->content=DestroyString(msl_info->content); } static void MSLPushImage(MSLInfo *msl_info,Image *image) { ssize_t n; (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(msl_info != (MSLInfo *) NULL); msl_info->n++; n=msl_info->n; msl_info->image_info=(ImageInfo **) ResizeQuantumMemory(msl_info->image_info, (n+1),sizeof(*msl_info->image_info)); msl_info->draw_info=(DrawInfo **) ResizeQuantumMemory(msl_info->draw_info, (n+1),sizeof(*msl_info->draw_info)); msl_info->attributes=(Image **) ResizeQuantumMemory(msl_info->attributes, (n+1),sizeof(*msl_info->attributes)); msl_info->image=(Image **) ResizeQuantumMemory(msl_info->image,(n+1), sizeof(*msl_info->image)); if ((msl_info->image_info == (ImageInfo **) NULL) || (msl_info->draw_info == (DrawInfo **) NULL) || (msl_info->attributes == (Image **) NULL) || (msl_info->image == (Image **) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed") msl_info->image_info[n]=CloneImageInfo(msl_info->image_info[n-1]); msl_info->draw_info[n]=CloneDrawInfo(msl_info->image_info[n-1], msl_info->draw_info[n-1]); if (image == (Image *) NULL) msl_info->attributes[n]=AcquireImage(msl_info->image_info[n], msl_info->exception); else msl_info->attributes[n]=CloneImage(image,0,0,MagickTrue, msl_info->exception); msl_info->image[n]=(Image *) image; if ((msl_info->image_info[n] == (ImageInfo *) NULL) || (msl_info->attributes[n] == (Image *) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed") if (msl_info->number_groups != 0) msl_info->group_info[msl_info->number_groups-1].numImages++; } static void MSLPopImage(MSLInfo *msl_info) { if (msl_info->number_groups != 0) return; if (msl_info->image[msl_info->n] != (Image *) NULL) msl_info->image[msl_info->n]=DestroyImage(msl_info->image[msl_info->n]); msl_info->attributes[msl_info->n]=DestroyImage( msl_info->attributes[msl_info->n]); msl_info->image_info[msl_info->n]=DestroyImageInfo( msl_info->image_info[msl_info->n]); msl_info->n--; } static void MSLStartElement(void *context,const xmlChar *tag, const xmlChar **attributes) { AffineMatrix affine, current; ChannelType channel; ChannelType channel_mask; char *attribute, key[MagickPathExtent], *value; const char *keyword; double angle; DrawInfo *draw_info; ExceptionInfo *exception; GeometryInfo geometry_info; Image *image; int flags; ssize_t option, j, n, x, y; MSLInfo *msl_info; RectangleInfo geometry; register ssize_t i; size_t height, width; /* Called when an opening tag has been processed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.startElement(%s",tag); exception=AcquireExceptionInfo(); msl_info=(MSLInfo *) context; n=msl_info->n; keyword=(const char *) NULL; value=(char *) NULL; SetGeometryInfo(&geometry_info); (void) ResetMagickMemory(&geometry,0,sizeof(geometry)); channel=DefaultChannels; switch (*tag) { case 'A': case 'a': { if (LocaleCompare((const char *) tag,"add-noise") == 0) { Image *noise_image; NoiseType noise; /* Add noise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } noise=UniformNoise; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'N': case 'n': { if (LocaleCompare(keyword,"noise") == 0) { option=ParseCommandOption(MagickNoiseOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); noise=(NoiseType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } channel_mask=SetImageChannelMask(msl_info->image[n],channel); noise_image=AddNoiseImage(msl_info->image[n],noise,1.0, msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); if (noise_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=noise_image; break; } if (LocaleCompare((const char *) tag,"annotate") == 0) { char text[MagickPathExtent]; /* Annotate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); angle=0.0; current=draw_info->affine; GetAffineMatrix(&affine); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"affine") == 0) { char *p; p=value; draw_info->affine.sx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.rx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ry=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.sy=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.tx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ty=StringToDouble(p,&p); break; } if (LocaleCompare(keyword,"align") == 0) { option=ParseCommandOption(MagickAlignOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedAlignType", value); draw_info->align=(AlignType) option; break; } if (LocaleCompare(keyword,"antialias") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); draw_info->stroke_antialias=(MagickBooleanType) option; draw_info->text_antialias=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"encoding") == 0) { CloneString(&draw_info->encoding,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->fill,exception); break; } if (LocaleCompare(keyword,"family") == 0) { CloneString(&draw_info->family,value); break; } if (LocaleCompare(keyword,"font") == 0) { CloneString(&draw_info->font,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGravityGeometry(msl_info->image[n],value, &geometry,exception); break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); draw_info->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"pointsize") == 0) { draw_info->pointsize=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { angle=StringToDouble(value,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.sx=geometry_info.rho; affine.sy=geometry_info.sigma; break; } if (LocaleCompare(keyword,"skewX") == 0) { angle=StringToDouble(value,(char **) NULL); affine.ry=tan(DegreesToRadians(fmod((double) angle, 360.0))); break; } if (LocaleCompare(keyword,"skewY") == 0) { angle=StringToDouble(value,(char **) NULL); affine.rx=tan(DegreesToRadians(fmod((double) angle, 360.0))); break; } if (LocaleCompare(keyword,"stretch") == 0) { option=ParseCommandOption(MagickStretchOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStretchType", value); draw_info->stretch=(StretchType) option; break; } if (LocaleCompare(keyword, "stroke") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->stroke,exception); break; } if (LocaleCompare(keyword,"strokewidth") == 0) { draw_info->stroke_width=StringToLong(value); break; } if (LocaleCompare(keyword,"style") == 0) { option=ParseCommandOption(MagickStyleOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStyleType", value); draw_info->style=(StyleType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"text") == 0) { CloneString(&draw_info->text,value); break; } if (LocaleCompare(keyword,"translate") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.tx=geometry_info.rho; affine.ty=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'U': case 'u': { if (LocaleCompare(keyword, "undercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->undercolor,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"weight") == 0) { draw_info->weight=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(text,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); CloneString(&draw_info->geometry,text); draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx; draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx; draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy; draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy; draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+ affine.tx; draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+ affine.ty; (void) AnnotateImage(msl_info->image[n],draw_info, msl_info->exception); draw_info=DestroyDrawInfo(draw_info); break; } if (LocaleCompare((const char *) tag,"append") == 0) { Image *append_image; MagickBooleanType stack; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } stack=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'S': case 's': { if (LocaleCompare(keyword,"stack") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); stack=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } append_image=AppendImages(msl_info->image[n],stack, msl_info->exception); if (append_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=append_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); break; } case 'B': case 'b': { if (LocaleCompare((const char *) tag,"blur") == 0) { Image *blur_image; /* Blur image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { geometry_info.sigma=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } channel_mask=SetImageChannelMask(msl_info->image[n],channel); blur_image=BlurImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); if (blur_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=blur_image; break; } if (LocaleCompare((const char *) tag,"border") == 0) { Image *border_image; /* Border image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"compose") == 0) { option=ParseCommandOption(MagickComposeOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedComposeType", value); msl_info->image[n]->compose=(CompositeOperator) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &msl_info->image[n]->border_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } border_image=BorderImage(msl_info->image[n],&geometry, msl_info->image[n]->compose,msl_info->exception); if (border_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=border_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'C': case 'c': { if (LocaleCompare((const char *) tag,"colorize") == 0) { char blend[MagickPathExtent]; Image *colorize_image; PixelInfo target; /* Add noise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } GetPixelInfo(msl_info->image[n],&target); (void) CopyMagickString(blend,"100",MagickPathExtent); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blend") == 0) { (void) CopyMagickString(blend,value,MagickPathExtent); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &target,msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } colorize_image=ColorizeImage(msl_info->image[n],blend,&target, msl_info->exception); if (colorize_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=colorize_image; break; } if (LocaleCompare((const char *) tag, "charcoal") == 0) { double radius = 0.0, sigma = 1.0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } /* NOTE: charcoal can have no attributes, since we use all the defaults! */ if (attributes != (const xmlChar **) NULL) { for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { radius=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { sigma = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } } /* charcoal image. */ { Image *newImage; newImage=CharcoalImage(msl_info->image[n],radius,sigma, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } if (LocaleCompare((const char *) tag,"chop") == 0) { Image *chop_image; /* Chop image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } chop_image=ChopImage(msl_info->image[n],&geometry, msl_info->exception); if (chop_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=chop_image; break; } if (LocaleCompare((const char *) tag,"color-floodfill") == 0) { PaintMethod paint_method; PixelInfo target; /* Color floodfill image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); SetGeometry(msl_info->image[n],&geometry); paint_method=FloodfillMethod; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"bordercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &target,exception); paint_method=FillToBorderMethod; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->fill,exception); break; } if (LocaleCompare(keyword,"fuzz") == 0) { msl_info->image[n]->fuzz=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FloodfillPaintImage(msl_info->image[n],draw_info,&target, geometry.x,geometry.y,paint_method == FloodfillMethod ? MagickFalse : MagickTrue,msl_info->exception); draw_info=DestroyDrawInfo(draw_info); break; } if (LocaleCompare((const char *) tag,"comment") == 0) break; if (LocaleCompare((const char *) tag,"composite") == 0) { char composite_geometry[MagickPathExtent]; CompositeOperator compose; Image *composite_image, *rotate_image; /* Composite image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } composite_image=NewImageList(); compose=OverCompositeOp; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"compose") == 0) { option=ParseCommandOption(MagickComposeOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedComposeType", value); compose=(CompositeOperator) option; break; } break; } case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id", exception); if ((attribute != (const char *) NULL) && (LocaleCompare(attribute,value) == 0)) { composite_image=CloneImage(msl_info->image[j],0,0, MagickFalse,exception); break; } } break; } default: break; } } if (composite_image == (Image *) NULL) break; rotate_image=NewImageList(); SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blend") == 0) { (void) SetImageArtifact(composite_image, "compose:args",value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } if (LocaleCompare(keyword, "color") == 0) { (void) QueryColorCompliance(value,AllCompliance, &composite_image->background_color,exception); break; } if (LocaleCompare(keyword,"compose") == 0) break; ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); msl_info->image[n]->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) break; ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'M': case 'm': { if (LocaleCompare(keyword,"mask") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id", exception); if ((attribute != (const char *) NULL) && (LocaleCompare(value,value) == 0)) { SetImageType(composite_image,TrueColorAlphaType, exception); (void) CompositeImage(composite_image, msl_info->image[j],CopyAlphaCompositeOp,MagickTrue, 0,0,exception); break; } } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { ssize_t opacity, y; register ssize_t x; register Quantum *q; CacheView *composite_view; opacity=StringToLong(value); if (compose != DissolveCompositeOp) { (void) SetImageAlpha(composite_image,(Quantum) opacity,exception); break; } (void) SetImageArtifact(msl_info->image[n], "compose:args",value); if (composite_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlpha(composite_image,OpaqueAlpha, exception); composite_view=AcquireAuthenticCacheView(composite_image,exception); for (y=0; y < (ssize_t) composite_image->rows ; y++) { q=GetCacheViewAuthenticPixels(composite_view,0,y, (ssize_t) composite_image->columns,1,exception); for (x=0; x < (ssize_t) composite_image->columns; x++) { if (GetPixelAlpha(composite_image,q) == OpaqueAlpha) SetPixelAlpha(composite_image, ClampToQuantum(opacity),q); q+=GetPixelChannels(composite_image); } if (SyncCacheViewAuthenticPixels(composite_view,exception) == MagickFalse) break; } composite_view=DestroyCacheView(composite_view); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { rotate_image=RotateImage(composite_image, StringToDouble(value,(char **) NULL),exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"tile") == 0) { MagickBooleanType tile; option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); tile=(MagickBooleanType) option; (void) tile; if (rotate_image != (Image *) NULL) (void) SetImageArtifact(rotate_image, "compose:outside-overlay","false"); else (void) SetImageArtifact(composite_image, "compose:outside-overlay","false"); image=msl_info->image[n]; height=composite_image->rows; width=composite_image->columns; for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) height) for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) width) { if (rotate_image != (Image *) NULL) (void) CompositeImage(image,rotate_image,compose, MagickTrue,x,y,exception); else (void) CompositeImage(image,composite_image, compose,MagickTrue,x,y,exception); } if (rotate_image != (Image *) NULL) rotate_image=DestroyImage(rotate_image); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } image=msl_info->image[n]; (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns, (double) composite_image->rows,(double) geometry.x,(double) geometry.y); flags=ParseGravityGeometry(image,composite_geometry,&geometry, exception); channel_mask=SetImageChannelMask(image,channel); if (rotate_image == (Image *) NULL) CompositeImage(image,composite_image,compose,MagickTrue,geometry.x, geometry.y,exception); else { /* Rotate image. */ geometry.x-=(ssize_t) (rotate_image->columns- composite_image->columns)/2; geometry.y-=(ssize_t) (rotate_image->rows- composite_image->rows)/2; CompositeImage(image,rotate_image,compose,MagickTrue,geometry.x, geometry.y,exception); rotate_image=DestroyImage(rotate_image); } (void) SetImageChannelMask(image,channel_mask); composite_image=DestroyImage(composite_image); break; } if (LocaleCompare((const char *) tag,"contrast") == 0) { MagickBooleanType sharpen; /* Contrast image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } sharpen=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'S': case 's': { if (LocaleCompare(keyword,"sharpen") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); sharpen=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) ContrastImage(msl_info->image[n],sharpen, msl_info->exception); break; } if (LocaleCompare((const char *) tag,"crop") == 0) { Image *crop_image; /* Crop image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGravityGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } crop_image=CropImage(msl_info->image[n],&geometry, msl_info->exception); if (crop_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=crop_image; break; } if (LocaleCompare((const char *) tag,"cycle-colormap") == 0) { ssize_t display; /* Cycle-colormap image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } display=0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"display") == 0) { display=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) CycleColormapImage(msl_info->image[n],display,exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'D': case 'd': { if (LocaleCompare((const char *) tag,"despeckle") == 0) { Image *despeckle_image; /* Despeckle image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } despeckle_image=DespeckleImage(msl_info->image[n], msl_info->exception); if (despeckle_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=despeckle_image; break; } if (LocaleCompare((const char *) tag,"display") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) DisplayImages(msl_info->image_info[n],msl_info->image[n], msl_info->exception); break; } if (LocaleCompare((const char *) tag,"draw") == 0) { char text[MagickPathExtent]; /* Annotate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); angle=0.0; current=draw_info->affine; GetAffineMatrix(&affine); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"affine") == 0) { char *p; p=value; draw_info->affine.sx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.rx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ry=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.sy=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.tx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ty=StringToDouble(p,&p); break; } if (LocaleCompare(keyword,"align") == 0) { option=ParseCommandOption(MagickAlignOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedAlignType", value); draw_info->align=(AlignType) option; break; } if (LocaleCompare(keyword,"antialias") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); draw_info->stroke_antialias=(MagickBooleanType) option; draw_info->text_antialias=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"encoding") == 0) { CloneString(&draw_info->encoding,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->fill,exception); break; } if (LocaleCompare(keyword,"family") == 0) { CloneString(&draw_info->family,value); break; } if (LocaleCompare(keyword,"font") == 0) { CloneString(&draw_info->font,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); draw_info->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"points") == 0) { if (LocaleCompare(draw_info->primitive,"path") == 0) { (void) ConcatenateString(&draw_info->primitive," '"); ConcatenateString(&draw_info->primitive,value); (void) ConcatenateString(&draw_info->primitive,"'"); } else { (void) ConcatenateString(&draw_info->primitive," "); ConcatenateString(&draw_info->primitive,value); } break; } if (LocaleCompare(keyword,"pointsize") == 0) { draw_info->pointsize=StringToDouble(value, (char **) NULL); break; } if (LocaleCompare(keyword,"primitive") == 0) { CloneString(&draw_info->primitive,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { angle=StringToDouble(value,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.sx=geometry_info.rho; affine.sy=geometry_info.sigma; break; } if (LocaleCompare(keyword,"skewX") == 0) { angle=StringToDouble(value,(char **) NULL); affine.ry=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"skewY") == 0) { angle=StringToDouble(value,(char **) NULL); affine.rx=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"stretch") == 0) { option=ParseCommandOption(MagickStretchOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStretchType", value); draw_info->stretch=(StretchType) option; break; } if (LocaleCompare(keyword, "stroke") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->stroke,exception); break; } if (LocaleCompare(keyword,"strokewidth") == 0) { draw_info->stroke_width=StringToLong(value); break; } if (LocaleCompare(keyword,"style") == 0) { option=ParseCommandOption(MagickStyleOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStyleType", value); draw_info->style=(StyleType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"text") == 0) { (void) ConcatenateString(&draw_info->primitive," '"); (void) ConcatenateString(&draw_info->primitive,value); (void) ConcatenateString(&draw_info->primitive,"'"); break; } if (LocaleCompare(keyword,"translate") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.tx=geometry_info.rho; affine.ty=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'U': case 'u': { if (LocaleCompare(keyword, "undercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->undercolor,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"weight") == 0) { draw_info->weight=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(text,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); CloneString(&draw_info->geometry,text); draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx; draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx; draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy; draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy; draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+ affine.tx; draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+ affine.ty; (void) DrawImage(msl_info->image[n],draw_info,exception); draw_info=DestroyDrawInfo(draw_info); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'E': case 'e': { if (LocaleCompare((const char *) tag,"edge") == 0) { Image *edge_image; /* Edge image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } edge_image=EdgeImage(msl_info->image[n],geometry_info.rho, msl_info->exception); if (edge_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=edge_image; break; } if (LocaleCompare((const char *) tag,"emboss") == 0) { Image *emboss_image; /* Emboss image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { geometry_info.sigma=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } emboss_image=EmbossImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,msl_info->exception); if (emboss_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=emboss_image; break; } if (LocaleCompare((const char *) tag,"enhance") == 0) { Image *enhance_image; /* Enhance image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } enhance_image=EnhanceImage(msl_info->image[n], msl_info->exception); if (enhance_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=enhance_image; break; } if (LocaleCompare((const char *) tag,"equalize") == 0) { /* Equalize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) EqualizeImage(msl_info->image[n], msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'F': case 'f': { if (LocaleCompare((const char *) tag, "flatten") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } /* no attributes here */ /* process the image */ { Image *newImage; newImage=MergeImageLayers(msl_info->image[n],FlattenLayer, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } if (LocaleCompare((const char *) tag,"flip") == 0) { Image *flip_image; /* Flip image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } flip_image=FlipImage(msl_info->image[n], msl_info->exception); if (flip_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=flip_image; break; } if (LocaleCompare((const char *) tag,"flop") == 0) { Image *flop_image; /* Flop image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } flop_image=FlopImage(msl_info->image[n], msl_info->exception); if (flop_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=flop_image; break; } if (LocaleCompare((const char *) tag,"frame") == 0) { FrameInfo frame_info; Image *frame_image; /* Frame image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } (void) ResetMagickMemory(&frame_info,0,sizeof(frame_info)); SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"compose") == 0) { option=ParseCommandOption(MagickComposeOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedComposeType", value); msl_info->image[n]->compose=(CompositeOperator) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &msl_info->image[n]->matte_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; frame_info.width=geometry.width; frame_info.height=geometry.height; frame_info.outer_bevel=geometry.x; frame_info.inner_bevel=geometry.y; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { frame_info.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"inner") == 0) { frame_info.inner_bevel=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"outer") == 0) { frame_info.outer_bevel=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { frame_info.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } frame_info.x=(ssize_t) frame_info.width; frame_info.y=(ssize_t) frame_info.height; frame_info.width=msl_info->image[n]->columns+2*frame_info.x; frame_info.height=msl_info->image[n]->rows+2*frame_info.y; frame_image=FrameImage(msl_info->image[n],&frame_info, msl_info->image[n]->compose,msl_info->exception); if (frame_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=frame_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'G': case 'g': { if (LocaleCompare((const char *) tag,"gamma") == 0) { char gamma[MagickPathExtent]; PixelInfo pixel; /* Gamma image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } channel=UndefinedChannel; pixel.red=0.0; pixel.green=0.0; pixel.blue=0.0; *gamma='\0'; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blue") == 0) { pixel.blue=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { (void) CopyMagickString(gamma,value,MagickPathExtent); break; } if (LocaleCompare(keyword,"green") == 0) { pixel.green=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"red") == 0) { pixel.red=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } if (*gamma == '\0') (void) FormatLocaleString(gamma,MagickPathExtent,"%g,%g,%g", (double) pixel.red,(double) pixel.green,(double) pixel.blue); (void) GammaImage(msl_info->image[n],strtod(gamma,(char **) NULL), msl_info->exception); break; } else if (LocaleCompare((const char *) tag,"get") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,(const char *) attributes[i]); (void) CopyMagickString(key,value,MagickPathExtent); switch (*keyword) { case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { (void) FormatLocaleString(value,MagickPathExtent,"%.20g", (double) msl_info->image[n]->rows); (void) SetImageProperty(msl_info->attributes[n],key,value, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { (void) FormatLocaleString(value,MagickPathExtent,"%.20g", (double) msl_info->image[n]->columns); (void) SetImageProperty(msl_info->attributes[n],key,value, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } break; } else if (LocaleCompare((const char *) tag, "group") == 0) { msl_info->number_groups++; msl_info->group_info=(MSLGroupInfo *) ResizeQuantumMemory( msl_info->group_info,msl_info->number_groups+1UL, sizeof(*msl_info->group_info)); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'I': case 'i': { if (LocaleCompare((const char *) tag,"image") == 0) { MSLPushImage(msl_info,(Image *) NULL); if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"color") == 0) { Image *next_image; (void) CopyMagickString(msl_info->image_info[n]->filename, "xc:",MagickPathExtent); (void) ConcatenateMagickString(msl_info->image_info[n]-> filename,value,MagickPathExtent); next_image=ReadImage(msl_info->image_info[n],exception); CatchException(exception); if (next_image == (Image *) NULL) continue; if (msl_info->image[n] == (Image *) NULL) msl_info->image[n]=next_image; else { register Image *p; /* Link image into image list. */ p=msl_info->image[n]; while (p->next != (Image *) NULL) p=GetNextImageInList(p); next_image->previous=p; p->next=next_image; } break; } (void) SetMSLAttributes(msl_info,keyword,value); break; } default: { (void) SetMSLAttributes(msl_info,keyword,value); break; } } } break; } if (LocaleCompare((const char *) tag,"implode") == 0) { Image *implode_image; /* Implode image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"amount") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } implode_image=ImplodeImage(msl_info->image[n],geometry_info.rho, msl_info->image[n]->interpolate,msl_info->exception); if (implode_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=implode_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'L': case 'l': { if (LocaleCompare((const char *) tag,"label") == 0) break; if (LocaleCompare((const char *) tag, "level") == 0) { double levelBlack = 0, levelGamma = 1, levelWhite = QuantumRange; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,(const char *) attributes[i]); (void) CopyMagickString(key,value,MagickPathExtent); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"black") == 0) { levelBlack = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { levelGamma = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"white") == 0) { levelWhite = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image */ LevelImage(msl_info->image[n],levelBlack,levelWhite,levelGamma, msl_info->exception); break; } } case 'M': case 'm': { if (LocaleCompare((const char *) tag,"magnify") == 0) { Image *magnify_image; /* Magnify image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } magnify_image=MagnifyImage(msl_info->image[n], msl_info->exception); if (magnify_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=magnify_image; break; } if (LocaleCompare((const char *) tag,"map") == 0) { Image *affinity_image; MagickBooleanType dither; QuantizeInfo *quantize_info; /* Map image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } affinity_image=NewImageList(); dither=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"dither") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); dither=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id", exception); if ((attribute != (const char *) NULL) && (LocaleCompare(attribute,value) == 0)) { affinity_image=CloneImage(msl_info->image[j],0,0, MagickFalse,exception); break; } } break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } quantize_info=AcquireQuantizeInfo(msl_info->image_info[n]); quantize_info->dither_method=dither != MagickFalse ? RiemersmaDitherMethod : NoDitherMethod; (void) RemapImages(quantize_info,msl_info->image[n], affinity_image,exception); quantize_info=DestroyQuantizeInfo(quantize_info); affinity_image=DestroyImage(affinity_image); break; } if (LocaleCompare((const char *) tag,"matte-floodfill") == 0) { double opacity; PixelInfo target; PaintMethod paint_method; /* Matte floodfill image. */ opacity=0.0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); paint_method=FloodfillMethod; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"bordercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &target,exception); paint_method=FillToBorderMethod; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fuzz") == 0) { msl_info->image[n]->fuzz=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { opacity=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); draw_info->fill.alpha=ClampToQuantum(opacity); channel_mask=SetImageChannelMask(msl_info->image[n],AlphaChannel); (void) FloodfillPaintImage(msl_info->image[n],draw_info,&target, geometry.x,geometry.y,paint_method == FloodfillMethod ? MagickFalse : MagickTrue,msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); draw_info=DestroyDrawInfo(draw_info); break; } if (LocaleCompare((const char *) tag,"median-filter") == 0) { Image *median_image; /* Median-filter image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } median_image=StatisticImage(msl_info->image[n],MedianStatistic, (size_t) geometry_info.rho,(size_t) geometry_info.sigma, msl_info->exception); if (median_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=median_image; break; } if (LocaleCompare((const char *) tag,"minify") == 0) { Image *minify_image; /* Minify image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } minify_image=MinifyImage(msl_info->image[n], msl_info->exception); if (minify_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=minify_image; break; } if (LocaleCompare((const char *) tag,"msl") == 0 ) break; if (LocaleCompare((const char *) tag,"modulate") == 0) { char modulate[MagickPathExtent]; /* Modulate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } geometry_info.rho=100.0; geometry_info.sigma=100.0; geometry_info.xi=100.0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blackness") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } if (LocaleCompare(keyword,"brightness") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"factor") == 0) { flags=ParseGeometry(value,&geometry_info); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"hue") == 0) { geometry_info.xi=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'L': case 'l': { if (LocaleCompare(keyword,"lightness") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"saturation") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"whiteness") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(modulate,MagickPathExtent,"%g,%g,%g", geometry_info.rho,geometry_info.sigma,geometry_info.xi); (void) ModulateImage(msl_info->image[n],modulate, msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'N': case 'n': { if (LocaleCompare((const char *) tag,"negate") == 0) { MagickBooleanType gray; /* Negate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } gray=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gray") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); gray=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } channel_mask=SetImageChannelMask(msl_info->image[n],channel); (void) NegateImage(msl_info->image[n],gray, msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); break; } if (LocaleCompare((const char *) tag,"normalize") == 0) { /* Normalize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) NormalizeImage(msl_info->image[n], msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'O': case 'o': { if (LocaleCompare((const char *) tag,"oil-paint") == 0) { Image *paint_image; /* Oil-paint image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } paint_image=OilPaintImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,msl_info->exception); if (paint_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=paint_image; break; } if (LocaleCompare((const char *) tag,"opaque") == 0) { PixelInfo fill_color, target; /* Opaque image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } (void) QueryColorCompliance("none",AllCompliance,&target, exception); (void) QueryColorCompliance("none",AllCompliance,&fill_color, exception); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &fill_color,exception); break; } if (LocaleCompare(keyword,"fuzz") == 0) { msl_info->image[n]->fuzz=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } channel_mask=SetImageChannelMask(msl_info->image[n],channel); (void) OpaquePaintImage(msl_info->image[n],&target,&fill_color, MagickFalse,msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'P': case 'p': { if (LocaleCompare((const char *) tag,"print") == 0) { if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'O': case 'o': { if (LocaleCompare(keyword,"output") == 0) { (void) FormatLocaleFile(stdout,"%s",value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } break; } if (LocaleCompare((const char *) tag, "profile") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { const char *name; const StringInfo *profile; Image *profile_image; ImageInfo *profile_info; keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); if (*keyword == '!') { /* Remove a profile from the image. */ (void) ProfileImage(msl_info->image[n],keyword, (const unsigned char *) NULL,0,exception); continue; } /* Associate a profile with the image. */ profile_info=CloneImageInfo(msl_info->image_info[n]); profile=GetImageProfile(msl_info->image[n],"iptc"); if (profile != (StringInfo *) NULL) profile_info->profile=(void *) CloneStringInfo(profile); profile_image=GetImageCache(profile_info,keyword,exception); profile_info=DestroyImageInfo(profile_info); if (profile_image == (Image *) NULL) { char name[MagickPathExtent], filename[MagickPathExtent]; register char *p; StringInfo *profile; (void) CopyMagickString(filename,keyword,MagickPathExtent); (void) CopyMagickString(name,keyword,MagickPathExtent); for (p=filename; *p != '\0'; p++) if ((*p == ':') && (IsPathDirectory(keyword) < 0) && (IsPathAccessible(keyword) == MagickFalse)) { register char *q; /* Look for profile name (e.g. name:profile). */ (void) CopyMagickString(name,filename,(size_t) (p-filename+1)); for (q=filename; *q != '\0'; q++) *q=(*++p); break; } profile=FileToStringInfo(filename,~0UL,exception); if (profile != (StringInfo *) NULL) { (void) ProfileImage(msl_info->image[n],name, GetStringInfoDatum(profile),(size_t) GetStringInfoLength(profile),exception); profile=DestroyStringInfo(profile); } continue; } ResetImageProfileIterator(profile_image); name=GetNextImageProfile(profile_image); while (name != (const char *) NULL) { profile=GetImageProfile(profile_image,name); if (profile != (StringInfo *) NULL) (void) ProfileImage(msl_info->image[n],name, GetStringInfoDatum(profile),(size_t) GetStringInfoLength(profile),exception); name=GetNextImageProfile(profile_image); } profile_image=DestroyImage(profile_image); } break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'Q': case 'q': { if (LocaleCompare((const char *) tag,"quantize") == 0) { QuantizeInfo quantize_info; /* Quantize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } GetQuantizeInfo(&quantize_info); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"colors") == 0) { quantize_info.number_colors=StringToLong(value); break; } if (LocaleCompare(keyword,"colorspace") == 0) { option=ParseCommandOption(MagickColorspaceOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError, "UnrecognizedColorspaceType",value); quantize_info.colorspace=(ColorspaceType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"dither") == 0) { option=ParseCommandOption(MagickDitherOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); quantize_info.dither_method=(DitherMethod) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'M': case 'm': { if (LocaleCompare(keyword,"measure") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); quantize_info.measure_error=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"treedepth") == 0) { quantize_info.tree_depth=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) QuantizeImage(&quantize_info,msl_info->image[n],exception); break; } if (LocaleCompare((const char *) tag,"query-font-metrics") == 0) { char text[MagickPathExtent]; MagickBooleanType status; TypeMetric metrics; /* Query font metrics. */ draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); angle=0.0; current=draw_info->affine; GetAffineMatrix(&affine); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"affine") == 0) { char *p; p=value; draw_info->affine.sx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.rx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ry=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.sy=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.tx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ty=StringToDouble(p,&p); break; } if (LocaleCompare(keyword,"align") == 0) { option=ParseCommandOption(MagickAlignOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedAlignType", value); draw_info->align=(AlignType) option; break; } if (LocaleCompare(keyword,"antialias") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); draw_info->stroke_antialias=(MagickBooleanType) option; draw_info->text_antialias=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"encoding") == 0) { CloneString(&draw_info->encoding,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->fill,exception); break; } if (LocaleCompare(keyword,"family") == 0) { CloneString(&draw_info->family,value); break; } if (LocaleCompare(keyword,"font") == 0) { CloneString(&draw_info->font,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); draw_info->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"pointsize") == 0) { draw_info->pointsize=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { angle=StringToDouble(value,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.sx=geometry_info.rho; affine.sy=geometry_info.sigma; break; } if (LocaleCompare(keyword,"skewX") == 0) { angle=StringToDouble(value,(char **) NULL); affine.ry=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"skewY") == 0) { angle=StringToDouble(value,(char **) NULL); affine.rx=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"stretch") == 0) { option=ParseCommandOption(MagickStretchOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStretchType", value); draw_info->stretch=(StretchType) option; break; } if (LocaleCompare(keyword, "stroke") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->stroke,exception); break; } if (LocaleCompare(keyword,"strokewidth") == 0) { draw_info->stroke_width=StringToLong(value); break; } if (LocaleCompare(keyword,"style") == 0) { option=ParseCommandOption(MagickStyleOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStyleType", value); draw_info->style=(StyleType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"text") == 0) { CloneString(&draw_info->text,value); break; } if (LocaleCompare(keyword,"translate") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.tx=geometry_info.rho; affine.ty=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'U': case 'u': { if (LocaleCompare(keyword, "undercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->undercolor,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"weight") == 0) { draw_info->weight=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(text,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); CloneString(&draw_info->geometry,text); draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx; draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx; draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy; draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy; draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+ affine.tx; draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+ affine.ty; status=GetTypeMetrics(msl_info->attributes[n],draw_info,&metrics, msl_info->exception); if (status != MagickFalse) { Image *image; image=msl_info->attributes[n]; FormatImageProperty(image,"msl:font-metrics.pixels_per_em.x", "%g",metrics.pixels_per_em.x); FormatImageProperty(image,"msl:font-metrics.pixels_per_em.y", "%g",metrics.pixels_per_em.y); FormatImageProperty(image,"msl:font-metrics.ascent","%g", metrics.ascent); FormatImageProperty(image,"msl:font-metrics.descent","%g", metrics.descent); FormatImageProperty(image,"msl:font-metrics.width","%g", metrics.width); FormatImageProperty(image,"msl:font-metrics.height","%g", metrics.height); FormatImageProperty(image,"msl:font-metrics.max_advance","%g", metrics.max_advance); FormatImageProperty(image,"msl:font-metrics.bounds.x1","%g", metrics.bounds.x1); FormatImageProperty(image,"msl:font-metrics.bounds.y1","%g", metrics.bounds.y1); FormatImageProperty(image,"msl:font-metrics.bounds.x2","%g", metrics.bounds.x2); FormatImageProperty(image,"msl:font-metrics.bounds.y2","%g", metrics.bounds.y2); FormatImageProperty(image,"msl:font-metrics.origin.x","%g", metrics.origin.x); FormatImageProperty(image,"msl:font-metrics.origin.y","%g", metrics.origin.y); } draw_info=DestroyDrawInfo(draw_info); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'R': case 'r': { if (LocaleCompare((const char *) tag,"raise") == 0) { MagickBooleanType raise; /* Raise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } raise=MagickFalse; SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"raise") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); raise=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) RaiseImage(msl_info->image[n],&geometry,raise, msl_info->exception); break; } if (LocaleCompare((const char *) tag,"read") == 0) { if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"filename") == 0) { Image *image; if (value == (char *) NULL) break; (void) CopyMagickString(msl_info->image_info[n]->filename, value,MagickPathExtent); image=ReadImage(msl_info->image_info[n],exception); CatchException(exception); if (image == (Image *) NULL) continue; AppendImageToList(&msl_info->image[n],image); break; } (void) SetMSLAttributes(msl_info,keyword,value); break; } default: { (void) SetMSLAttributes(msl_info,keyword,value); break; } } } break; } if (LocaleCompare((const char *) tag,"reduce-noise") == 0) { Image *paint_image; /* Reduce-noise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } paint_image=StatisticImage(msl_info->image[n],NonpeakStatistic, (size_t) geometry_info.rho,(size_t) geometry_info.sigma, msl_info->exception); if (paint_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=paint_image; break; } else if (LocaleCompare((const char *) tag,"repage") == 0) { /* init the values */ width=msl_info->image[n]->page.width; height=msl_info->image[n]->page.height; x=msl_info->image[n]->page.x; y=msl_info->image[n]->page.y; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { int flags; RectangleInfo geometry; flags=ParseAbsoluteGeometry(value,&geometry); if ((flags & WidthValue) != 0) { if ((flags & HeightValue) == 0) geometry.height=geometry.width; width=geometry.width; height=geometry.height; } if ((flags & AspectValue) != 0) { if ((flags & XValue) != 0) x+=geometry.x; if ((flags & YValue) != 0) y+=geometry.y; } else { if ((flags & XValue) != 0) { x=geometry.x; if ((width == 0) && (geometry.x > 0)) width=msl_info->image[n]->columns+geometry.x; } if ((flags & YValue) != 0) { y=geometry.y; if ((height == 0) && (geometry.y > 0)) height=msl_info->image[n]->rows+geometry.y; } } break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { height = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { width = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { x = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { y = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } msl_info->image[n]->page.width=width; msl_info->image[n]->page.height=height; msl_info->image[n]->page.x=x; msl_info->image[n]->page.y=y; break; } else if (LocaleCompare((const char *) tag,"resample") == 0) { double x_resolution, y_resolution; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; x_resolution=DefaultResolution; y_resolution=DefaultResolution; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { ssize_t flags; flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma*=geometry_info.rho; x_resolution=geometry_info.rho; y_resolution=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x-resolution") == 0) { x_resolution=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y-resolution") == 0) { y_resolution=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* Resample image. */ { double factor; Image *resample_image; factor=1.0; if (msl_info->image[n]->units == PixelsPerCentimeterResolution) factor=2.54; width=(size_t) (x_resolution*msl_info->image[n]->columns/ (factor*(msl_info->image[n]->resolution.x == 0.0 ? DefaultResolution : msl_info->image[n]->resolution.x))+0.5); height=(size_t) (y_resolution*msl_info->image[n]->rows/ (factor*(msl_info->image[n]->resolution.y == 0.0 ? DefaultResolution : msl_info->image[n]->resolution.y))+0.5); resample_image=ResizeImage(msl_info->image[n],width,height, msl_info->image[n]->filter,msl_info->exception); if (resample_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=resample_image; } break; } if (LocaleCompare((const char *) tag,"resize") == 0) { FilterType filter; Image *resize_image; /* Resize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } filter=UndefinedFilter; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"filter") == 0) { option=ParseCommandOption(MagickFilterOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); filter=(FilterType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseRegionGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToUnsignedLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } resize_image=ResizeImage(msl_info->image[n],geometry.width, geometry.height,filter,msl_info->exception); if (resize_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=resize_image; break; } if (LocaleCompare((const char *) tag,"roll") == 0) { Image *roll_image; /* Roll image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } roll_image=RollImage(msl_info->image[n],geometry.x,geometry.y, msl_info->exception); if (roll_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=roll_image; break; } else if (LocaleCompare((const char *) tag,"roll") == 0) { /* init the values */ width=msl_info->image[n]->columns; height=msl_info->image[n]->rows; x = y = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { (void) ParseMetaGeometry(value,&x,&y,&width,&height); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { x = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { y = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { Image *newImage; newImage=RollImage(msl_info->image[n], x, y, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; } break; } if (LocaleCompare((const char *) tag,"rotate") == 0) { Image *rotate_image; /* Rotate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"degrees") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } rotate_image=RotateImage(msl_info->image[n],geometry_info.rho, msl_info->exception); if (rotate_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=rotate_image; break; } else if (LocaleCompare((const char *) tag,"rotate") == 0) { /* init the values */ double degrees = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"degrees") == 0) { degrees = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { Image *newImage; newImage=RotateImage(msl_info->image[n], degrees, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; } break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'S': case 's': { if (LocaleCompare((const char *) tag,"sample") == 0) { Image *sample_image; /* Sample image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseRegionGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToUnsignedLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } sample_image=SampleImage(msl_info->image[n],geometry.width, geometry.height,msl_info->exception); if (sample_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=sample_image; break; } if (LocaleCompare((const char *) tag,"scale") == 0) { Image *scale_image; /* Scale image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseRegionGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToUnsignedLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } scale_image=ScaleImage(msl_info->image[n],geometry.width, geometry.height,msl_info->exception); if (scale_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=scale_image; break; } if (LocaleCompare((const char *) tag,"segment") == 0) { ColorspaceType colorspace; MagickBooleanType verbose; /* Segment image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } geometry_info.rho=1.0; geometry_info.sigma=1.5; colorspace=sRGBColorspace; verbose=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"cluster-threshold") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } if (LocaleCompare(keyword,"colorspace") == 0) { option=ParseCommandOption(MagickColorspaceOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError, "UnrecognizedColorspaceType",value); colorspace=(ColorspaceType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.5; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"smoothing-threshold") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SegmentImage(msl_info->image[n],colorspace,verbose, geometry_info.rho,geometry_info.sigma,exception); break; } else if (LocaleCompare((const char *) tag, "set") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"clip-mask") == 0) { for (j=0; j < msl_info->n; j++) { const char *property; property=GetImageProperty(msl_info->attributes[j],"id", exception); if (LocaleCompare(property,value) == 0) { SetImageMask(msl_info->image[n],ReadPixelMask, msl_info->image[j],exception); break; } } break; } if (LocaleCompare(keyword,"clip-path") == 0) { for (j=0; j < msl_info->n; j++) { const char *property; property=GetImageProperty(msl_info->attributes[j],"id", exception); if (LocaleCompare(property,value) == 0) { SetImageMask(msl_info->image[n],ReadPixelMask, msl_info->image[j],exception); break; } } break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,value); if (colorspace < 0) ThrowMSLException(OptionError,"UnrecognizedColorspace", value); (void) TransformImageColorspace(msl_info->image[n], (ColorspaceType) colorspace,exception); break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, exception); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { flags=ParseGeometry(value,&geometry_info); msl_info->image[n]->resolution.x=geometry_info.rho; msl_info->image[n]->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) msl_info->image[n]->resolution.y= msl_info->image[n]->resolution.x; break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, exception); break; } case 'O': case 'o': { if (LocaleCompare(keyword, "opacity") == 0) { ssize_t opac = OpaqueAlpha, len = (ssize_t) strlen( value ); if (value[len-1] == '%') { char tmp[100]; (void) CopyMagickString(tmp,value,len); opac = StringToLong( tmp ); opac = (int)(QuantumRange * ((float)opac/100)); } else opac = StringToLong( value ); (void) SetImageAlpha( msl_info->image[n], (Quantum) opac, exception); break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, msl_info->exception); break; } case 'P': case 'p': { if (LocaleCompare(keyword, "page") == 0) { char page[MagickPathExtent]; const char *image_option; MagickStatusType flags; RectangleInfo geometry; (void) ResetMagickMemory(&geometry,0,sizeof(geometry)); image_option=GetImageArtifact(msl_info->image[n],"page"); if (image_option != (const char *) NULL) flags=ParseAbsoluteGeometry(image_option,&geometry); flags=ParseAbsoluteGeometry(value,&geometry); (void) FormatLocaleString(page,MagickPathExtent,"%.20gx%.20g", (double) geometry.width,(double) geometry.height); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) (void) FormatLocaleString(page,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width, (double) geometry.height,(double) geometry.x,(double) geometry.y); (void) SetImageOption(msl_info->image_info[n],keyword,page); msl_info->image_info[n]->page=GetPageGeometry(page); break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, msl_info->exception); break; } default: { (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, msl_info->exception); break; } } } break; } if (LocaleCompare((const char *) tag,"shade") == 0) { Image *shade_image; MagickBooleanType gray; /* Shade image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } gray=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"azimuth") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"elevation") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } if (LocaleCompare(keyword,"gray") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); gray=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } shade_image=ShadeImage(msl_info->image[n],gray,geometry_info.rho, geometry_info.sigma,msl_info->exception); if (shade_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=shade_image; break; } if (LocaleCompare((const char *) tag,"shadow") == 0) { Image *shadow_image; /* Shear image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { geometry_info.rho=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { geometry_info.sigma=StringToLong(value); break; } break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry_info.xi=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry_info.psi=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } shadow_image=ShadowImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,(ssize_t) ceil(geometry_info.xi-0.5), (ssize_t) ceil(geometry_info.psi-0.5),msl_info->exception); if (shadow_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=shadow_image; break; } if (LocaleCompare((const char *) tag,"sharpen") == 0) { double radius = 0.0, sigma = 1.0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } /* NOTE: sharpen can have no attributes, since we use all the defaults! */ if (attributes != (const xmlChar **) NULL) { for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'R': case 'r': { if (LocaleCompare(keyword, "radius") == 0) { radius = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { sigma = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } } /* sharpen image. */ { Image *newImage; newImage=SharpenImage(msl_info->image[n],radius,sigma, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } else if (LocaleCompare((const char *) tag,"shave") == 0) { /* init the values */ width = height = 0; x = y = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { (void) ParseMetaGeometry(value,&x,&y,&width,&height); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { height = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { width = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { Image *newImage; RectangleInfo rectInfo; rectInfo.height = height; rectInfo.width = width; rectInfo.x = x; rectInfo.y = y; newImage=ShaveImage(msl_info->image[n], &rectInfo, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; } break; } if (LocaleCompare((const char *) tag,"shear") == 0) { Image *shear_image; /* Shear image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &msl_info->image[n]->background_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry_info.sigma=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } shear_image=ShearImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,msl_info->exception); if (shear_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=shear_image; break; } if (LocaleCompare((const char *) tag,"signature") == 0) { /* Signature image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SignatureImage(msl_info->image[n],exception); break; } if (LocaleCompare((const char *) tag,"solarize") == 0) { /* Solarize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } geometry_info.rho=QuantumRange/2.0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"threshold") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SolarizeImage(msl_info->image[n],geometry_info.rho, msl_info->exception); break; } if (LocaleCompare((const char *) tag,"spread") == 0) { Image *spread_image; /* Spread image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } spread_image=SpreadImage(msl_info->image[n], msl_info->image[n]->interpolate,geometry_info.rho, msl_info->exception); if (spread_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=spread_image; break; } else if (LocaleCompare((const char *) tag,"stegano") == 0) { Image * watermark = (Image*) NULL; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) { for (j=0; j<msl_info->n;j++) { const char * theAttr = GetImageProperty(msl_info->attributes[j], "id", exception); if (theAttr && LocaleCompare(theAttr, value) == 0) { watermark = msl_info->image[j]; break; } } break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ if ( watermark != (Image*) NULL ) { Image *newImage; newImage=SteganoImage(msl_info->image[n], watermark, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } else ThrowMSLException(OptionError,"MissingWatermarkImage",keyword); } else if (LocaleCompare((const char *) tag,"stereo") == 0) { Image * stereoImage = (Image*) NULL; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) { for (j=0; j<msl_info->n;j++) { const char * theAttr = GetImageProperty(msl_info->attributes[j], "id", exception); if (theAttr && LocaleCompare(theAttr, value) == 0) { stereoImage = msl_info->image[j]; break; } } break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ if ( stereoImage != (Image*) NULL ) { Image *newImage; newImage=StereoImage(msl_info->image[n], stereoImage, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } else ThrowMSLException(OptionError,"Missing stereo image",keyword); } if (LocaleCompare((const char *) tag,"strip") == 0) { /* Strip image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } (void) StripImage(msl_info->image[n],msl_info->exception); break; } if (LocaleCompare((const char *) tag,"swap") == 0) { Image *p, *q, *swap; ssize_t index, swap_index; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } index=(-1); swap_index=(-2); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"indexes") == 0) { flags=ParseGeometry(value,&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) == 0) swap_index=(ssize_t) geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } /* Swap images. */ p=GetImageFromList(msl_info->image[n],index); q=GetImageFromList(msl_info->image[n],swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { ThrowMSLException(OptionError,"NoSuchImage",(const char *) tag); break; } swap=CloneImage(p,0,0,MagickTrue,msl_info->exception); ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue, msl_info->exception)); ReplaceImageInList(&q,swap); msl_info->image[n]=GetFirstImageInList(q); break; } if (LocaleCompare((const char *) tag,"swirl") == 0) { Image *swirl_image; /* Swirl image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"degrees") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } swirl_image=SwirlImage(msl_info->image[n],geometry_info.rho, msl_info->image[n]->interpolate,msl_info->exception); if (swirl_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=swirl_image; break; } if (LocaleCompare((const char *) tag,"sync") == 0) { /* Sync image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SyncImage(msl_info->image[n],exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'T': case 't': { if (LocaleCompare((const char *) tag,"map") == 0) { Image *texture_image; /* Texture image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } texture_image=NewImageList(); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id", exception); if ((attribute != (const char *) NULL) && (LocaleCompare(attribute,value) == 0)) { texture_image=CloneImage(msl_info->image[j],0,0, MagickFalse,exception); break; } } break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) TextureImage(msl_info->image[n],texture_image,exception); texture_image=DestroyImage(texture_image); break; } else if (LocaleCompare((const char *) tag,"threshold") == 0) { /* init the values */ double threshold = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'T': case 't': { if (LocaleCompare(keyword,"threshold") == 0) { threshold = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { BilevelImage(msl_info->image[n],threshold,exception); break; } } else if (LocaleCompare((const char *) tag, "transparent") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"color") == 0) { PixelInfo target; (void) QueryColorCompliance(value,AllCompliance,&target, exception); (void) TransparentPaintImage(msl_info->image[n],&target, TransparentAlpha,MagickFalse,msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } break; } else if (LocaleCompare((const char *) tag, "trim") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } /* no attributes here */ /* process the image */ { Image *newImage; RectangleInfo rectInfo; /* all zeros on a crop == trim edges! */ rectInfo.height = rectInfo.width = 0; rectInfo.x = rectInfo.y = 0; newImage=CropImage(msl_info->image[n],&rectInfo, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'W': case 'w': { if (LocaleCompare((const char *) tag,"write") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"filename") == 0) { (void) CopyMagickString(msl_info->image[n]->filename,value, MagickPathExtent); break; } (void) SetMSLAttributes(msl_info,keyword,value); } default: { (void) SetMSLAttributes(msl_info,keyword,value); break; } } } /* process */ { *msl_info->image_info[n]->magick='\0'; (void) WriteImage(msl_info->image_info[n], msl_info->image[n], msl_info->exception); break; } } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } default: { ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); break; } } if (value != (char *) NULL) value=DestroyString(value); (void) DestroyExceptionInfo(exception); (void) LogMagickEvent(CoderEvent,GetMagickModule()," )"); } static void MSLEndElement(void *context,const xmlChar *tag) { ssize_t n; MSLInfo *msl_info; /* Called when the end of an element has been detected. */ (void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.endElement(%s)", tag); msl_info=(MSLInfo *) context; n=msl_info->n; switch (*tag) { case 'C': case 'c': { if (LocaleCompare((const char *) tag,"comment") == 0 ) { (void) DeleteImageProperty(msl_info->image[n],"comment"); if (msl_info->content == (char *) NULL) break; StripString(msl_info->content); (void) SetImageProperty(msl_info->image[n],"comment", msl_info->content,msl_info->exception); break; } break; } case 'G': case 'g': { if (LocaleCompare((const char *) tag, "group") == 0 ) { if (msl_info->group_info[msl_info->number_groups-1].numImages > 0 ) { ssize_t i = (ssize_t) (msl_info->group_info[msl_info->number_groups-1].numImages); while ( i-- ) { if (msl_info->image[msl_info->n] != (Image *) NULL) msl_info->image[msl_info->n]=DestroyImage( msl_info->image[msl_info->n]); msl_info->attributes[msl_info->n]=DestroyImage( msl_info->attributes[msl_info->n]); msl_info->image_info[msl_info->n]=DestroyImageInfo( msl_info->image_info[msl_info->n]); msl_info->n--; } } msl_info->number_groups--; } break; } case 'I': case 'i': { if (LocaleCompare((const char *) tag, "image") == 0) MSLPopImage(msl_info); break; } case 'L': case 'l': { if (LocaleCompare((const char *) tag,"label") == 0 ) { (void) DeleteImageProperty(msl_info->image[n],"label"); if (msl_info->content == (char *) NULL) break; StripString(msl_info->content); (void) SetImageProperty(msl_info->image[n],"label", msl_info->content,msl_info->exception); break; } break; } case 'M': case 'm': { if (LocaleCompare((const char *) tag, "msl") == 0 ) { /* This our base element. at the moment we don't do anything special but someday we might! */ } break; } default: break; } if (msl_info->content != (char *) NULL) msl_info->content=DestroyString(msl_info->content); } static void MSLCharacters(void *context,const xmlChar *c,int length) { MSLInfo *msl_info; register char *p; register ssize_t i; /* Receiving some characters from the parser. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.characters(%s,%d)",c,length); msl_info=(MSLInfo *) context; if (msl_info->content != (char *) NULL) msl_info->content=(char *) ResizeQuantumMemory(msl_info->content, strlen(msl_info->content)+length+MagickPathExtent, sizeof(*msl_info->content)); else { msl_info->content=(char *) NULL; if (~(size_t) length >= (MagickPathExtent-1)) msl_info->content=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*msl_info->content)); if (msl_info->content != (char *) NULL) *msl_info->content='\0'; } if (msl_info->content == (char *) NULL) return; p=msl_info->content+strlen(msl_info->content); for (i=0; i < length; i++) *p++=c[i]; *p='\0'; } static void MSLReference(void *context,const xmlChar *name) { MSLInfo *msl_info; xmlParserCtxtPtr parser; /* Called when an entity reference is detected. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.reference(%s)",name); msl_info=(MSLInfo *) context; parser=msl_info->parser; if (*name == '#') (void) xmlAddChild(parser->node,xmlNewCharRef(msl_info->document,name)); else (void) xmlAddChild(parser->node,xmlNewReference(msl_info->document,name)); } static void MSLIgnorableWhitespace(void *context,const xmlChar *c,int length) { MSLInfo *msl_info; /* Receiving some ignorable whitespaces from the parser. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.ignorableWhitespace(%.30s, %d)",c,length); msl_info=(MSLInfo *) context; (void) msl_info; } static void MSLProcessingInstructions(void *context,const xmlChar *target, const xmlChar *data) { MSLInfo *msl_info; /* A processing instruction has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.processingInstruction(%s, %s)", target,data); msl_info=(MSLInfo *) context; (void) msl_info; } static void MSLComment(void *context,const xmlChar *value) { MSLInfo *msl_info; /* A comment has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.comment(%s)",value); msl_info=(MSLInfo *) context; (void) msl_info; } static void MSLWarning(void *context,const char *format,...) { char *message, reason[MagickPathExtent]; MSLInfo *msl_info; va_list operands; /** Display and format a warning messages, gives file, line, position and extra parameters. */ va_start(operands,format); (void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.warning: "); (void) LogMagickEvent(CoderEvent,GetMagickModule(),format,operands); msl_info=(MSLInfo *) context; (void) msl_info; #if !defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsprintf(reason,format,operands); #else (void) vsnprintf(reason,MagickPathExtent,format,operands); #endif message=GetExceptionMessage(errno); ThrowMSLException(CoderError,reason,message); message=DestroyString(message); va_end(operands); } static void MSLError(void *context,const char *format,...) { char reason[MagickPathExtent]; MSLInfo *msl_info; va_list operands; /* Display and format a error formats, gives file, line, position and extra parameters. */ va_start(operands,format); (void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.error: "); (void) LogMagickEvent(CoderEvent,GetMagickModule(),format,operands); msl_info=(MSLInfo *) context; (void) msl_info; #if !defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsprintf(reason,format,operands); #else (void) vsnprintf(reason,MagickPathExtent,format,operands); #endif ThrowMSLException(DelegateFatalError,reason,"SAX error"); va_end(operands); } static void MSLCDataBlock(void *context,const xmlChar *value,int length) { MSLInfo *msl_info; xmlNodePtr child; xmlParserCtxtPtr parser; /* Called when a pcdata block has been parsed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.pcdata(%s, %d)",value,length); msl_info=(MSLInfo *) context; (void) msl_info; parser=msl_info->parser; child=xmlGetLastChild(parser->node); if ((child != (xmlNodePtr) NULL) && (child->type == XML_CDATA_SECTION_NODE)) { xmlTextConcat(child,value,length); return; } (void) xmlAddChild(parser->node,xmlNewCDataBlock(parser->myDoc,value,length)); } static void MSLExternalSubset(void *context,const xmlChar *name, const xmlChar *external_id,const xmlChar *system_id) { MSLInfo *msl_info; xmlParserCtxt parser_context; xmlParserCtxtPtr parser; xmlParserInputPtr input; /* Does this document has an external subset? */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.externalSubset(%s %s %s)",name, (external_id != (const xmlChar *) NULL ? (const char *) external_id : " "), (system_id != (const xmlChar *) NULL ? (const char *) system_id : " ")); msl_info=(MSLInfo *) context; (void) msl_info; parser=msl_info->parser; if (((external_id == NULL) && (system_id == NULL)) || ((parser->validate == 0) || (parser->wellFormed == 0) || (msl_info->document == 0))) return; input=MSLResolveEntity(context,external_id,system_id); if (input == NULL) return; (void) xmlNewDtd(msl_info->document,name,external_id,system_id); parser_context=(*parser); parser->inputTab=(xmlParserInputPtr *) xmlMalloc(5*sizeof(*parser->inputTab)); if (parser->inputTab == (xmlParserInputPtr *) NULL) { parser->errNo=XML_ERR_NO_MEMORY; parser->input=parser_context.input; parser->inputNr=parser_context.inputNr; parser->inputMax=parser_context.inputMax; parser->inputTab=parser_context.inputTab; return; } parser->inputNr=0; parser->inputMax=5; parser->input=NULL; xmlPushInput(parser,input); (void) xmlSwitchEncoding(parser,xmlDetectCharEncoding(parser->input->cur,4)); if (input->filename == (char *) NULL) input->filename=(char *) xmlStrdup(system_id); input->line=1; input->col=1; input->base=parser->input->cur; input->cur=parser->input->cur; input->free=NULL; xmlParseExternalSubset(parser,external_id,system_id); while (parser->inputNr > 1) (void) xmlPopInput(parser); xmlFreeInputStream(parser->input); xmlFree(parser->inputTab); parser->input=parser_context.input; parser->inputNr=parser_context.inputNr; parser->inputMax=parser_context.inputMax; parser->inputTab=parser_context.inputTab; } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickBooleanType ProcessMSLScript(const ImageInfo *image_info, Image **image,ExceptionInfo *exception) { char message[MagickPathExtent]; Image *msl_image; int status; ssize_t n; MSLInfo msl_info; xmlSAXHandler sax_modules; xmlSAXHandlerPtr sax_handler; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(image != (Image **) NULL); msl_image=AcquireImage(image_info,exception); status=OpenBlob(image_info,msl_image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", msl_image->filename); msl_image=DestroyImageList(msl_image); return(MagickFalse); } msl_image->columns=1; msl_image->rows=1; /* Parse MSL file. */ (void) ResetMagickMemory(&msl_info,0,sizeof(msl_info)); msl_info.exception=exception; msl_info.image_info=(ImageInfo **) AcquireMagickMemory( sizeof(*msl_info.image_info)); msl_info.draw_info=(DrawInfo **) AcquireMagickMemory( sizeof(*msl_info.draw_info)); /* top of the stack is the MSL file itself */ msl_info.image=(Image **) AcquireMagickMemory(sizeof(*msl_info.image)); msl_info.attributes=(Image **) AcquireMagickMemory( sizeof(*msl_info.attributes)); msl_info.group_info=(MSLGroupInfo *) AcquireMagickMemory( sizeof(*msl_info.group_info)); if ((msl_info.image_info == (ImageInfo **) NULL) || (msl_info.image == (Image **) NULL) || (msl_info.attributes == (Image **) NULL) || (msl_info.group_info == (MSLGroupInfo *) NULL)) ThrowFatalException(ResourceLimitFatalError,"UnableToInterpretMSLImage"); *msl_info.image_info=CloneImageInfo(image_info); *msl_info.draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); *msl_info.attributes=AcquireImage(image_info,exception); msl_info.group_info[0].numImages=0; /* the first slot is used to point to the MSL file image */ *msl_info.image=msl_image; if (*image != (Image *) NULL) MSLPushImage(&msl_info,*image); (void) xmlSubstituteEntitiesDefault(1); (void) ResetMagickMemory(&sax_modules,0,sizeof(sax_modules)); sax_modules.internalSubset=MSLInternalSubset; sax_modules.isStandalone=MSLIsStandalone; sax_modules.hasInternalSubset=MSLHasInternalSubset; sax_modules.hasExternalSubset=MSLHasExternalSubset; sax_modules.resolveEntity=MSLResolveEntity; sax_modules.getEntity=MSLGetEntity; sax_modules.entityDecl=MSLEntityDeclaration; sax_modules.notationDecl=MSLNotationDeclaration; sax_modules.attributeDecl=MSLAttributeDeclaration; sax_modules.elementDecl=MSLElementDeclaration; sax_modules.unparsedEntityDecl=MSLUnparsedEntityDeclaration; sax_modules.setDocumentLocator=MSLSetDocumentLocator; sax_modules.startDocument=MSLStartDocument; sax_modules.endDocument=MSLEndDocument; sax_modules.startElement=MSLStartElement; sax_modules.endElement=MSLEndElement; sax_modules.reference=MSLReference; sax_modules.characters=MSLCharacters; sax_modules.ignorableWhitespace=MSLIgnorableWhitespace; sax_modules.processingInstruction=MSLProcessingInstructions; sax_modules.comment=MSLComment; sax_modules.warning=MSLWarning; sax_modules.error=MSLError; sax_modules.fatalError=MSLError; sax_modules.getParameterEntity=MSLGetParameterEntity; sax_modules.cdataBlock=MSLCDataBlock; sax_modules.externalSubset=MSLExternalSubset; sax_handler=(&sax_modules); msl_info.parser=xmlCreatePushParserCtxt(sax_handler,&msl_info,(char *) NULL,0, msl_image->filename); while (ReadBlobString(msl_image,message) != (char *) NULL) { n=(ssize_t) strlen(message); if (n == 0) continue; status=xmlParseChunk(msl_info.parser,message,(int) n,MagickFalse); if (status != 0) break; (void) xmlParseChunk(msl_info.parser," ",1,MagickFalse); if (msl_info.exception->severity >= ErrorException) break; } if (msl_info.exception->severity == UndefinedException) (void) xmlParseChunk(msl_info.parser," ",1,MagickTrue); /* Free resources. */ xmlFreeParserCtxt(msl_info.parser); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX"); msl_info.group_info=(MSLGroupInfo *) RelinquishMagickMemory( msl_info.group_info); if (*image == (Image *) NULL) *image=(*msl_info.image); *msl_info.image_info=DestroyImageInfo(*msl_info.image_info); msl_info.image_info=(ImageInfo **) RelinquishMagickMemory( msl_info.image_info); *msl_info.draw_info=DestroyDrawInfo(*msl_info.draw_info); msl_info.draw_info=(DrawInfo **) RelinquishMagickMemory(msl_info.draw_info); msl_info.image=(Image **) RelinquishMagickMemory(msl_info.image); *msl_info.attributes=DestroyImage(*msl_info.attributes); msl_info.attributes=(Image **) RelinquishMagickMemory(msl_info.attributes); msl_info.group_info=(MSLGroupInfo *) RelinquishMagickMemory( msl_info.group_info); if (msl_info.exception->severity != UndefinedException) return(MagickFalse); return(MagickTrue); } static Image *ReadMSLImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=(Image *) NULL; (void) ProcessMSLScript(image_info,&image,exception); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M S L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterMSLImage() adds attributes for the MSL image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterMSLImage method is: % % size_t RegisterMSLImage(void) % */ ModuleExport size_t RegisterMSLImage(void) { MagickInfo *entry; #if defined(MAGICKCORE_XML_DELEGATE) xmlInitParser(); #endif entry=AcquireMagickInfo("MSL","MSL","Magick Scripting Language"); #if defined(MAGICKCORE_XML_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMSLImage; entry->encoder=(EncodeImageHandler *) WriteMSLImage; #endif entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } #if defined(MAGICKCORE_XML_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t M S L A t t r i b u t e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetMSLAttributes() ... % % The format of the SetMSLAttributes method is: % % MagickBooleanType SetMSLAttributes(MSLInfo *msl_info, % const char *keyword,const char *value) % % A description of each parameter follows: % % o msl_info: the MSL info. % % o keyword: the keyword. % % o value: the value. % */ static MagickBooleanType SetMSLAttributes(MSLInfo *msl_info,const char *keyword, const char *value) { Image *attributes; DrawInfo *draw_info; ExceptionInfo *exception; GeometryInfo geometry_info; Image *image; ImageInfo *image_info; int flags; ssize_t n; assert(msl_info != (MSLInfo *) NULL); if (keyword == (const char *) NULL) return(MagickTrue); if (value == (const char *) NULL) return(MagickTrue); exception=msl_info->exception; n=msl_info->n; attributes=msl_info->attributes[n]; image_info=msl_info->image_info[n]; draw_info=msl_info->draw_info[n]; image=msl_info->image[n]; switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"adjoin") == 0) { ssize_t adjoin; adjoin=ParseCommandOption(MagickBooleanOptions,MagickFalse,value); if (adjoin < 0) ThrowMSLException(OptionError,"UnrecognizedType",value); image_info->adjoin=(MagickBooleanType) adjoin; break; } if (LocaleCompare(keyword,"alpha") == 0) { ssize_t alpha; alpha=ParseCommandOption(MagickAlphaChannelOptions,MagickFalse,value); if (alpha < 0) ThrowMSLException(OptionError,"UnrecognizedType",value); if (image != (Image *) NULL) (void) SetImageAlphaChannel(image,(AlphaChannelOption) alpha, exception); break; } if (LocaleCompare(keyword,"antialias") == 0) { ssize_t antialias; antialias=ParseCommandOption(MagickBooleanOptions,MagickFalse,value); if (antialias < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType",value); image_info->antialias=(MagickBooleanType) antialias; break; } if (LocaleCompare(keyword,"area-limit") == 0) { MagickSizeType limit; limit=MagickResourceInfinity; if (LocaleCompare(value,"unlimited") != 0) limit=(MagickSizeType) StringToDoubleInterval(value,100.0); (void) SetMagickResourceLimit(AreaResource,limit); break; } if (LocaleCompare(keyword,"attenuate") == 0) { (void) SetImageOption(image_info,keyword,value); break; } if (LocaleCompare(keyword,"authenticate") == 0) { (void) CloneString(&image_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'B': case 'b': { if (LocaleCompare(keyword,"background") == 0) { (void) QueryColorCompliance(value,AllCompliance, &image_info->background_color,exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { if (image == (Image *) NULL) break; flags=ParseGeometry(value,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"bordercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &image_info->border_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { (void) CloneString(&image_info->density,value); (void) CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorCompliance(value,AllCompliance,&draw_info->fill, exception); (void) SetImageOption(image_info,keyword,value); break; } if (LocaleCompare(keyword,"filename") == 0) { (void) CopyMagickString(image_info->filename,value,MagickPathExtent); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gravity") == 0) { ssize_t gravity; gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,value); if (gravity < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType",value); (void) SetImageOption(image_info,keyword,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"id") == 0) { (void) SetImageProperty(attributes,keyword,value,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'M': case 'm': { if (LocaleCompare(keyword,"magick") == 0) { (void) CopyMagickString(image_info->magick,value,MagickPathExtent); break; } if (LocaleCompare(keyword,"mattecolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &image_info->matte_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"pointsize") == 0) { image_info->pointsize=StringToDouble(value,(char **) NULL); draw_info->pointsize=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Q': case 'q': { if (LocaleCompare(keyword,"quality") == 0) { image_info->quality=StringToLong(value); if (image == (Image *) NULL) break; image->quality=StringToLong(value); break; } break; } case 'S': case 's': { if (LocaleCompare(keyword,"size") == 0) { (void) CloneString(&image_info->size,value); break; } if (LocaleCompare(keyword,"stroke") == 0) { (void) QueryColorCompliance(value,AllCompliance,&draw_info->stroke, exception); (void) SetImageOption(image_info,keyword,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } return(MagickTrue); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M S L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterMSLImage() removes format registrations made by the % MSL module from the list of supported formats. % % The format of the UnregisterMSLImage method is: % % UnregisterMSLImage(void) % */ ModuleExport void UnregisterMSLImage(void) { (void) UnregisterMagickInfo("MSL"); #if defined(MAGICKCORE_XML_DELEGATE) xmlCleanupParser(); #endif } #if defined(MAGICKCORE_XML_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M S L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMSLImage() writes an image to a file in MVG image format. % % The format of the WriteMSLImage method is: % % MagickBooleanType WriteMSLImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteMSLImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { Image *msl_image; MagickBooleanType status; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); msl_image=CloneImage(image,0,0,MagickTrue,exception); status=ProcessMSLScript(image_info,&msl_image,exception); if (msl_image != (Image *) NULL) msl_image=DestroyImage(msl_image); return(status); } #endif
./CrossVul/dataset_final_sorted/CWE-772/c/good_2608_1
crossvul-cpp_data_bad_1356_0
/* SPDX-License-Identifier: LGPL-2.1+ */ #include <errno.h> #include <fcntl.h> #include <string.h> #include <sys/ioctl.h> #include <unistd.h> #include <linux/input.h> #include "sd-messages.h" #include "alloc-util.h" #include "fd-util.h" #include "logind-button.h" #include "missing_input.h" #include "string-util.h" #include "util.h" #define CONST_MAX4(a, b, c, d) CONST_MAX(CONST_MAX(a, b), CONST_MAX(c, d)) #define ULONG_BITS (sizeof(unsigned long)*8) static bool bitset_get(const unsigned long *bits, unsigned i) { return (bits[i / ULONG_BITS] >> (i % ULONG_BITS)) & 1UL; } static void bitset_put(unsigned long *bits, unsigned i) { bits[i / ULONG_BITS] |= (unsigned long) 1 << (i % ULONG_BITS); } Button* button_new(Manager *m, const char *name) { Button *b; assert(m); assert(name); b = new0(Button, 1); if (!b) return NULL; b->name = strdup(name); if (!b->name) return mfree(b); if (hashmap_put(m->buttons, b->name, b) < 0) { free(b->name); return mfree(b); } b->manager = m; b->fd = -1; return b; } void button_free(Button *b) { assert(b); hashmap_remove(b->manager->buttons, b->name); sd_event_source_unref(b->io_event_source); sd_event_source_unref(b->check_event_source); if (b->fd >= 0) /* If the device has been unplugged close() returns * ENODEV, let's ignore this, hence we don't use * safe_close() */ (void) close(b->fd); free(b->name); free(b->seat); free(b); } int button_set_seat(Button *b, const char *sn) { char *s; assert(b); assert(sn); s = strdup(sn); if (!s) return -ENOMEM; free(b->seat); b->seat = s; return 0; } static void button_lid_switch_handle_action(Manager *manager, bool is_edge) { HandleAction handle_action; assert(manager); /* If we are docked or on external power, handle the lid switch * differently */ if (manager_is_docked_or_external_displays(manager)) handle_action = manager->handle_lid_switch_docked; else if (manager->handle_lid_switch_ep != _HANDLE_ACTION_INVALID && manager_is_on_external_power()) handle_action = manager->handle_lid_switch_ep; else handle_action = manager->handle_lid_switch; manager_handle_action(manager, INHIBIT_HANDLE_LID_SWITCH, handle_action, manager->lid_switch_ignore_inhibited, is_edge); } static int button_recheck(sd_event_source *e, void *userdata) { Button *b = userdata; assert(b); assert(b->lid_closed); button_lid_switch_handle_action(b->manager, false); return 1; } static int button_install_check_event_source(Button *b) { int r; assert(b); /* Install a post handler, so that we keep rechecking as long as the lid is closed. */ if (b->check_event_source) return 0; r = sd_event_add_post(b->manager->event, &b->check_event_source, button_recheck, b); if (r < 0) return r; return sd_event_source_set_priority(b->check_event_source, SD_EVENT_PRIORITY_IDLE+1); } static int button_dispatch(sd_event_source *s, int fd, uint32_t revents, void *userdata) { Button *b = userdata; struct input_event ev; ssize_t l; assert(s); assert(fd == b->fd); assert(b); l = read(b->fd, &ev, sizeof(ev)); if (l < 0) return errno != EAGAIN ? -errno : 0; if ((size_t) l < sizeof(ev)) return -EIO; if (ev.type == EV_KEY && ev.value > 0) { switch (ev.code) { case KEY_POWER: case KEY_POWER2: log_struct(LOG_INFO, LOG_MESSAGE("Power key pressed."), "MESSAGE_ID=" SD_MESSAGE_POWER_KEY_STR); manager_handle_action(b->manager, INHIBIT_HANDLE_POWER_KEY, b->manager->handle_power_key, b->manager->power_key_ignore_inhibited, true); break; /* The kernel is a bit confused here: KEY_SLEEP = suspend-to-ram, which everybody else calls "suspend" KEY_SUSPEND = suspend-to-disk, which everybody else calls "hibernate" */ case KEY_SLEEP: log_struct(LOG_INFO, LOG_MESSAGE("Suspend key pressed."), "MESSAGE_ID=" SD_MESSAGE_SUSPEND_KEY_STR); manager_handle_action(b->manager, INHIBIT_HANDLE_SUSPEND_KEY, b->manager->handle_suspend_key, b->manager->suspend_key_ignore_inhibited, true); break; case KEY_SUSPEND: log_struct(LOG_INFO, LOG_MESSAGE("Hibernate key pressed."), "MESSAGE_ID=" SD_MESSAGE_HIBERNATE_KEY_STR); manager_handle_action(b->manager, INHIBIT_HANDLE_HIBERNATE_KEY, b->manager->handle_hibernate_key, b->manager->hibernate_key_ignore_inhibited, true); break; } } else if (ev.type == EV_SW && ev.value > 0) { if (ev.code == SW_LID) { log_struct(LOG_INFO, LOG_MESSAGE("Lid closed."), "MESSAGE_ID=" SD_MESSAGE_LID_CLOSED_STR); b->lid_closed = true; button_lid_switch_handle_action(b->manager, true); button_install_check_event_source(b); } else if (ev.code == SW_DOCK) { log_struct(LOG_INFO, LOG_MESSAGE("System docked."), "MESSAGE_ID=" SD_MESSAGE_SYSTEM_DOCKED_STR); b->docked = true; } } else if (ev.type == EV_SW && ev.value == 0) { if (ev.code == SW_LID) { log_struct(LOG_INFO, LOG_MESSAGE("Lid opened."), "MESSAGE_ID=" SD_MESSAGE_LID_OPENED_STR); b->lid_closed = false; b->check_event_source = sd_event_source_unref(b->check_event_source); } else if (ev.code == SW_DOCK) { log_struct(LOG_INFO, LOG_MESSAGE("System undocked."), "MESSAGE_ID=" SD_MESSAGE_SYSTEM_UNDOCKED_STR); b->docked = false; } } return 0; } static int button_suitable(Button *b) { unsigned long types[CONST_MAX(EV_KEY, EV_SW)/ULONG_BITS+1]; assert(b); assert(b->fd); if (ioctl(b->fd, EVIOCGBIT(EV_SYN, sizeof(types)), types) < 0) return -errno; if (bitset_get(types, EV_KEY)) { unsigned long keys[CONST_MAX4(KEY_POWER, KEY_POWER2, KEY_SLEEP, KEY_SUSPEND)/ULONG_BITS+1]; if (ioctl(b->fd, EVIOCGBIT(EV_KEY, sizeof(keys)), keys) < 0) return -errno; if (bitset_get(keys, KEY_POWER) || bitset_get(keys, KEY_POWER2) || bitset_get(keys, KEY_SLEEP) || bitset_get(keys, KEY_SUSPEND)) return true; } if (bitset_get(types, EV_SW)) { unsigned long switches[CONST_MAX(SW_LID, SW_DOCK)/ULONG_BITS+1]; if (ioctl(b->fd, EVIOCGBIT(EV_SW, sizeof(switches)), switches) < 0) return -errno; if (bitset_get(switches, SW_LID) || bitset_get(switches, SW_DOCK)) return true; } return false; } static int button_set_mask(Button *b) { unsigned long types[CONST_MAX(EV_KEY, EV_SW)/ULONG_BITS+1] = {}, keys[CONST_MAX4(KEY_POWER, KEY_POWER2, KEY_SLEEP, KEY_SUSPEND)/ULONG_BITS+1] = {}, switches[CONST_MAX(SW_LID, SW_DOCK)/ULONG_BITS+1] = {}; struct input_mask mask; assert(b); assert(b->fd >= 0); bitset_put(types, EV_KEY); bitset_put(types, EV_SW); mask = (struct input_mask) { .type = EV_SYN, .codes_size = sizeof(types), .codes_ptr = PTR_TO_UINT64(types), }; if (ioctl(b->fd, EVIOCSMASK, &mask) < 0) /* Log only at debug level if the kernel doesn't do EVIOCSMASK yet */ return log_full_errno(IN_SET(errno, ENOTTY, EOPNOTSUPP, EINVAL) ? LOG_DEBUG : LOG_WARNING, errno, "Failed to set EV_SYN event mask on /dev/input/%s: %m", b->name); bitset_put(keys, KEY_POWER); bitset_put(keys, KEY_POWER2); bitset_put(keys, KEY_SLEEP); bitset_put(keys, KEY_SUSPEND); mask = (struct input_mask) { .type = EV_KEY, .codes_size = sizeof(keys), .codes_ptr = PTR_TO_UINT64(keys), }; if (ioctl(b->fd, EVIOCSMASK, &mask) < 0) return log_warning_errno(errno, "Failed to set EV_KEY event mask on /dev/input/%s: %m", b->name); bitset_put(switches, SW_LID); bitset_put(switches, SW_DOCK); mask = (struct input_mask) { .type = EV_SW, .codes_size = sizeof(switches), .codes_ptr = PTR_TO_UINT64(switches), }; if (ioctl(b->fd, EVIOCSMASK, &mask) < 0) return log_warning_errno(errno, "Failed to set EV_SW event mask on /dev/input/%s: %m", b->name); return 0; } int button_open(Button *b) { char *p, name[256]; int r; assert(b); b->fd = safe_close(b->fd); p = strjoina("/dev/input/", b->name); b->fd = open(p, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK); if (b->fd < 0) return log_warning_errno(errno, "Failed to open %s: %m", p); r = button_suitable(b); if (r < 0) return log_warning_errno(r, "Failed to determine whether input device is relevant to us: %m"); if (r == 0) return log_debug_errno(SYNTHETIC_ERRNO(EADDRNOTAVAIL), "Device %s does not expose keys or switches relevant to us, ignoring.", p); if (ioctl(b->fd, EVIOCGNAME(sizeof(name)), name) < 0) { r = log_error_errno(errno, "Failed to get input name: %m"); goto fail; } (void) button_set_mask(b); r = sd_event_add_io(b->manager->event, &b->io_event_source, b->fd, EPOLLIN, button_dispatch, b); if (r < 0) { log_error_errno(r, "Failed to add button event: %m"); goto fail; } log_info("Watching system buttons on /dev/input/%s (%s)", b->name, name); return 0; fail: b->fd = safe_close(b->fd); return r; } int button_check_switches(Button *b) { unsigned long switches[CONST_MAX(SW_LID, SW_DOCK)/ULONG_BITS+1] = {}; assert(b); if (b->fd < 0) return -EINVAL; if (ioctl(b->fd, EVIOCGSW(sizeof(switches)), switches) < 0) return -errno; b->lid_closed = bitset_get(switches, SW_LID); b->docked = bitset_get(switches, SW_DOCK); if (b->lid_closed) button_install_check_event_source(b); return 0; }
./CrossVul/dataset_final_sorted/CWE-772/c/bad_1356_0