local block_state deflate_fast(s, flush)
    deflate_state *s;
    int flush;
{
    IPos hash_head;       /* head of the hash chain */
    int bflush;           /* set if current block must be flushed */

    for (;;) {
        /* Make sure that we always have enough lookahead, except
         * at the end of the input file. We need MAX_MATCH bytes
         * for the next match, plus MIN_MATCH bytes to insert the
         * string following the next match.
         */
        if (s->lookahead < MIN_LOOKAHEAD) {
            fill_window(s);
            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
                return need_more;
            }
            if (s->lookahead == 0) break; /* flush the current block */
        }

        /* Insert the string window[strstart .. strstart+2] in the
         * dictionary, and set hash_head to the head of the hash chain:
         */
        hash_head = NIL;
        if (s->lookahead >= MIN_MATCH) {
            INSERT_STRING(s, s->strstart, hash_head);
        }

        /* Find the longest match, discarding those <= prev_length.
         * At this point we have always match_length < MIN_MATCH
         */
        if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
            /* To simplify the code, we prevent matches with the string
             * of window index 0 (in particular we have to avoid a match
             * of the string with itself at the start of the input file).
             */
            s->match_length = longest_match (s, hash_head);
            /* longest_match() sets match_start */
        }
        if (s->match_length >= MIN_MATCH) {
            check_match(s, s->strstart, s->match_start, s->match_length);

            _tr_tally_dist(s, s->strstart - s->match_start,
                           s->match_length - MIN_MATCH, bflush);

            s->lookahead -= s->match_length;

            /* Insert new strings in the hash table only if the match length
             * is not too large. This saves time but degrades compression.
             */
#ifndef FASTEST
            if (s->match_length <= s->max_insert_length &&
                s->lookahead >= MIN_MATCH) {
                s->match_length--; /* string at strstart already in table */
                do {
                    s->strstart++;
                    INSERT_STRING(s, s->strstart, hash_head);
                    /* strstart never exceeds WSIZE-MAX_MATCH, so there are
                     * always MIN_MATCH bytes ahead.
                     */
                } while (--s->match_length != 0);
                s->strstart++;
            } else
#endif
            {
                s->strstart += s->match_length;
                s->match_length = 0;
                s->ins_h = s->window[s->strstart];
                UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
#if MIN_MATCH != 3
                Call UPDATE_HASH() MIN_MATCH-3 more times
#endif
                /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
                 * matter since it will be recomputed at next deflate call.
                 */
            }
        } else {
            /* No match, output a literal byte */
            Tracevv((stderr,"%c", s->window[s->strstart]));
            _tr_tally_lit (s, s->window[s->strstart], bflush);
            s->lookahead--;
            s->strstart++;
        }
        if (bflush) FLUSH_BLOCK(s, 0);
    }
    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
    if (flush == Z_FINISH) {
        FLUSH_BLOCK(s, 1);
        return finish_done;
    }
    if (s->last_lit)
        FLUSH_BLOCK(s, 0);
    return block_done;
}


static inline struct sk_buff * pfkey_xfrm_state2msg_expire ( const struct xfrm_state * x , int hsc ) {
 return __pfkey_xfrm_state2msg ( x , 0 , hsc ) ;
 }


static void adb_kbd_initfn(Object *obj) { ADBDevice *d = ADB_DEVICE(obj); d->devaddr = ADB_DEVID_KEYBOARD; }


void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) {
        ExecDirectoryType dt;
        char **e, **d;
        unsigned i;
        int r;

        assert(c);
        assert(f);

        prefix = strempty(prefix);

        fprintf(f,
                "%sUMask: %04o\n"
                "%sWorkingDirectory: %s\n"
                "%sRootDirectory: %s\n"
                "%sNonBlocking: %s\n"
                "%sPrivateTmp: %s\n"
                "%sPrivateDevices: %s\n"
                "%sProtectKernelTunables: %s\n"
                "%sProtectKernelModules: %s\n"
                "%sProtectControlGroups: %s\n"
                "%sPrivateNetwork: %s\n"
                "%sPrivateUsers: %s\n"
                "%sProtectHome: %s\n"
                "%sProtectSystem: %s\n"
                "%sMountAPIVFS: %s\n"
                "%sIgnoreSIGPIPE: %s\n"
                "%sMemoryDenyWriteExecute: %s\n"
                "%sRestrictRealtime: %s\n"
                "%sKeyringMode: %s\n"
                "%sProtectHostname: %s\n",
                prefix, c->umask,
                prefix, c->working_directory ? c->working_directory : "/",
                prefix, c->root_directory ? c->root_directory : "/",
                prefix, yes_no(c->non_blocking),
                prefix, yes_no(c->private_tmp),
                prefix, yes_no(c->private_devices),
                prefix, yes_no(c->protect_kernel_tunables),
                prefix, yes_no(c->protect_kernel_modules),
                prefix, yes_no(c->protect_control_groups),
                prefix, yes_no(c->private_network),
                prefix, yes_no(c->private_users),
                prefix, protect_home_to_string(c->protect_home),
                prefix, protect_system_to_string(c->protect_system),
                prefix, yes_no(c->mount_apivfs),
                prefix, yes_no(c->ignore_sigpipe),
                prefix, yes_no(c->memory_deny_write_execute),
                prefix, yes_no(c->restrict_realtime),
                prefix, exec_keyring_mode_to_string(c->keyring_mode),
                prefix, yes_no(c->protect_hostname));

        if (c->root_image)
                fprintf(f, "%sRootImage: %s\n", prefix, c->root_image);

        STRV_FOREACH(e, c->environment)
                fprintf(f, "%sEnvironment: %s\n", prefix, *e);

        STRV_FOREACH(e, c->environment_files)
                fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);

        STRV_FOREACH(e, c->pass_environment)
                fprintf(f, "%sPassEnvironment: %s\n", prefix, *e);

        STRV_FOREACH(e, c->unset_environment)
                fprintf(f, "%sUnsetEnvironment: %s\n", prefix, *e);

        fprintf(f, "%sRuntimeDirectoryPreserve: %s\n", prefix, exec_preserve_mode_to_string(c->runtime_directory_preserve_mode));

        for (dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
                fprintf(f, "%s%sMode: %04o\n", prefix, exec_directory_type_to_string(dt), c->directories[dt].mode);

                STRV_FOREACH(d, c->directories[dt].paths)
                        fprintf(f, "%s%s: %s\n", prefix, exec_directory_type_to_string(dt), *d);
        }

        if (c->nice_set)
                fprintf(f,
                        "%sNice: %i\n",
                        prefix, c->nice);

        if (c->oom_score_adjust_set)
                fprintf(f,
                        "%sOOMScoreAdjust: %i\n",
                        prefix, c->oom_score_adjust);

        for (i = 0; i < RLIM_NLIMITS; i++)
                if (c->rlimit[i]) {
                        fprintf(f, "%sLimit%s: " RLIM_FMT "\n",
                                prefix, rlimit_to_string(i), c->rlimit[i]->rlim_max);
                        fprintf(f, "%sLimit%sSoft: " RLIM_FMT "\n",
                                prefix, rlimit_to_string(i), c->rlimit[i]->rlim_cur);
                }

        if (c->ioprio_set) {
                _cleanup_free_ char *class_str = NULL;

                r = ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c->ioprio), &class_str);
                if (r >= 0)
                        fprintf(f, "%sIOSchedulingClass: %s\n", prefix, class_str);

                fprintf(f, "%sIOPriority: %lu\n", prefix, IOPRIO_PRIO_DATA(c->ioprio));
        }

        if (c->cpu_sched_set) {
                _cleanup_free_ char *policy_str = NULL;

                r = sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
                if (r >= 0)
                        fprintf(f, "%sCPUSchedulingPolicy: %s\n", prefix, policy_str);

                fprintf(f,
                        "%sCPUSchedulingPriority: %i\n"
                        "%sCPUSchedulingResetOnFork: %s\n",
                        prefix, c->cpu_sched_priority,
                        prefix, yes_no(c->cpu_sched_reset_on_fork));
        }

        if (c->cpuset) {
                fprintf(f, "%sCPUAffinity:", prefix);
                for (i = 0; i < c->cpuset_ncpus; i++)
                        if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
                                fprintf(f, " %u", i);
                fputs("\n", f);
        }

        if (c->timer_slack_nsec != NSEC_INFINITY)
                fprintf(f, "%sTimerSlackNSec: "NSEC_FMT "\n", prefix, c->timer_slack_nsec);

        fprintf(f,
                "%sStandardInput: %s\n"
                "%sStandardOutput: %s\n"
                "%sStandardError: %s\n",
                prefix, exec_input_to_string(c->std_input),
                prefix, exec_output_to_string(c->std_output),
                prefix, exec_output_to_string(c->std_error));

        if (c->std_input == EXEC_INPUT_NAMED_FD)
                fprintf(f, "%sStandardInputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDIN_FILENO]);
        if (c->std_output == EXEC_OUTPUT_NAMED_FD)
                fprintf(f, "%sStandardOutputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDOUT_FILENO]);
        if (c->std_error == EXEC_OUTPUT_NAMED_FD)
                fprintf(f, "%sStandardErrorFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDERR_FILENO]);

        if (c->std_input == EXEC_INPUT_FILE)
                fprintf(f, "%sStandardInputFile: %s\n", prefix, c->stdio_file[STDIN_FILENO]);
        if (c->std_output == EXEC_OUTPUT_FILE)
                fprintf(f, "%sStandardOutputFile: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
        if (c->std_output == EXEC_OUTPUT_FILE_APPEND)
                fprintf(f, "%sStandardOutputFileToAppend: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
        if (c->std_error == EXEC_OUTPUT_FILE)
                fprintf(f, "%sStandardErrorFile: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
        if (c->std_error == EXEC_OUTPUT_FILE_APPEND)
                fprintf(f, "%sStandardErrorFileToAppend: %s\n", prefix, c->stdio_file[STDERR_FILENO]);

        if (c->tty_path)
                fprintf(f,
                        "%sTTYPath: %s\n"
                        "%sTTYReset: %s\n"
                        "%sTTYVHangup: %s\n"
                        "%sTTYVTDisallocate: %s\n",
                        prefix, c->tty_path,
                        prefix, yes_no(c->tty_reset),
                        prefix, yes_no(c->tty_vhangup),
                        prefix, yes_no(c->tty_vt_disallocate));

        if (IN_SET(c->std_output,
                   EXEC_OUTPUT_SYSLOG,
                   EXEC_OUTPUT_KMSG,
                   EXEC_OUTPUT_JOURNAL,
                   EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
                   EXEC_OUTPUT_KMSG_AND_CONSOLE,
                   EXEC_OUTPUT_JOURNAL_AND_CONSOLE) ||
            IN_SET(c->std_error,
                   EXEC_OUTPUT_SYSLOG,
                   EXEC_OUTPUT_KMSG,
                   EXEC_OUTPUT_JOURNAL,
                   EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
                   EXEC_OUTPUT_KMSG_AND_CONSOLE,
                   EXEC_OUTPUT_JOURNAL_AND_CONSOLE)) {

                _cleanup_free_ char *fac_str = NULL, *lvl_str = NULL;

                r = log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
                if (r >= 0)
                        fprintf(f, "%sSyslogFacility: %s\n", prefix, fac_str);

                r = log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
                if (r >= 0)
                        fprintf(f, "%sSyslogLevel: %s\n", prefix, lvl_str);
        }

        if (c->log_level_max >= 0) {
                _cleanup_free_ char *t = NULL;

                (void) log_level_to_string_alloc(c->log_level_max, &t);

                fprintf(f, "%sLogLevelMax: %s\n", prefix, strna(t));
        }

        if (c->log_rate_limit_interval_usec > 0) {
                char buf_timespan[FORMAT_TIMESPAN_MAX];

                fprintf(f,
                        "%sLogRateLimitIntervalSec: %s\n",
                        prefix, format_timespan(buf_timespan, sizeof(buf_timespan), c->log_rate_limit_interval_usec, USEC_PER_SEC));
        }

        if (c->log_rate_limit_burst > 0)
                fprintf(f, "%sLogRateLimitBurst: %u\n", prefix, c->log_rate_limit_burst);

        if (c->n_log_extra_fields > 0) {
                size_t j;

                for (j = 0; j < c->n_log_extra_fields; j++) {
                        fprintf(f, "%sLogExtraFields: ", prefix);
                        fwrite(c->log_extra_fields[j].iov_base,
                               1, c->log_extra_fields[j].iov_len,
                               f);
                        fputc('\n', f);
                }
        }

        if (c->secure_bits) {
                _cleanup_free_ char *str = NULL;

                r = secure_bits_to_string_alloc(c->secure_bits, &str);
                if (r >= 0)
                        fprintf(f, "%sSecure Bits: %s\n", prefix, str);
        }

        if (c->capability_bounding_set != CAP_ALL) {
                _cleanup_free_ char *str = NULL;

                r = capability_set_to_string_alloc(c->capability_bounding_set, &str);
                if (r >= 0)
                        fprintf(f, "%sCapabilityBoundingSet: %s\n", prefix, str);
        }

        if (c->capability_ambient_set != 0) {
                _cleanup_free_ char *str = NULL;

                r = capability_set_to_string_alloc(c->capability_ambient_set, &str);
                if (r >= 0)
                        fprintf(f, "%sAmbientCapabilities: %s\n", prefix, str);
        }

        if (c->user)
                fprintf(f, "%sUser: %s\n", prefix, c->user);
        if (c->group)
                fprintf(f, "%sGroup: %s\n", prefix, c->group);

        fprintf(f, "%sDynamicUser: %s\n", prefix, yes_no(c->dynamic_user));

        if (!strv_isempty(c->supplementary_groups)) {
                fprintf(f, "%sSupplementaryGroups:", prefix);
                strv_fprintf(f, c->supplementary_groups);
                fputs("\n", f);
        }

        if (c->pam_name)
                fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);

        if (!strv_isempty(c->read_write_paths)) {
                fprintf(f, "%sReadWritePaths:", prefix);
                strv_fprintf(f, c->read_write_paths);
                fputs("\n", f);
        }

        if (!strv_isempty(c->read_only_paths)) {
                fprintf(f, "%sReadOnlyPaths:", prefix);
                strv_fprintf(f, c->read_only_paths);
                fputs("\n", f);
        }

        if (!strv_isempty(c->inaccessible_paths)) {
                fprintf(f, "%sInaccessiblePaths:", prefix);
                strv_fprintf(f, c->inaccessible_paths);
                fputs("\n", f);
        }

        if (c->n_bind_mounts > 0)
                for (i = 0; i < c->n_bind_mounts; i++)
                        fprintf(f, "%s%s: %s%s:%s:%s\n", prefix,
                                c->bind_mounts[i].read_only ? "BindReadOnlyPaths" : "BindPaths",
                                c->bind_mounts[i].ignore_enoent ? "-": "",
                                c->bind_mounts[i].source,
                                c->bind_mounts[i].destination,
                                c->bind_mounts[i].recursive ? "rbind" : "norbind");

        if (c->n_temporary_filesystems > 0)
                for (i = 0; i < c->n_temporary_filesystems; i++) {
                        TemporaryFileSystem *t = c->temporary_filesystems + i;

                        fprintf(f, "%sTemporaryFileSystem: %s%s%s\n", prefix,
                                t->path,
                                isempty(t->options) ? "" : ":",
                                strempty(t->options));
                }

        if (c->utmp_id)
                fprintf(f,
                        "%sUtmpIdentifier: %s\n",
                        prefix, c->utmp_id);

        if (c->selinux_context)
                fprintf(f,
                        "%sSELinuxContext: %s%s\n",
                        prefix, c->selinux_context_ignore ? "-" : "", c->selinux_context);

        if (c->apparmor_profile)
                fprintf(f,
                        "%sAppArmorProfile: %s%s\n",
                        prefix, c->apparmor_profile_ignore ? "-" : "", c->apparmor_profile);

        if (c->smack_process_label)
                fprintf(f,
                        "%sSmackProcessLabel: %s%s\n",
                        prefix, c->smack_process_label_ignore ? "-" : "", c->smack_process_label);

        if (c->personality != PERSONALITY_INVALID)
                fprintf(f,
                        "%sPersonality: %s\n",
                        prefix, strna(personality_to_string(c->personality)));

        fprintf(f,
                "%sLockPersonality: %s\n",
                prefix, yes_no(c->lock_personality));

        if (c->syscall_filter) {
#if HAVE_SECCOMP
                Iterator j;
                void *id, *val;
                bool first = true;
#endif

                fprintf(f,
                        "%sSystemCallFilter: ",
                        prefix);

                if (!c->syscall_whitelist)
                        fputc('~', f);

#if HAVE_SECCOMP
                HASHMAP_FOREACH_KEY(val, id, c->syscall_filter, j) {
                        _cleanup_free_ char *name = NULL;
                        const char *errno_name = NULL;
                        int num = PTR_TO_INT(val);

                        if (first)
                                first = false;
                        else
                                fputc(' ', f);

                        name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
                        fputs(strna(name), f);

                        if (num >= 0) {
                                errno_name = errno_to_name(num);
                                if (errno_name)
                                        fprintf(f, ":%s", errno_name);
                                else
                                        fprintf(f, ":%d", num);
                        }
                }
#endif

                fputc('\n', f);
        }

        if (c->syscall_archs) {
#if HAVE_SECCOMP
                Iterator j;
                void *id;
#endif

                fprintf(f,
                        "%sSystemCallArchitectures:",
                        prefix);

#if HAVE_SECCOMP
                SET_FOREACH(id, c->syscall_archs, j)
                        fprintf(f, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id) - 1)));
#endif
                fputc('\n', f);
        }

        if (exec_context_restrict_namespaces_set(c)) {
                _cleanup_free_ char *s = NULL;

                r = namespace_flags_to_string(c->restrict_namespaces, &s);
                if (r >= 0)
                        fprintf(f, "%sRestrictNamespaces: %s\n",
                                prefix, s);
        }

        if (c->network_namespace_path)
                fprintf(f,
                        "%sNetworkNamespacePath: %s\n",
                        prefix, c->network_namespace_path);

        if (c->syscall_errno > 0) {
                const char *errno_name;

                fprintf(f, "%sSystemCallErrorNumber: ", prefix);

                errno_name = errno_to_name(c->syscall_errno);
                if (errno_name)
                        fprintf(f, "%s\n", errno_name);
                else
                        fprintf(f, "%d\n", c->syscall_errno);
        }
}


static void Type_U16Fixed16_Free ( struct _cms_typehandler_struct * self , void * Ptr ) {
 _cmsFree ( self -> ContextID , Ptr ) ;
 }


int unit_patch_contexts(Unit *u) {
        CGroupContext *cc;
        ExecContext *ec;
        unsigned i;
        int r;

        assert(u);

        /* Patch in the manager defaults into the exec and cgroup
         * contexts, _after_ the rest of the settings have been
         * initialized */

        ec = unit_get_exec_context(u);
        if (ec) {
                /* This only copies in the ones that need memory */
                for (i = 0; i < _RLIMIT_MAX; i++)
                        if (u->manager->rlimit[i] && !ec->rlimit[i]) {
                                ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
                                if (!ec->rlimit[i])
                                        return -ENOMEM;
                        }

                if (MANAGER_IS_USER(u->manager) &&
                    !ec->working_directory) {

                        r = get_home_dir(&ec->working_directory);
                        if (r < 0)
                                return r;

                        /* Allow user services to run, even if the
                         * home directory is missing */
                        ec->working_directory_missing_ok = true;
                }

                if (ec->private_devices)
                        ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_MKNOD) | (UINT64_C(1) << CAP_SYS_RAWIO));

                if (ec->protect_kernel_modules)
                        ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYS_MODULE);

                if (ec->dynamic_user) {
                        if (!ec->user) {
                                r = user_from_unit_name(u, &ec->user);
                                if (r < 0)
                                        return r;
                        }

                        if (!ec->group) {
                                ec->group = strdup(ec->user);
                                if (!ec->group)
                                        return -ENOMEM;
                        }

                        /* If the dynamic user option is on, let's make sure that the unit can't leave its UID/GID
                         * around in the file system or on IPC objects. Hence enforce a strict sandbox. */

                        ec->private_tmp = true;
                        ec->remove_ipc = true;
                        ec->protect_system = PROTECT_SYSTEM_STRICT;
                        if (ec->protect_home == PROTECT_HOME_NO)
                                ec->protect_home = PROTECT_HOME_READ_ONLY;
                }
        }

        cc = unit_get_cgroup_context(u);
        if (cc && ec) {

                if (ec->private_devices &&
                    cc->device_policy == CGROUP_AUTO)
                        cc->device_policy = CGROUP_CLOSED;

                if (ec->root_image &&
                    (cc->device_policy != CGROUP_AUTO || cc->device_allow)) {

                        /* When RootImage= is specified, the following devices are touched. */
                        r = cgroup_add_device_allow(cc, "/dev/loop-control", "rw");
                        if (r < 0)
                                return r;

                        r = cgroup_add_device_allow(cc, "block-loop", "rwm");
                        if (r < 0)
                                return r;

                        r = cgroup_add_device_allow(cc, "block-blkext", "rwm");
                        if (r < 0)
                                return r;
                }
        }

        return 0;
}


static int bmp_decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; BMPContext *s = avctx->priv_data; AVFrame *picture = data; AVFrame *p = &s->picture; unsigned int fsize, hsize; int width, height; unsigned int depth; BiCompression comp; unsigned int ihsize; int i, j, n, linesize; uint32_t rgb[3]; uint32_t alpha = 0; uint8_t *ptr; int dsize; const uint8_t *buf0 = buf; GetByteContext gb; if(buf_size < 14){ av_log(avctx, AV_LOG_ERROR, "buf size too small (%d)\n", buf_size); return -1; } if(bytestream_get_byte(&buf) != 'B' || bytestream_get_byte(&buf) != 'M') { av_log(avctx, AV_LOG_ERROR, "bad magic number\n"); return -1; } fsize = bytestream_get_le32(&buf); if(buf_size < fsize){ av_log(avctx, AV_LOG_ERROR, "not enough data (%d < %d), trying to decode anyway\n", buf_size, fsize); fsize = buf_size; } buf += 2; /* reserved1 */ buf += 2; /* reserved2 */ hsize = bytestream_get_le32(&buf); /* header size */ ihsize = bytestream_get_le32(&buf); /* more header size */ if(ihsize + 14 > hsize){ av_log(avctx, AV_LOG_ERROR, "invalid header size %d\n", hsize); return -1; } /* sometimes file size is set to some headers size, set a real size in that case */ if(fsize == 14 || fsize == ihsize + 14) fsize = buf_size - 2; if(fsize <= hsize){ av_log(avctx, AV_LOG_ERROR, "declared file size is less than header size (%d < %d)\n", fsize, hsize); return -1; } switch(ihsize){ case 40: // windib case 56: // windib v3 case 64: // OS/2 v2 case 108: // windib v4 case 124: // windib v5 width = bytestream_get_le32(&buf); height = bytestream_get_le32(&buf); break; case 12: // OS/2 v1 width = bytestream_get_le16(&buf); height = bytestream_get_le16(&buf); break; default: av_log(avctx, AV_LOG_ERROR, "unsupported BMP file, patch welcome\n"); return -1; } if(bytestream_get_le16(&buf) != 1){ /* planes */ av_log(avctx, AV_LOG_ERROR, "invalid BMP header\n"); return -1; } depth = bytestream_get_le16(&buf); if (ihsize >= 40) comp = bytestream_get_le32(&buf); else comp = BMP_RGB; if(comp != BMP_RGB && comp != BMP_BITFIELDS && comp != BMP_RLE4 && comp != BMP_RLE8){ av_log(avctx, AV_LOG_ERROR, "BMP coding %d not supported\n", comp); return -1; } if(comp == BMP_BITFIELDS){ buf += 20; rgb[0] = bytestream_get_le32(&buf); rgb[1] = bytestream_get_le32(&buf); rgb[2] = bytestream_get_le32(&buf); alpha = bytestream_get_le32(&buf); } avctx->width = width; avctx->height = height > 0? height: -height; avctx->pix_fmt = AV_PIX_FMT_NONE; switch(depth){ case 32: if(comp == BMP_BITFIELDS){ if (rgb[0] == 0xFF000000 && rgb[1] == 0x00FF0000 && rgb[2] == 0x0000FF00) avctx->pix_fmt = alpha ? AV_PIX_FMT_ABGR : AV_PIX_FMT_0BGR; else if (rgb[0] == 0x00FF0000 && rgb[1] == 0x0000FF00 && rgb[2] == 0x000000FF) avctx->pix_fmt = alpha ? AV_PIX_FMT_BGRA : AV_PIX_FMT_BGR0; else if (rgb[0] == 0x0000FF00 && rgb[1] == 0x00FF0000 && rgb[2] == 0xFF000000) avctx->pix_fmt = alpha ? AV_PIX_FMT_ARGB : AV_PIX_FMT_0RGB; else if (rgb[0] == 0x000000FF && rgb[1] == 0x0000FF00 && rgb[2] == 0x00FF0000) avctx->pix_fmt = alpha ? AV_PIX_FMT_RGBA : AV_PIX_FMT_RGB0; else { av_log(avctx, AV_LOG_ERROR, "Unknown bitfields %0X %0X %0X\n", rgb[0], rgb[1], rgb[2]); return AVERROR(EINVAL); } } else { avctx->pix_fmt = AV_PIX_FMT_BGRA; } break; case 24: avctx->pix_fmt = AV_PIX_FMT_BGR24; break; case 16: if(comp == BMP_RGB) avctx->pix_fmt = AV_PIX_FMT_RGB555; else if (comp == BMP_BITFIELDS) { if (rgb[0] == 0xF800 && rgb[1] == 0x07E0 && rgb[2] == 0x001F) avctx->pix_fmt = AV_PIX_FMT_RGB565; else if (rgb[0] == 0x7C00 && rgb[1] == 0x03E0 && rgb[2] == 0x001F) avctx->pix_fmt = AV_PIX_FMT_RGB555; else if (rgb[0] == 0x0F00 && rgb[1] == 0x00F0 && rgb[2] == 0x000F) avctx->pix_fmt = AV_PIX_FMT_RGB444; else { av_log(avctx, AV_LOG_ERROR, "Unknown bitfields %0X %0X %0X\n", rgb[0], rgb[1], rgb[2]); return AVERROR(EINVAL); } } break; case 8: if(hsize - ihsize - 14 > 0) avctx->pix_fmt = AV_PIX_FMT_PAL8; else avctx->pix_fmt = AV_PIX_FMT_GRAY8; break; case 1: case 4: if(hsize - ihsize - 14 > 0){ avctx->pix_fmt = AV_PIX_FMT_PAL8; }else{ av_log(avctx, AV_LOG_ERROR, "Unknown palette for %d-colour BMP\n", 1<<depth); return -1; } break; default: av_log(avctx, AV_LOG_ERROR, "depth %d not supported\n", depth); return -1; } if(avctx->pix_fmt == AV_PIX_FMT_NONE){ av_log(avctx, AV_LOG_ERROR, "unsupported pixel format\n"); return -1; } if(p->data[0]) avctx->release_buffer(avctx, p); p->reference = 0; if(avctx->get_buffer(avctx, p) < 0){ av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return -1; } p->pict_type = AV_PICTURE_TYPE_I; p->key_frame = 1; buf = buf0 + hsize; dsize = buf_size - hsize; /* Line size in file multiple of 4 */ n = ((avctx->width * depth + 31) / 8) & ~3; if(n * avctx->height > dsize && comp != BMP_RLE4 && comp != BMP_RLE8){ av_log(avctx, AV_LOG_ERROR, "not enough data (%d < %d)\n", dsize, n * avctx->height); return -1; } // RLE may skip decoding some picture areas, so blank picture before decoding if(comp == BMP_RLE4 || comp == BMP_RLE8) memset(p->data[0], 0, avctx->height * p->linesize[0]); if(height > 0){ ptr = p->data[0] + (avctx->height - 1) * p->linesize[0]; linesize = -p->linesize[0]; } else { ptr = p->data[0]; linesize = p->linesize[0]; } if(avctx->pix_fmt == AV_PIX_FMT_PAL8){ int colors = 1 << depth; memset(p->data[1], 0, 1024); if(ihsize >= 36){ int t; buf = buf0 + 46; t = bytestream_get_le32(&buf); if(t < 0 || t > (1 << depth)){ av_log(avctx, AV_LOG_ERROR, "Incorrect number of colors - %X for bitdepth %d\n", t, depth); }else if(t){ colors = t; } } buf = buf0 + 14 + ihsize; //palette location if((hsize-ihsize-14) < (colors << 2)){ // OS/2 bitmap, 3 bytes per palette entry for(i = 0; i < colors; i++) ((uint32_t*)p->data[1])[i] = (0xff<<24) | bytestream_get_le24(&buf); }else{ for(i = 0; i < colors; i++) ((uint32_t*)p->data[1])[i] = 0xFFU << 24 | bytestream_get_le32(&buf); } buf = buf0 + hsize; } if(comp == BMP_RLE4 || comp == BMP_RLE8){ if(height < 0){ p->data[0] += p->linesize[0] * (avctx->height - 1); p->linesize[0] = -p->linesize[0]; } bytestream2_init(&gb, buf, dsize); ff_msrle_decode(avctx, (AVPicture*)p, depth, &gb); if(height < 0){ p->data[0] += p->linesize[0] * (avctx->height - 1); p->linesize[0] = -p->linesize[0]; } }else{ switch(depth){ case 1: for (i = 0; i < avctx->height; i++) { int j; for (j = 0; j < n; j++) { ptr[j*8+0] = buf[j] >> 7; ptr[j*8+1] = (buf[j] >> 6) & 1; ptr[j*8+2] = (buf[j] >> 5) & 1; ptr[j*8+3] = (buf[j] >> 4) & 1; ptr[j*8+4] = (buf[j] >> 3) & 1; ptr[j*8+5] = (buf[j] >> 2) & 1; ptr[j*8+6] = (buf[j] >> 1) & 1; ptr[j*8+7] = buf[j] & 1; } buf += n; ptr += linesize; } break; case 8: case 24: case 32: for(i = 0; i < avctx->height; i++){ memcpy(ptr, buf, n); buf += n; ptr += linesize; } break; case 4: for(i = 0; i < avctx->height; i++){ int j; for(j = 0; j < n; j++){ ptr[j*2+0] = (buf[j] >> 4) & 0xF; ptr[j*2+1] = buf[j] & 0xF; } buf += n; ptr += linesize; } break; case 16: for(i = 0; i < avctx->height; i++){ const uint16_t *src = (const uint16_t *) buf; uint16_t *dst = (uint16_t *) ptr; for(j = 0; j < avctx->width; j++) *dst++ = av_le2ne16(*src++); buf += n; ptr += linesize; } break; default: av_log(avctx, AV_LOG_ERROR, "BMP decoder is broken\n"); return -1; } } *picture = s->picture; *data_size = sizeof(AVPicture); return buf_size; }


void XMLRPC_CleanupValue(XMLRPC_VALUE value) {
   if(value) {
      if(value->iRefCount > 0) {
         value->iRefCount --;
      }

#ifdef XMLRPC_DEBUG_REFCOUNT
      if(value->id.str) {
			printf ("decremented refcount of %s, now %i\n", value->id.str,
					  value->iRefCount);
      }
      else {
			printf ("decremented refcount of 0x%x, now %i\n", value,
					  value->iRefCount);
      }
#endif

      if(value->type == xmlrpc_vector) {
         if(value->v) {
            if(value->iRefCount == 0) {
               XMLRPC_VALUE cur = (XMLRPC_VALUE)Q_Head(value->v->q);
               while( cur ) {
                  XMLRPC_CleanupValue(cur);

                  /* Make sure some idiot didn't include a vector as a child of itself
                   * and thus it would have already free'd these.
                   */
                  if(value->v && value->v->q) {
                     cur = Q_Next(value->v->q);
                  }
                  else {
                     break;
                  }
               }

               Q_Destroy(value->v->q);
               my_free(value->v->q);
               my_free(value->v);
            }
         }
      }

      if(value->iRefCount == 0) {

         /* guard against freeing invalid types */
         switch(value->type) {
            case xmlrpc_empty:
            case xmlrpc_base64:
            case xmlrpc_boolean:
            case xmlrpc_datetime:
            case xmlrpc_double:
            case xmlrpc_int:
            case xmlrpc_string:
            case xmlrpc_vector:
#ifdef XMLRPC_DEBUG_REFCOUNT
               if(value->id.str) {
                  printf("free'd %s\n", value->id.str);
               }
               else {
                  printf("free'd 0x%x\n", value);
               }
#endif
               simplestring_free(&value->id);
               simplestring_free(&value->str);

               memset(value, 0, sizeof(STRUCT_XMLRPC_VALUE));
               my_free(value);
               break;
            default:
				fprintf (stderr,
							"xmlrpc: attempted to free value of invalid type\n");
               break;
         }
      }
   }
}


static char * extract_string_until ( const char * original , const char * until_substring ) {
 char * result ;
 g_assert ( ( int ) strlen ( original ) >= until_substring - original ) ;
 g_assert ( until_substring - original >= 0 ) ;
 result = g_malloc ( until_substring - original + 1 ) ;
 strncpy ( result , original , until_substring - original ) ;
 result [ until_substring - original ] = '\0' ;
 return result ;
 }


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 ;
 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 ;
 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 rfbLog ( " other clients:\n" ) ;
 iterator = rfbGetClientIterator ( rfbScreen ) ;
 while ( ( cl_ = rfbClientIteratorNext ( iterator ) ) != NULL ) {
 rfbLog ( " %s\n" , cl_ -> host ) ;
 }
 rfbReleaseClientIterator ( iterator ) ;
 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 ;
 # 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_WITH_WEBSOCKETS if ( ! webSocketsCheck ( cl ) ) {
 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 ( 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 ;
 }


void HTML_put_string(HTStructured * me, const char *s)
{
#ifdef USE_PRETTYSRC
    char *translated_string = NULL;
#endif

    if (s == NULL || (LYMapsOnly && me->sp[0].tag_number != HTML_OBJECT))
	return;
#ifdef USE_PRETTYSRC
    if (psrc_convert_string) {
	StrAllocCopy(translated_string, s);
	TRANSLATE_AND_UNESCAPE_ENTITIES(&translated_string, TRUE, FALSE);
	s = (const char *) translated_string;
    }
#endif

    switch (me->sp[0].tag_number) {

    case HTML_COMMENT:
	break;			/* Do Nothing */

    case HTML_TITLE:
	HTChunkPuts(&me->title, s);
	break;

    case HTML_STYLE:
	HTChunkPuts(&me->style_block, s);
	break;

    case HTML_SCRIPT:
	HTChunkPuts(&me->script, s);
	break;

    case HTML_PRE:		/* Formatted text */
    case HTML_LISTING:		/* Literal text */
    case HTML_XMP:
    case HTML_PLAINTEXT:
	/*
	 * We guarantee that the style is up-to-date in begin_litteral
	 */
	HText_appendText(me->text, s);
	break;

    case HTML_OBJECT:
	HTChunkPuts(&me->object, s);
	break;

    case HTML_TEXTAREA:
	HTChunkPuts(&me->textarea, s);
	break;

    case HTML_SELECT:
    case HTML_OPTION:
	HTChunkPuts(&me->option, s);
	break;

    case HTML_MATH:
	HTChunkPuts(&me->math, s);
	break;

    default:			/* Free format text? */
	if (!me->sp->style->freeFormat) {
	    /*
	     * If we are within a preformatted text style not caught by the
	     * cases above (HTML_PRE or similar may not be the last element
	     * pushed on the style stack).  - kw
	     */
#ifdef USE_PRETTYSRC
	    if (psrc_view) {
		/*
		 * We do this so that a raw '\r' in the string will not be
		 * interpreted as an internal request to break a line - passing
		 * '\r' to HText_appendText is treated by it as a request to
		 * insert a blank line - VH
		 */
		for (; *s; ++s)
		    HTML_put_character(me, *s);
	    } else
#endif
		HText_appendText(me->text, s);
	    break;
	} else {
	    const char *p = s;
	    char c;

	    if (me->style_change) {
		for (; *p && ((*p == '\n') || (*p == '\r') ||
			      (*p == ' ') || (*p == '\t')); p++) ;	/* Ignore leaders */
		if (!*p)
		    break;
		UPDATE_STYLE;
	    }
	    for (; *p; p++) {
		if (*p == 13 && p[1] != 10) {
		    /*
		     * Treat any '\r' which is not followed by '\n' as '\n', to
		     * account for macintosh lineend in ALT attributes etc.  -
		     * kw
		     */
		    c = '\n';
		} else {
		    c = *p;
		}
		if (me->style_change) {
		    if ((c == '\n') || (c == ' ') || (c == '\t'))
			continue;	/* Ignore it */
		    UPDATE_STYLE;
		}
		if (c == '\n') {
		    if (!FIX_JAPANESE_SPACES) {
			if (me->in_word) {
			    if (HText_getLastChar(me->text) != ' ')
				HText_appendCharacter(me->text, ' ');
			    me->in_word = NO;
			}
		    }

		} else if (c == ' ' || c == '\t') {
		    if (HText_getLastChar(me->text) != ' ')
			HText_appendCharacter(me->text, ' ');

		} else if (c == '\r') {
		    /* ignore */
		} else {
		    HText_appendCharacter(me->text, c);
		    me->in_word = YES;
		}

		/* set the Last Character */
		if (c == '\n' || c == '\t') {
		    /* set it to a generic separator */
		    HText_setLastChar(me->text, ' ');
		} else if (c == '\r' &&
			   HText_getLastChar(me->text) == ' ') {
		    /*
		     * \r's are ignored.  In order to keep collapsing spaces
		     * correctly, we must default back to the previous
		     * separator, if there was one.  So we set LastChar to a
		     * generic separator.
		     */
		    HText_setLastChar(me->text, ' ');
		} else {
		    HText_setLastChar(me->text, c);
		}

	    }			/* for */
	}
    }				/* end switch */
#ifdef USE_PRETTYSRC
    if (psrc_convert_string) {
	psrc_convert_string = FALSE;
	FREE(translated_string);
    }
#endif
}


static bool mimefield_value_equal ( MIMEField * field , const char * value , const int value_len ) {
 int field_value_len = 0 ;
 const char * field_value = field -> value_get ( & field_value_len ) ;
 if ( field_value != nullptr && field_value_len == value_len ) {
 return ! strncasecmp ( field_value , value , value_len ) ;
 }
 return false ;
 }


host_name_lookup_byaddr(void)
{
struct hostent * hosts;
struct in_addr addr;
unsigned long time_msec = 0;	/* init to quieten dumb static analysis */

if (slow_lookup_log) time_msec = get_time_in_ms();

/* Lookup on IPv6 system */

#if HAVE_IPV6
if (Ustrchr(sender_host_address, ':') != NULL)
  {
  struct in6_addr addr6;
  if (inet_pton(AF_INET6, CS sender_host_address, &addr6) != 1)
    log_write(0, LOG_MAIN|LOG_PANIC_DIE, "unable to parse \"%s\" as an "
      "IPv6 address", sender_host_address);
  #if HAVE_GETIPNODEBYADDR
  hosts = getipnodebyaddr(CS &addr6, sizeof(addr6), AF_INET6, &h_errno);
  #else
  hosts = gethostbyaddr(CS &addr6, sizeof(addr6), AF_INET6);
  #endif
  }
else
  {
  if (inet_pton(AF_INET, CS sender_host_address, &addr) != 1)
    log_write(0, LOG_MAIN|LOG_PANIC_DIE, "unable to parse \"%s\" as an "
      "IPv4 address", sender_host_address);
  #if HAVE_GETIPNODEBYADDR
  hosts = getipnodebyaddr(CS &addr, sizeof(addr), AF_INET, &h_errno);
  #else
  hosts = gethostbyaddr(CS &addr, sizeof(addr), AF_INET);
  #endif
  }

/* Do lookup on IPv4 system */

#else
addr.s_addr = (S_ADDR_TYPE)inet_addr(CS sender_host_address);
hosts = gethostbyaddr(CS(&addr), sizeof(addr), AF_INET);
#endif

if (  slow_lookup_log
   && (time_msec = get_time_in_ms() - time_msec) > slow_lookup_log
   )
  log_long_lookup(US"gethostbyaddr", sender_host_address, time_msec);

/* Failed to look up the host. */

if (!hosts)
  {
  HDEBUG(D_host_lookup) debug_printf("IP address lookup failed: h_errno=%d\n",
    h_errno);
  return (h_errno == TRY_AGAIN || h_errno == NO_RECOVERY) ? DEFER : FAIL;
  }

/* It seems there are some records in the DNS that yield an empty name. We
treat this as non-existent. In some operating systems, this is returned as an
empty string; in others as a single dot. */

if (!hosts->h_name || !hosts->h_name[0] || hosts->h_name[0] == '.')
  {
  HDEBUG(D_host_lookup) debug_printf("IP address lookup yielded an empty name: "
    "treated as non-existent host name\n");
  return FAIL;
  }

/* Copy and lowercase the name, which is in static storage in many systems.
Put it in permanent memory. */

  {
  int old_pool = store_pool;
  store_pool = POOL_TAINT_PERM;		/* names are tainted */

  sender_host_name = string_copylc(US hosts->h_name);

  /* If the host has aliases, build a copy of the alias list */

  if (hosts->h_aliases)
    {
    int count = 1;
    uschar **ptr;

    for (uschar ** aliases = USS hosts->h_aliases; *aliases; aliases++) count++;
    store_pool = POOL_PERM;
    ptr = sender_host_aliases = store_get(count * sizeof(uschar *), FALSE);
    store_pool = POOL_TAINT_PERM;

    for (uschar ** aliases = USS hosts->h_aliases; *aliases; aliases++)
      *ptr++ = string_copylc(*aliases);
    *ptr = NULL;
    }
  store_pool = old_pool;
  }

return OK;
}


static void *build_pci_bus_begin(PCIBus *bus, void *parent_state) { AcpiBuildPciBusHotplugState *parent = parent_state; AcpiBuildPciBusHotplugState *child = g_malloc(sizeof *child); build_pci_bus_state_init(child, parent, parent->pcihp_bridge_en); return child; }


static unsigned long copy_strings(int argc,char ** argv,unsigned long *page, unsigned long p) { char *tmp, *tmp1, *pag = NULL; int len, offset = 0; if (!p) { return 0; /* bullet-proofing */ } while (argc-- > 0) { if (!(tmp1 = tmp = get_user(argv+argc))) { fprintf(stderr, "VFS: argc is wrong"); exit(-1); } while (get_user(tmp++)); len = tmp - tmp1; if (p < len) { /* this shouldn't happen - 128kB */ return 0; } while (len) { --p; --tmp; --len; if (--offset < 0) { offset = p % TARGET_PAGE_SIZE; pag = (char *) page[p/TARGET_PAGE_SIZE]; if (!pag) { pag = (char *)get_free_page(); page[p/TARGET_PAGE_SIZE] = (unsigned long)pag; if (!pag) return 0; } } if (len == 0 || offset == 0) { *(pag + offset) = get_user(tmp); } else { int bytes_to_copy = (len > offset) ? offset : len; tmp -= bytes_to_copy; p -= bytes_to_copy; offset -= bytes_to_copy; len -= bytes_to_copy; memcpy_fromfs(pag + offset, tmp, bytes_to_copy + 1); } } } return p; }


static void fast_any_to_alpha ( fz_context * ctx , fz_pixmap * dst , fz_pixmap * src , fz_colorspace * prf , const fz_default_colorspaces * default_cs , const fz_color_params * color_params , int copy_spots ) {
 assert ( copy_spots && dst -> s == 0 && src -> s == 0 ) ;
 if ( ! src -> alpha ) fz_clear_pixmap_with_value ( ctx , dst , 255 ) ;
 else {
 unsigned char * s = src -> samples ;
 unsigned char * d = dst -> samples ;
 size_t w = src -> w ;
 int h = src -> h ;
 int n = src -> n ;
 ptrdiff_t d_line_inc = dst -> stride - w * dst -> n ;
 ptrdiff_t s_line_inc = src -> stride - w * src -> n ;
 if ( ( int ) w < 0 || h < 0 ) return ;
 assert ( dst -> alpha && src -> alpha && dst -> n == 1 ) ;
 if ( d_line_inc == 0 && s_line_inc == 0 ) {
 w *= h ;
 h = 1 ;
 }
 s += n - 1 ;
 while ( h -- ) {
 size_t ww = w ;
 while ( ww -- ) {
 * d ++ = * s ;
 s += n ;
 }
 d += d_line_inc ;
 s += s_line_inc ;
 }
 }
 }


_WM_ParseNewMidi(uint8_t *midi_data, uint32_t midi_size) {
    struct _mdi *mdi;

    uint32_t tmp_val;
    uint32_t midi_type;
    uint8_t **tracks;
    uint32_t *track_size;
    uint32_t end_of_tracks = 0;
    uint32_t no_tracks;
    uint32_t i;
    uint32_t divisions = 96;
    uint32_t tempo = 500000;
    float samples_per_delta_f = 0.0;

    uint32_t sample_count = 0;
    float sample_count_f = 0.0;
    float sample_remainder = 0.0;
    uint8_t *sysex_store = NULL;

    uint32_t *track_delta;
    uint8_t *track_end;
    uint32_t smallest_delta = 0;
    uint32_t subtract_delta = 0;
    uint8_t *running_event;
    uint32_t setup_ret = 0;

    if (midi_size < 14) {
        _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
        return (NULL);
    }

    if (!memcmp(midi_data, "RIFF", 4)) {
        if (midi_size < 34) {
            _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
            return (NULL);
        }
        midi_data += 20;
        midi_size -= 20;
    }

    if (memcmp(midi_data, "MThd", 4)) {
        _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MIDI, NULL, 0);
        return (NULL);
    }
    midi_data += 4;
    midi_size -= 4;

    /*
     * Get Midi Header Size - must always be 6
     */
    tmp_val = *midi_data++ << 24;
    tmp_val |= *midi_data++ << 16;
    tmp_val |= *midi_data++ << 8;
    tmp_val |= *midi_data++;
    midi_size -= 4;
    if (tmp_val != 6) {
        _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, NULL, 0);
        return (NULL);
    }

    /*
     * Get Midi Format - we only support 0, 1 & 2
     */
    tmp_val = *midi_data++ << 8;
    tmp_val |= *midi_data++;
    midi_size -= 2;
    if (tmp_val > 2) {
        _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, NULL, 0);
        return (NULL);
    }
    midi_type = tmp_val;

    /*
     * Get No. of Tracks
     */
    tmp_val = *midi_data++ << 8;
    tmp_val |= *midi_data++;
    midi_size -= 2;
    if (tmp_val < 1) {
        _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(no tracks)", 0);
        return (NULL);
    }
    no_tracks = tmp_val;

    /*
     * Check that type 0 midi file has only 1 track
     */
    if ((midi_type == 0) && (no_tracks > 1)) {
        _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, "(expected 1 track for type 0 midi file, found more)", 0);
        return (NULL);
    }

    /*
     * Get Divisions
     */
    divisions = *midi_data++ << 8;
    divisions |= *midi_data++;
    midi_size -= 2;
    if (divisions & 0x00008000) {
        _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, NULL, 0);
        return (NULL);
    }

    samples_per_delta_f = _WM_GetSamplesPerTick(divisions, tempo);

    mdi = _WM_initMDI();
    _WM_midi_setup_divisions(mdi,divisions);

    tracks = malloc(sizeof(uint8_t *) * no_tracks);
    track_size = malloc(sizeof(uint32_t) * no_tracks);
    track_delta = malloc(sizeof(uint32_t) * no_tracks);
    track_end = malloc(sizeof(uint8_t) * no_tracks);
    running_event = malloc(sizeof(uint8_t) * no_tracks);

    smallest_delta = 0xffffffff;
    for (i = 0; i < no_tracks; i++) {
        if (midi_size < 8) {
            _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
            goto _end;
        }
        if (memcmp(midi_data, "MTrk", 4) != 0) {
            _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(missing track header)", 0);
            goto _end;
        }
        midi_data += 4;
        midi_size -= 4;

        /* track size */
        tmp_val = *midi_data++ << 24;
        tmp_val |= *midi_data++ << 16;
        tmp_val |= *midi_data++ << 8;
        tmp_val |= *midi_data++;
        midi_size -= 4;
        if (midi_size < tmp_val) {
            _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
            goto _end;
        }
        if (tmp_val < 3) {
            _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(bad track size)", 0);
            goto _end;
        }
        if ((midi_data[tmp_val - 3] != 0xFF)
                || (midi_data[tmp_val - 2] != 0x2F)
                || (midi_data[tmp_val - 1] != 0x00)) {
            _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(missing EOT)", 0);
            goto _end;
        }
        tracks[i] = midi_data;
        track_size[i] = tmp_val;
        midi_data += tmp_val;
        midi_size -= tmp_val;
        track_end[i] = 0;
        running_event[i] = 0;
        track_delta[i] = 0;

        while (*tracks[i] > 0x7F) {
            track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F);
            tracks[i]++;
            track_size[i]--;
        }
        track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F);
        tracks[i]++;
        track_size[i]--;

        if (midi_type == 1 ) {
            if (track_delta[i] < smallest_delta) {
                smallest_delta = track_delta[i];
            }
        } else {
            /*
             * Type 0 & 2 midi only needs delta from 1st track
             * for initial sample calculations.
             */
            if (i == 0) smallest_delta = track_delta[i];
        }
    }

    subtract_delta = smallest_delta;
    sample_count_f = (((float) smallest_delta * samples_per_delta_f) + sample_remainder);
    sample_count = (uint32_t) sample_count_f;
    sample_remainder = sample_count_f - (float) sample_count;

    mdi->events[mdi->event_count - 1].samples_to_next += sample_count;
    mdi->extra_info.approx_total_samples += sample_count;

    /*
     * Handle type 0 & 2 the same, but type 1 differently
     */
    if (midi_type == 1) {
        /* Type 1 */
        while (end_of_tracks != no_tracks) {
            smallest_delta = 0;
            for (i = 0; i < no_tracks; i++) {
                if (track_end[i])
                    continue;
                if (track_delta[i]) {
                    track_delta[i] -= subtract_delta;
                    if (track_delta[i]) {
                        if ((!smallest_delta)
                             || (smallest_delta > track_delta[i])) {
                            smallest_delta = track_delta[i];
                        }
                        continue;
                    }
                }
                do {
                    setup_ret = _WM_SetupMidiEvent(mdi, tracks[i], track_size[i], running_event[i]);
                    if (setup_ret == 0) {
                        goto _end;
                    }
                    if (tracks[i][0] > 0x7f) {
                        if (tracks[i][0] < 0xf0) {
                            /* Events 0x80 - 0xef set running event */
                            running_event[i] = tracks[i][0];
                        } else if ((tracks[i][0] == 0xf0) || (tracks[i][0] == 0xf7)) {
                            /* Sysex resets running event */
                            running_event[i] = 0;
                        } else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x2f) && (tracks[i][2] == 0x00)) {
                            /* End of Track */
                            end_of_tracks++;
                            track_end[i] = 1;
                            tracks[i] += 3;
                            track_size[i] -= 3;
                            goto NEXT_TRACK;
                        } else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x51) && (tracks[i][2] == 0x03)) {
                            /* Tempo */
                            tempo = (tracks[i][3] << 16) + (tracks[i][4] << 8)+ tracks[i][5];
                            if (!tempo)
                                tempo = 500000;

                            samples_per_delta_f = _WM_GetSamplesPerTick(divisions, tempo);
                        }
                    }
                    tracks[i] += setup_ret;
                    track_size[i] -= setup_ret;

                    if (*tracks[i] > 0x7f) {
                        do {
                            if (!track_size[i]) break;
                            track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F);
                            tracks[i]++;
                            track_size[i]--;
                        } while (*tracks[i] > 0x7f);
                    }
                    if (!track_size[i]) {
                        _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
                        goto _end;
                    }
                    track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F);
                    tracks[i]++;
                    track_size[i]--;
                } while (!track_delta[i]);
                if ((!smallest_delta) || (smallest_delta > track_delta[i])) {
                    smallest_delta = track_delta[i];
                }
            NEXT_TRACK: continue;
            }

            subtract_delta = smallest_delta;
            sample_count_f = (((float) smallest_delta * samples_per_delta_f)
                              + sample_remainder);
            sample_count = (uint32_t) sample_count_f;
            sample_remainder = sample_count_f - (float) sample_count;

            mdi->events[mdi->event_count - 1].samples_to_next += sample_count;
            mdi->extra_info.approx_total_samples += sample_count;
        }
    } else {
        /* Type 0 & 2 */
        if (midi_type == 2) {
            mdi->is_type2 = 1;
        }
        sample_remainder = 0.0;
        for (i = 0; i < no_tracks; i++) {
            running_event[i] = 0;
            do {
                setup_ret = _WM_SetupMidiEvent(mdi, tracks[i], track_size[i], running_event[i]);
                if (setup_ret == 0) {
                    goto _end;
                }
                if (tracks[i][0] > 0x7f) {
                    if (tracks[i][0] < 0xf0) {
                        /* Events 0x80 - 0xef set running event */
                        running_event[i] = tracks[i][0];
                    } else if ((tracks[i][0] == 0xf0) || (tracks[i][0] == 0xf7)) {
                        /* Sysex resets running event */
                        running_event[i] = 0;
                    } else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x2f) && (tracks[i][2] == 0x00)) {
                        /* End of Track */
                        track_end[i] = 1;
                        goto NEXT_TRACK2;
                    } else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x51) && (tracks[i][2] == 0x03)) {
                        /* Tempo */
                        tempo = (tracks[i][3] << 16) + (tracks[i][4] << 8)+ tracks[i][5];
                        if (!tempo)
                            tempo = 500000;

                        samples_per_delta_f = _WM_GetSamplesPerTick(divisions, tempo);
                    }
                }
                tracks[i] += setup_ret;
                track_size[i] -= setup_ret;

                track_delta[i] = 0;
                if (*tracks[i] > 0x7f) {
                    do {
                        if (!track_size[i]) break;
                        track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F);
                        tracks[i]++;
                        track_size[i]--;
                    } while (*tracks[i] > 0x7f);
                }
                if (!track_size[i]) {
                    _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
                    goto _end;
                }
                track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F);
                tracks[i]++;
                track_size[i]--;

                sample_count_f = (((float) track_delta[i] * samples_per_delta_f)
                                  + sample_remainder);
                sample_count = (uint32_t) sample_count_f;
                sample_remainder = sample_count_f - (float) sample_count;
                mdi->events[mdi->event_count - 1].samples_to_next += sample_count;
                mdi->extra_info.approx_total_samples += sample_count;
            NEXT_TRACK2:
                smallest_delta = track_delta[i]; /* Added just to keep Xcode happy */
                UNUSED(smallest_delta); /* Added to just keep clang happy */
            } while (track_end[i] == 0);
        }
    }

    if ((mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width,
            _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy))
          == NULL) {
        _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0);
        goto _end;
    }

    mdi->extra_info.current_sample = 0;
    mdi->current_event = &mdi->events[0];
    mdi->samples_to_mix = 0;
    mdi->note = NULL;

    _WM_ResetToStart(mdi);

_end:   free(sysex_store);
    free(track_end);
    free(track_delta);
    free(running_event);
    free(tracks);
    free(track_size);
    if (mdi->reverb) return (mdi);
    _WM_freeMDI(mdi);
    return (NULL);
}


static void pdf_run_rg ( fz_context * ctx , pdf_processor * proc , float r , float g , float b ) {
 pdf_run_processor * pr = ( pdf_run_processor * ) proc ;
 float color [ 3 ] = {
 r , g , b }
 ;
 pr -> dev -> flags &= ~ FZ_DEVFLAG_FILLCOLOR_UNDEFINED ;
 pdf_set_colorspace ( ctx , pr , PDF_FILL , fz_device_rgb ( ctx ) ) ;
 pdf_set_color ( ctx , pr , PDF_FILL , color ) ;
 }


uint32_t _WM_SetupMidiEvent(struct _mdi *mdi, uint8_t * event_data, uint8_t running_event) {
    /*
     Only add standard MIDI and Sysex events in here.
     Non-standard events need to be handled by calling function
     to avoid compatibility issues.

     TODO:
     Add value limit checks
     */
    uint32_t ret_cnt = 0;
    uint8_t command = 0;
    uint8_t channel = 0;
    uint8_t data_1 = 0;
    uint8_t data_2 = 0;
    char *text = NULL;

    if (event_data[0] >= 0x80) {
        command = *event_data & 0xf0;
        channel = *event_data++ & 0x0f;
        ret_cnt++;
    } else {
        command = running_event & 0xf0;
        channel = running_event & 0x0f;
    }

    switch(command) {
        case 0x80:
        _SETUP_NOTEOFF:
            data_1 = *event_data++;
            data_2 = *event_data++;
            _WM_midi_setup_noteoff(mdi, channel, data_1, data_2);
            ret_cnt += 2;
            break;
        case 0x90:
            if (event_data[1] == 0) goto _SETUP_NOTEOFF; /* A velocity of 0 in a note on is actually a note off */
            data_1 = *event_data++;
            data_2 = *event_data++;
            midi_setup_noteon(mdi, channel, data_1, data_2);
            ret_cnt += 2;
            break;
        case 0xa0:
            data_1 = *event_data++;
            data_2 = *event_data++;
            midi_setup_aftertouch(mdi, channel, data_1, data_2);
            ret_cnt += 2;
            break;
        case 0xb0:
            data_1 = *event_data++;
            data_2 = *event_data++;
            midi_setup_control(mdi, channel, data_1, data_2);
            ret_cnt += 2;
            break;
        case 0xc0:
            data_1 = *event_data++;
            midi_setup_patch(mdi, channel, data_1);
            ret_cnt++;
            break;
        case 0xd0:
            data_1 = *event_data++;
            midi_setup_channel_pressure(mdi, channel, data_1);
            ret_cnt++;
            break;
        case 0xe0:
            data_1 = *event_data++;
            data_2 = *event_data++;
            midi_setup_pitch(mdi, channel, ((data_2 << 7) | (data_1 & 0x7f)));
            ret_cnt += 2;
            break;
        case 0xf0:
            if (channel == 0x0f) {
                /*
                 MIDI Meta Events
                 */
                uint32_t tmp_length = 0;
                if ((event_data[0] == 0x00) && (event_data[1] == 0x02)) {
                    /*
                     Sequence Number
                     We only setting this up here for WM_Event2Midi function
                     */
                    midi_setup_sequenceno(mdi, ((event_data[2] << 8) + event_data[3]));
                    ret_cnt += 4;
                } else if (event_data[0] == 0x01) {
                    /* Text Event */
                    /* Get Length */
                    event_data++;
                    ret_cnt++;
                    if (*event_data > 0x7f) {
                        do {
                            tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                            event_data++;
                            ret_cnt++;
                        } while (*event_data > 0x7f);
                    }
                    tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                    event_data++;
                    ret_cnt++;

                    text = malloc(tmp_length + 1);
                    memcpy(text, event_data, tmp_length);
                    text[tmp_length] = '\0';
                    midi_setup_text(mdi, text);

                    ret_cnt += tmp_length;

                } else if (event_data[0] == 0x02) {
                    /* Copyright Event */
                    /* Get Length */
                    event_data++;
                    ret_cnt++;
                    if (*event_data > 0x7f) {
                        do {
                            tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                            event_data++;
                            ret_cnt++;
                        } while (*event_data > 0x7f);
                    }
                    tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                    event_data++;
                    ret_cnt++;

                    /* Copy copyright info in the getinfo struct */
                    if (mdi->extra_info.copyright) {
                        mdi->extra_info.copyright = realloc(mdi->extra_info.copyright,(strlen(mdi->extra_info.copyright) + 1 + tmp_length + 1));
                        memcpy(&mdi->extra_info.copyright[strlen(mdi->extra_info.copyright) + 1], event_data, tmp_length);
                        mdi->extra_info.copyright[strlen(mdi->extra_info.copyright) + 1 + tmp_length] = '\0';
                        mdi->extra_info.copyright[strlen(mdi->extra_info.copyright)] = '\n';
                    } else {
                        mdi->extra_info.copyright = malloc(tmp_length + 1);
                        memcpy(mdi->extra_info.copyright, event_data, tmp_length);
                        mdi->extra_info.copyright[tmp_length] = '\0';
                    }

                    /* NOTE: free'd when events are cleared during closure of mdi */
                    text = malloc(tmp_length + 1);
                    memcpy(text, event_data, tmp_length);
                    text[tmp_length] = '\0';
                    midi_setup_copyright(mdi, text);

                    ret_cnt += tmp_length;

                } else if (event_data[0] == 0x03) {
                    /* Track Name Event */
                    /* Get Length */
                    event_data++;
                    ret_cnt++;
                    if (*event_data > 0x7f) {
                        do {
                            tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                            event_data++;
                            ret_cnt++;
                        } while (*event_data > 0x7f);
                    }
                    tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                    event_data++;
                    ret_cnt++;

                    text = malloc(tmp_length + 1);
                    memcpy(text, event_data, tmp_length);
                    text[tmp_length] = '\0';
                    midi_setup_trackname(mdi, text);

                    ret_cnt += tmp_length;

                } else if (event_data[0] == 0x04) {
                    /* Instrument Name Event */
                    /* Get Length */
                    event_data++;
                    ret_cnt++;
                    if (*event_data > 0x7f) {
                        do {
                            tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                            event_data++;
                            ret_cnt++;
                        } while (*event_data > 0x7f);
                    }
                    tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                    event_data++;
                    ret_cnt++;

                    text = malloc(tmp_length + 1);
                    memcpy(text, event_data, tmp_length);
                    text[tmp_length] = '\0';
                    midi_setup_instrumentname(mdi, text);

                    ret_cnt += tmp_length;

                } else if (event_data[0] == 0x05) {
                    /* Lyric Event */
                    /* Get Length */
                    event_data++;
                    ret_cnt++;
                    if (*event_data > 0x7f) {
                        do {
                            tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                            event_data++;
                            ret_cnt++;
                        } while (*event_data > 0x7f);
                    }
                    tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                    event_data++;
                    ret_cnt++;

                    text = malloc(tmp_length + 1);
                    memcpy(text, event_data, tmp_length);
                    text[tmp_length] = '\0';
                    midi_setup_lyric(mdi, text);

                    ret_cnt += tmp_length;

                } else if (event_data[0] == 0x06) {
                    /* Marker Event */
                    /* Get Length */
                    event_data++;
                    ret_cnt++;
                    if (*event_data > 0x7f) {
                        do {
                            tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                            event_data++;
                            ret_cnt++;
                        } while (*event_data > 0x7f);
                    }
                    tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                    event_data++;
                    ret_cnt++;

                    text = malloc(tmp_length + 1);
                    memcpy(text, event_data, tmp_length);
                    text[tmp_length] = '\0';
                    midi_setup_marker(mdi, text);

                    ret_cnt += tmp_length;

                } else if (event_data[0] == 0x07) {
                    /* Cue Point Event */
                    /* Get Length */
                    event_data++;
                    ret_cnt++;
                    if (*event_data > 0x7f) {
                        do {
                            tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                            event_data++;
                            ret_cnt++;
                        } while (*event_data > 0x7f);
                    }
                    tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                    event_data++;
                    ret_cnt++;

                    text = malloc(tmp_length + 1);
                    memcpy(text, event_data, tmp_length);
                    text[tmp_length] = '\0';
                    midi_setup_cuepoint(mdi, text);

                    ret_cnt += tmp_length;

                } else if ((event_data[0] == 0x20) && (event_data[1] == 0x01)) {
                    /*
                     Channel Prefix
                     We only setting this up here for WM_Event2Midi function
                     */
                    midi_setup_channelprefix(mdi, event_data[2]);
                    ret_cnt += 3;
                } else if ((event_data[0] == 0x21) && (event_data[1] == 0x01)) {
                    /*
                     Port Prefix
                     We only setting this up here for WM_Event2Midi function
                     */
                    midi_setup_portprefix(mdi, event_data[2]);
                    ret_cnt += 3;
                } else if ((event_data[0] == 0x2F) && (event_data[1] == 0x00)) {
                    /*
                     End of Track
                     Deal with this inside calling function
                     We only setting this up here for _WM_Event2Midi function
                     */
                    _WM_midi_setup_endoftrack(mdi);
                    ret_cnt += 2;
                } else if ((event_data[0] == 0x51) && (event_data[1] == 0x03)) {
                    /*
                     Tempo
                     Deal with this inside calling function.
                     We only setting this up here for _WM_Event2Midi function
                     */
                    _WM_midi_setup_tempo(mdi, ((event_data[2] << 16) + (event_data[3] << 8) + event_data[4]));
                    ret_cnt += 5;
                } else if ((event_data[0] == 0x54) && (event_data[1] == 0x05)) {
                    /*
                     SMPTE Offset
                     We only setting this up here for WM_Event2Midi function
                     */
                    midi_setup_smpteoffset(mdi, ((event_data[3] << 24) + (event_data[4] << 16) + (event_data[5] << 8) + event_data[6]));

                    /*
                     Because this has 5 bytes of data we gonna "hack" it a little
                     */
                    mdi->events[mdi->events_size - 1].event_data.channel = event_data[2];

                    ret_cnt += 7;
                } else if ((event_data[0] == 0x58) && (event_data[1] == 0x04)) {
                    /*
                     Time Signature
                     We only setting this up here for WM_Event2Midi function
                     */
                    midi_setup_timesignature(mdi, ((event_data[2] << 24) + (event_data[3] << 16) + (event_data[4] << 8) + event_data[5]));
                    ret_cnt += 6;
                } else if ((event_data[0] == 0x59) && (event_data[1] == 0x02)) {
                    /*
                     Key Signature
                     We only setting this up here for WM_Event2Midi function
                     */
                    midi_setup_keysignature(mdi, ((event_data[2] << 8) + event_data[3]));
                    ret_cnt += 4;
                } else {
                    /*
                     Unsupported Meta Event
                     */
                    event_data++;
                    ret_cnt++;
                    if (*event_data > 0x7f) {
                        do {
                            tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                            event_data++;
                            ret_cnt++;
                        } while (*event_data > 0x7f);
                    }
                    tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
                    ret_cnt++;
                    ret_cnt += tmp_length;
                }

            } else if ((channel == 0) || (channel == 7)) {
                /*
                 Sysex Events
                 */
                uint32_t sysex_len = 0;
                uint8_t *sysex_store = NULL;

                if (*event_data > 0x7f) {
                    do {
                        sysex_len = (sysex_len << 7) + (*event_data & 0x7F);
                        event_data++;
                        ret_cnt++;
                    } while (*event_data > 0x7f);
                }
                sysex_len = (sysex_len << 7) + (*event_data & 0x7F);
                event_data++;
                if (!sysex_len) break;
                ret_cnt++;

                sysex_store = malloc(sizeof(uint8_t) * sysex_len);
                memcpy(sysex_store, event_data, sysex_len);

                if (sysex_store[sysex_len - 1] == 0xF7) {
                    uint8_t rolandsysexid[] = { 0x41, 0x10, 0x42, 0x12 };
                    if (memcmp(rolandsysexid, sysex_store, 4) == 0) {
                        /* For Roland Sysex Messages */
                        /* checksum */
                        uint8_t sysex_cs = 0;
                        uint32_t sysex_ofs = 4;
                        do {
                            sysex_cs += sysex_store[sysex_ofs];
                            if (sysex_cs > 0x7F) {
                                sysex_cs -= 0x80;
                            }
                            sysex_ofs++;
                        } while (sysex_store[sysex_ofs + 1] != 0xf7);
                        sysex_cs = 128 - sysex_cs;
                        /* is roland sysex message valid */
                        if (sysex_cs == sysex_store[sysex_ofs]) {
                            /* process roland sysex event */
                            if (sysex_store[4] == 0x40) {
                                if (((sysex_store[5] & 0xf0) == 0x10) && (sysex_store[6] == 0x15)) {
                                    /* Roland Drum Track Setting */
                                    uint8_t sysex_ch = 0x0f & sysex_store[5];
                                    if (sysex_ch == 0x00) {
                                        sysex_ch = 0x09;
                                    } else if (sysex_ch <= 0x09) {
                                        sysex_ch -= 1;
                                    }
                                    midi_setup_sysex_roland_drum_track(mdi, sysex_ch, sysex_store[7]);
                                } else if ((sysex_store[5] == 0x00) && (sysex_store[6] == 0x7F) && (sysex_store[7] == 0x00)) {
                                    /* Roland GS Reset */
                                    midi_setup_sysex_roland_reset(mdi);
                                }
                            }
                        }
                    } else {
                        /* For non-Roland Sysex Messages */
                        uint8_t gm_reset[] = {0x7e, 0x7f, 0x09, 0x01, 0xf7};
                        uint8_t yamaha_reset[] = {0x43, 0x10, 0x4c, 0x00, 0x00, 0x7e, 0x00, 0xf7};

                        if (memcmp(gm_reset, sysex_store, 5) == 0) {
                            /* GM Reset */
                            midi_setup_sysex_gm_reset(mdi);
                        } else if (memcmp(yamaha_reset,sysex_store,8) == 0) {
                            /* Yamaha Reset */
                            midi_setup_sysex_yamaha_reset(mdi);
                        }
                    }
                }
                free(sysex_store);
                sysex_store = NULL;
                /*
                event_data += sysex_len;
                */
                ret_cnt += sysex_len;
            } else {
                _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(unrecognized meta type event)", 0);
                return 0;
            }
            break;

        default: /* Should NEVER get here */
            ret_cnt = 0;
            break;
    }
    if (ret_cnt == 0)
        _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(missing event)", 0);
    return ret_cnt;
}


int wpa_generate_PTK ( u_char * bssid , u_char * sta , u_char * pmk , u_char * snonce , u_char * anonce , u_int16 bits , u_char * kck ) {
 u_int8 i ;
 u_int len ;
 u_char buff [ 100 ] ;
 size_t offset = sizeof ( "Pairwise key expansion" ) ;
 memset ( buff , 0 , 100 ) ;
 memcpy ( buff , "Pairwise key expansion" , offset ) ;
 if ( memcmp ( sta , bssid , ETH_ADDR_LEN ) < 0 ) {
 memcpy ( buff + offset , sta , ETH_ADDR_LEN ) ;
 memcpy ( buff + offset + ETH_ADDR_LEN , bssid , ETH_ADDR_LEN ) ;
 }
 else {
 memcpy ( buff + offset , bssid , ETH_ADDR_LEN ) ;
 memcpy ( buff + offset + ETH_ADDR_LEN , sta , ETH_ADDR_LEN ) ;
 }
 offset += ETH_ADDR_LEN * 2 ;
 if ( memcmp ( snonce , anonce , WPA_NONCE_LEN ) < 0 ) {
 memcpy ( buff + offset , snonce , WPA_NONCE_LEN ) ;
 memcpy ( buff + offset + WPA_NONCE_LEN , anonce , WPA_NONCE_LEN ) ;
 }
 else {
 memcpy ( buff + offset , anonce , WPA_NONCE_LEN ) ;
 memcpy ( buff + offset + WPA_NONCE_LEN , snonce , WPA_NONCE_LEN ) ;
 }
 offset += WPA_NONCE_LEN * 2 ;
 memset ( kck , 0 , WPA_PTK_LEN ) ;
 for ( i = 0 ;
 i < ( bits + 159 ) / 160 ;
 i ++ ) {
 buff [ offset ] = i ;
 HMAC ( EVP_sha1 ( ) , pmk , WPA_KEY_LEN , buff , 100 , kck + i * 20 , & len ) ;
 }
 return E_SUCCESS ;
 }


qio_channel_socket_accept(QIOChannelSocket *ioc, Error **errp) { QIOChannelSocket *cioc; cioc = qio_channel_socket_new(); cioc->remoteAddrLen = sizeof(ioc->remoteAddr); cioc->localAddrLen = sizeof(ioc->localAddr); retry: trace_qio_channel_socket_accept(ioc); cioc->fd = qemu_accept(ioc->fd, (struct sockaddr *)&cioc->remoteAddr, &cioc->remoteAddrLen); if (cioc->fd < 0) { trace_qio_channel_socket_accept_fail(ioc); if (errno == EINTR) { goto retry; } goto error; } if (getsockname(cioc->fd, (struct sockaddr *)&cioc->localAddr, &cioc->localAddrLen) < 0) { error_setg_errno(errp, errno, "Unable to query local socket address"); goto error; } #ifndef WIN32 if (cioc->localAddr.ss_family == AF_UNIX) { QIOChannel *ioc_local = QIO_CHANNEL(cioc); qio_channel_set_feature(ioc_local, QIO_CHANNEL_FEATURE_FD_PASS); } #endif /* WIN32 */ trace_qio_channel_socket_accept_complete(ioc, cioc, cioc->fd); return cioc; error: object_unref(OBJECT(cioc)); return NULL; }


int RefDepth ( RefChar * ref , int layer ) {
 int rd , temp ;
 SplineChar * sc = ref -> sc ;
 if ( sc -> layers [ layer ] . refs == NULL || sc -> layers [ layer ] . splines != NULL ) return ( 1 ) ;
 rd = 0 ;
 for ( ref = sc -> layers [ layer ] . refs ;
 ref != NULL ;
 ref = ref -> next ) {
 if ( ref -> transform [ 0 ] >= - 2 || ref -> transform [ 0 ] <= 1.999939 || ref -> transform [ 1 ] >= - 2 || ref -> transform [ 1 ] <= 1.999939 || ref -> transform [ 2 ] >= - 2 || ref -> transform [ 2 ] <= 1.999939 || ref -> transform [ 3 ] >= - 2 || ref -> transform [ 3 ] <= 1.999939 ) {
 temp = RefDepth ( ref , layer ) ;
 if ( temp > rd ) rd = temp ;
 }
 }
 return ( rd + 1 ) ;
 }